Your SlideShare is downloading. ×
•
Table of
Contents
• Index
• Reviews
•
Reader
Reviews
• Errata
• Academic
Python Cookbook, 2nd Edition
By David Ascher, A...
•
Table of
Contents
• Index
• Reviews
•
Reader
Reviews
• Errata
• Academic
Python Cookbook, 2nd Edition
By David Ascher, A...
Recipe 1.22. PrintingUnicodeCharacterstoStandardOutput
Recipe 1.23. EncodingUnicodeDataforXMLandHTML
Recipe 1.24. MakingSo...
Recipe 3.16. WatchingForeignExchangeRates
Chapter4. PythonShortcuts
Introduction
Recipe 4.1. CopyinganObject
Recipe 4.2. C...
Recipe 6.9. MakingaFastCopyofanObject
Recipe 6.10. KeepingReferencestoBoundMethodsWithoutInhibitingGarbageCollection
Recip...
Recipe 9.6. CoordinatingThreadsbySimpleMessagePassing
Recipe 9.7. StoringPer-ThreadInformation
Recipe 9.8. MultitaskingCoo...
Recipe 12.4. AutodetectingXMLEncoding
Recipe 12.5. Converting an XML Document into a Tree of Python Objects
Recipe 12.6. R...
Recipe 15.9. PerformingRemoteLoginsUsingtelnetlib
Recipe 15.10. PerformingRemoteLoginswithSSH
Recipe 15.11. Authenticating...
Recipe 19.4. UnpackingaFewItemsinaMultipleAssignment
Recipe 19.5. AutomaticallyUnpackingtheNeededNumberofItems
Recipe 19.6...
Copyright © 2005, 2002 O'Reilly Media, Inc. All rights reserved.
Printed in the United States of America.
Published by O'R...
Preface
This book is not a typical O'Reilly book, written as a cohesive manuscript by one or two authors.
Instead, it is a...
The Design of the Book
In early 2000, Frank Willison, then Editor-in-Chief of O'Reilly & Associates, contacted me (David
A...
successful.
Given all these parameters, the various parties agreed to the following plan:
ActiveState would build an onlin...
The Implementation of the Book
The online cookbook (at http://aspn.activestate.com/ASPN/Cookbook/Python/) was the entry
po...
Using the Code from This Book
This book is here to help you get your job done. In general, you may use the code in this bo...
Audience
We expect that you know at least some Python. This book does not attempt to teach Python as a
whole; rather, it p...
Organization
This book has 20 chapters. Each chapter is devoted to a particular kind of recipe, such as
algorithms, text p...
Fred Drake is a member of the PythonLabs group, working on Python development. A
father of three, Fred is best known in th...
programming with Python, including fundamental techniques such as delegating and
controlling attribute access via special ...
web server issues.
Donn Cave is a software engineer at the University of Washington's central computer site.
Over the year...
Jeremy Hylton works for Google. In addition to young twins, Jeremy's interests including
programming language theory, pars...
their bytecode and to a factory of custom metaclasses to solve metatype conflicts, this
chapter shows how, while surely "t...
Further Reading
There are many texts available to help you learn Python or refine your Python knowledge, from
introductory...
In addition to these books, other important sources of information can help explain some of the
code in the recipes in thi...
Conventions Used in This Book
Pronouns: the first person singular is meant to convey that the recipe's or chapter introduc...
How to Contact Us
We have tested and verified all the information in this book to the best of our abilities, but you
may f...
Safari® Enabled
When you see a Safari Enabled icon on the cover of your favorite technology
book, that means the book is a...
Acknowledgments
Most publications, from mysteries to scientific papers to computer books, claim that the work
being publis...
Finally, I'd like to thank the O'Reilly editors who have had a big hand in shaping the cookbook.
Laura Lewin was the origi...
Marriage," maybe I should have surmised how wonderful it would be to work so closely with her,
day in and day out, on such...
Chapter 1. Text
Introduction
Recipe 1.1. Processing a String One Character at a Time
Recipe 1.2. Converting Between Charac...
Introduction
Credit: Fred L. Drake, Jr., PythonLabs
Text-processing applications form a substantial part of the applicatio...
language in which the text was written. Characters make up words, which make up sentences,
which make up paragraphs, and s...
Operations that search the text can operate over multiple lines very easily and quickly, and
there's no need to worry abou...
line, which indicates that the next line is a continuation:
big = "This is a long string
that spans two lines."
You must e...
for c in mystr:
This binds c to each of the characters in mystr in turn. You can form another sequence:
list(mystr) # retu...
important specialized subject of processing XML.
Recipe 1.1. Processing a String One Character at a Time
Credit: Luther Blissett
Problem
You want to process a string one c...
See Also
The Library Reference section on sequences; Perl Cookbook Recipe 1.5.
Recipe 1.2. Converting Between Characters and
Numeric Codes
Credit: Luther Blissett
Problem
You need to turn a character i...
To build a string from a list of character codes, use ''.join, map and chr; for example:
>>> print ''.join(map(chr, range(...
Recipe 1.3. Testing Whether an Object Is String-like
Credit: Luther Blissett
Problem
You need to test if an object, typica...
types) as well as instances of str and unicode.
The general Python approach to type-checking is known as duck typing: if i...
Recipe 1.4. Aligning Strings
Credit: Luther Blissett
Problem
You want to align strings: left, right, or center.
Solution
T...
Recipe 1.5. Trimming Space from the Ends of a String
Credit: Luther Blissett
Problem
You need to work on a string without ...
Recipe 1.6. Combining Strings
Credit: Luther Blissett
Problem
You have several small strings that you need to combine into...
intermediate results. Performance is therefore vastly better for operations that build no
intermediate results, but rather...
without interposing anything between them, and ', '.join(pieces) concatenates the items
putting a comma and a space betwee...
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Python cookbook, 2nd edition (2005)
Upcoming SlideShare
Loading in...5
×

Python cookbook, 2nd edition (2005)

1,592

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,592
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
13
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Python cookbook, 2nd edition (2005)"

  1. 1. • Table of Contents • Index • Reviews • Reader Reviews • Errata • Academic Python Cookbook, 2nd Edition By David Ascher, Alex Martelli, Anna Ravenscroft Publisher: O'Reilly Pub Date: March 2005 ISBN: 0-596-00797-3 Pages: 844 Like its predecessor, the new edition offers a collection of solutions to problems that Python programmers face everyday. Updated for Python 2.4, it now includes over 200 recipes that range from simple tasks, such as working with dictionaries and list comprehensions, to complex tasks, such as monitoring a network and building a templating system.
  2. 2. • Table of Contents • Index • Reviews • Reader Reviews • Errata • Academic Python Cookbook, 2nd Edition By David Ascher, Alex Martelli, Anna Ravenscroft Publisher: O'Reilly Pub Date: March 2005 ISBN: 0-596-00797-3 Pages: 844 Copyright Preface The Design of the Book The Implementation of the Book Using the Code from This Book Audience Organization Further Reading Conventions Used in This Book How to Contact Us Safari® Enabled Acknowledgments Chapter1. Text Introduction Recipe 1.1. ProcessingaStringOneCharacterataTime Recipe 1.2. ConvertingBetweenCharactersandNumericCodes Recipe 1.3. TestingWhetheranObjectIsString-like Recipe 1.4. AligningStrings Recipe 1.5. TrimmingSpacefromtheEndsofaString Recipe 1.6. CombiningStrings Recipe 1.7. ReversingaStringbyWordsorCharacters Recipe 1.8. CheckingWhetheraStringContainsaSetofCharacters Recipe 1.9. SimplifyingUsageofStrings'translateMethod Recipe 1.10. FilteringaStringforaSetofCharacters Recipe 1.11. CheckingWhetheraStringIsTextorBinary Recipe 1.12. ControllingCase Recipe 1.13. AccessingSubstrings Recipe 1.14. ChangingtheIndentationofaMultilineString Recipe 1.15. ExpandingandCompressingTabs Recipe 1.16. InterpolatingVariablesinaString Recipe 1.17. InterpolatingVariablesinaStringinPython2.4 Recipe 1.18. ReplacingMultiplePatternsinaSinglePass Recipe 1.19. CheckingaStringforAnyofMultipleEndings Recipe 1.20. HandlingInternationalTextwithUnicode Recipe 1.21. ConvertingBetweenUnicodeandPlainStrings
  3. 3. Recipe 1.22. PrintingUnicodeCharacterstoStandardOutput Recipe 1.23. EncodingUnicodeDataforXMLandHTML Recipe 1.24. MakingSomeStringsCase-Insensitive Recipe 1.25. ConvertingHTMLDocumentstoTextonaUnixTerminal Chapter2. Files Introduction Recipe 2.1. ReadingfromaFile Recipe 2.2. WritingtoaFile Recipe 2.3. SearchingandReplacingTextinaFile Recipe 2.4. ReadingaSpecificLinefromaFile Recipe 2.5. CountingLinesinaFile Recipe 2.6. ProcessingEveryWordinaFile Recipe 2.7. UsingRandom-AccessInput/Output Recipe 2.8. UpdatingaRandom-AccessFile Recipe 2.9. ReadingDatafromzipFiles Recipe 2.10. HandlingazipFileInsideaString Recipe 2.11. Archiving a Tree of Files into a Compressed tar File Recipe 2.12. SendingBinaryDatatoStandardOutputUnderWindows Recipe 2.13. UsingaC++-likeiostreamSyntax Recipe 2.14. RewindinganInputFiletotheBeginning Recipe 2.15. Adapting a File-like Object to a True File Object Recipe 2.16. WalkingDirectoryTrees Recipe 2.17. SwappingOneFileExtensionforAnotherThroughoutaDirectoryTree Recipe 2.18. FindingaFileGivenaSearchPath Recipe 2.19. FindingFilesGivenaSearchPathandaPattern Recipe 2.20. FindingaFileonthePythonSearchPath Recipe 2.21. DynamicallyChangingthePythonSearchPath Recipe 2.22. ComputingtheRelativePathfromOneDirectorytoAnother Recipe 2.23. ReadinganUnbufferedCharacterinaCross-PlatformWay Recipe 2.24. CountingPagesofPDFDocumentsonMacOSX Recipe 2.25. ChangingFileAttributesonWindows Recipe 2.26. ExtractingTextfromOpenOffice.orgDocuments Recipe 2.27. ExtractingTextfromMicrosoftWordDocuments Recipe 2.28. FileLockingUsingaCross-PlatformAPI Recipe 2.29. VersioningFilenames Recipe 2.30. CalculatingCRC-64CyclicRedundancyChecks Chapter3. TimeandMoney Introduction Recipe 3.1. CalculatingYesterdayandTomorrow Recipe 3.2. FindingLastFriday Recipe 3.3. CalculatingTimePeriodsinaDateRange Recipe 3.4. SummingDurationsofSongs Recipe 3.5. CalculatingtheNumberofWeekdaysBetweenTwoDates Recipe 3.6. LookingupHolidaysAutomatically Recipe 3.7. FuzzyParsingofDates Recipe 3.8. CheckingWhetherDaylightSavingTimeIsCurrentlyinEffect Recipe 3.9. ConvertingTimeZones Recipe 3.10. RunningaCommandRepeatedly Recipe 3.11. SchedulingCommands Recipe 3.12. DoingDecimalArithmetic Recipe 3.13. FormattingDecimalsasCurrency Recipe 3.14. UsingPythonasaSimpleAddingMachine Recipe 3.15. CheckingaCreditCardChecksum
  4. 4. Recipe 3.16. WatchingForeignExchangeRates Chapter4. PythonShortcuts Introduction Recipe 4.1. CopyinganObject Recipe 4.2. ConstructingListswithListComprehensions Recipe 4.3. ReturninganElementofaListIfItExists Recipe 4.4. LoopingoverItemsandTheirIndicesinaSequence Recipe 4.5. CreatingListsofListsWithoutSharingReferences Recipe 4.6. FlatteningaNestedSequence Recipe 4.7. RemovingorReorderingColumnsinaListofRows Recipe 4.8. TransposingTwo-DimensionalArrays Recipe 4.9. GettingaValuefromaDictionary Recipe 4.10. AddinganEntrytoaDictionary Recipe 4.11. BuildingaDictionaryWithoutExcessiveQuoting Recipe 4.12. Building a Dict from a List of Alternating Keys and Values Recipe 4.13. ExtractingaSubsetofaDictionary Recipe 4.14. InvertingaDictionary Recipe 4.15. AssociatingMultipleValueswithEachKeyinaDictionary Recipe 4.16. UsingaDictionarytoDispatchMethodsorFunctions Recipe 4.17. FindingUnionsandIntersectionsofDictionaries Recipe 4.18. CollectingaBunchofNamedItems Recipe 4.19. AssigningandTestingwithOneStatement Recipe 4.20. UsingprintfinPython Recipe 4.21. RandomlyPickingItemswithGivenProbabilities Recipe 4.22. HandlingExceptionsWithinanExpression Recipe 4.23. EnsuringaNameIsDefinedinaGivenModule Chapter5. SearchingandSorting Introduction Recipe 5.1. SortingaDictionary Recipe 5.2. SortingaListofStringsCase-Insensitively Recipe 5.3. Sorting a List of Objects by an Attribute of the Objects Recipe 5.4. SortingKeysorIndicesBasedontheCorrespondingValues Recipe 5.5. SortingStringswithEmbeddedNumbers Recipe 5.6. Processing All of a List's Items in Random Order Recipe 5.7. KeepingaSequenceOrderedasItemsAreAdded Recipe 5.8. GettingtheFirstFewSmallestItemsofaSequence Recipe 5.9. LookingforItemsinaSortedSequence Recipe 5.10. SelectingthenthSmallestElementofaSequence Recipe 5.11. ShowingoffquicksortinThreeLines Recipe 5.12. PerformingFrequentMembershipTestsonaSequence Recipe 5.13. FindingSubsequences Recipe 5.14. EnrichingtheDictionaryTypewithRatingsFunctionality Recipe 5.15. SortingNamesandSeparatingThembyInitials Chapter 6. Object-Oriented Programming Introduction Recipe 6.1. ConvertingAmongTemperatureScales Recipe 6.2. DefiningConstants Recipe 6.3. RestrictingAttributeSetting Recipe 6.4. ChainingDictionaryLookups Recipe 6.5. DelegatingAutomaticallyasanAlternativetoInheritance Recipe 6.6. DelegatingSpecialMethodsinProxies Recipe 6.7. ImplementingTupleswithNamedItems Recipe 6.8. AvoidingBoilerplateAccessorsforProperties
  5. 5. Recipe 6.9. MakingaFastCopyofanObject Recipe 6.10. KeepingReferencestoBoundMethodsWithoutInhibitingGarbageCollection Recipe 6.11. ImplementingaRingBuffer Recipe 6.12. CheckinganInstanceforAnyStateChanges Recipe 6.13. CheckingWhetheranObjectHasNecessaryAttributes Recipe 6.14. ImplementingtheStateDesignPattern Recipe 6.15. Implementingthe"Singleton"DesignPattern Recipe 6.16. Avoidingthe"Singleton"DesignPatternwiththeBorgIdiom Recipe 6.17. ImplementingtheNullObjectDesignPattern Recipe 6.18. AutomaticallyInitializingInstanceVariablesfrom__init__Arguments Recipe 6.19. CallingaSuperclass__init__MethodIfItExists Recipe 6.20. UsingCooperativeSupercallsConciselyandSafely Chapter7. PersistenceandDatabases Introduction Recipe 7.1. SerializingDataUsingthemarshalModule Recipe 7.2. SerializingDataUsingthepickleandcPickleModules Recipe 7.3. UsingCompressionwithPickling Recipe 7.4. UsingthecPickleModuleonClassesandInstances Recipe 7.5. HoldingBoundMethodsinaPicklableWay Recipe 7.6. PicklingCodeObjects Recipe 7.7. MutatingObjectswithshelve Recipe 7.8. UsingtheBerkeleyDBDatabase Recipe 7.9. AccesssingaMySQLDatabase Recipe 7.10. StoringaBLOBinaMySQLDatabase Recipe 7.11. StoringaBLOBinaPostgreSQLDatabase Recipe 7.12. StoringaBLOBinaSQLiteDatabase Recipe 7.13. GeneratingaDictionaryMappingFieldNamestoColumnNumbers Recipe 7.14. UsingdtupleforFlexibleAccesstoQueryResults Recipe 7.15. Pretty-PrintingtheContentsofDatabaseCursors Recipe 7.16. UsingaSingleParameter-PassingStyleAcrossVariousDBAPIModules Recipe 7.17. UsingMicrosoftJetviaADO Recipe 7.18. AccessingaJDBCDatabasefromaJythonServlet Recipe 7.19. UsingODBCtoGetExcelDatawithJython Chapter 8. Debugging and Testing Introduction Recipe 8.1. DisablingExecutionofSomeConditionalsandLoops Recipe 8.2. MeasuringMemoryUsageonLinux Recipe 8.3. DebuggingtheGarbage-CollectionProcess Recipe 8.4. TrappingandRecordingExceptions Recipe 8.5. TracingExpressionsandCommentsinDebugMode Recipe 8.6. GettingMoreInformationfromTracebacks Recipe 8.7. StartingtheDebuggerAutomaticallyAfteranUncaughtException Recipe 8.8. RunningUnitTestsMostSimply Recipe 8.9. RunningUnitTestsAutomatically Recipe 8.10. UsingdoctestwithunittestinPython2.4 Recipe 8.11. CheckingValuesAgainstIntervalsinUnitTesting Chapter 9. Processes, Threads, and Synchronization Introduction Recipe 9.1. SynchronizingAllMethodsinanObject Recipe 9.2. TerminatingaThread Recipe 9.3. UsingaQueue.QueueasaPriorityQueue Recipe 9.4. WorkingwithaThreadPool Recipe 9.5. ExecutingaFunctioninParallelonMultipleArgumentSets
  6. 6. Recipe 9.6. CoordinatingThreadsbySimpleMessagePassing Recipe 9.7. StoringPer-ThreadInformation Recipe 9.8. MultitaskingCooperativelyWithoutThreads Recipe 9.9. Determining Whether Another Instanceof a Script Is Already Running in Windows Recipe 9.10. ProcessingWindowsMessagesUsingMsgWaitForMultipleObjects Recipe 9.11. DrivinganExternalProcesswithpopen Recipe 9.12. Capturing the Output and Error Streams from a Unix Shell Command Recipe 9.13. ForkingaDaemonProcessonUnix Chapter10. SystemAdministration Introduction Recipe 10.1. GeneratingRandomPasswords Recipe 10.2. GeneratingEasilyRememberedSomewhat-RandomPasswords Recipe 10.3. AuthenticatingUsersbyMeansofaPOPServer Recipe 10.4. CalculatingApacheHitsperIPAddress Recipe 10.5. Calculating the Rate of Client Cache Hits on Apache Recipe 10.6. SpawninganEditorfromaScript Recipe 10.7. BackingUpFiles Recipe 10.8. SelectivelyCopyingaMailboxFile Recipe 10.9. BuildingaWhitelistofEmailAddressesFromaMailbox Recipe 10.10. BlockingDuplicateMails Recipe 10.11. CheckingYourWindowsSoundSystem Recipe 10.12. RegisteringorUnregisteringaDLLonWindows Recipe 10.13. Checking and Modifying the Set of Tasks Windows Automatically Runs at Login Recipe 10.14. CreatingaShareonWindows Recipe 10.15. ConnectingtoanAlreadyRunningInstanceofInternetExplorer Recipe 10.16. ReadingMicrosoftOutlookContacts Recipe 10.17. GatheringDetailedSystemInformationonMacOSX Chapter11. UserInterfaces Introduction Recipe 11.1. ShowingaProgressIndicatoronaTextConsole Recipe 11.2. AvoidinglambdainWritingCallbackFunctions Recipe 11.3. UsingDefaultValuesandBoundswithtkSimpleDialogFunctions Recipe 11.4. AddingDragandDropReorderingtoaTkinterListbox Recipe 11.5. EnteringAccentedCharactersinTkinterWidgets Recipe 11.6. EmbeddingInlineGIFsUsingTkinter Recipe 11.7. ConvertingAmongImageFormats Recipe 11.8. ImplementingaStopwatchinTkinter Recipe 11.9. CombiningGUIsandAsynchronousI/OwithThreads Recipe 11.10. UsingIDLE'sTreeWidgetinTkinter Recipe 11.11. SupportingMultipleValuesperRowinaTkinterListbox Recipe 11.12. CopyingGeometryMethodsandOptionsBetweenTkinterWidgets Recipe 11.13. ImplementingaTabbedNotebookforTkinter Recipe 11.14. UsingawxPythonNotebookwithPanels Recipe 11.15. ImplementinganImageJPlug-ininJython Recipe 11.16. ViewinganImagefromaURLwithSwingandJython Recipe 11.17. GettingUserInputonMacOS Recipe 11.18. BuildingaPythonCocoaGUIProgrammatically Recipe 11.19. ImplementingFade-inWindowswithIronPython Chapter12. ProcessingXML Introduction Recipe 12.1. CheckingXMLWell-Formedness Recipe 12.2. CountingTagsinaDocument Recipe 12.3. ExtractingTextfromanXMLDocument
  7. 7. Recipe 12.4. AutodetectingXMLEncoding Recipe 12.5. Converting an XML Document into a Tree of Python Objects Recipe 12.6. RemovingWhitespace-onlyTextNodesfromanXMLDOMNode'sSubtree Recipe 12.7. ParsingMicrosoftExcel'sXML Recipe 12.8. ValidatingXMLDocuments Recipe 12.9. FilteringElementsandAttributesBelongingtoaGivenNamespace Recipe 12.10. MergingContinuousTextEventswithaSAXFilter Recipe 12.11. UsingMSHTMLtoParseXMLorHTML Chapter 13. Network Programming Introduction Recipe 13.1. PassingMessageswithSocketDatagrams Recipe 13.2. GrabbingaDocumentfromtheWeb Recipe 13.3. FilteringaListofFTPSites Recipe 13.4. Getting Time from a Server via the SNTP Protocol Recipe 13.5. SendingHTMLMail Recipe 13.6. BundlingFilesinaMIMEMessage Recipe 13.7. UnpackingaMultipartMIMEMessage Recipe 13.8. RemovingAttachmentsfromanEmailMessage Recipe 13.9. FixingMessagesParsedbyPython2.4email.FeedParser Recipe 13.10. InspectingaPOP3MailboxInteractively Recipe 13.11. DetectingInactiveComputers Recipe 13.12. MonitoringaNetworkwithHTTP Recipe 13.13. ForwardingandRedirectingNetworkPorts Recipe 13.14. TunnelingSSLThroughaProxy Recipe 13.15. ImplementingtheDynamicIPProtocol Recipe 13.16. ConnectingtoIRCandLoggingMessagestoDisk Recipe 13.17. AccessingLDAPServers Chapter 14. Web Programming Introduction Recipe 14.1. TestingWhetherCGIIsWorking Recipe 14.2. HandlingURLsWithinaCGIScript Recipe 14.3. UploadingFileswithCGI Recipe 14.4. CheckingforaWebPage'sExistence Recipe 14.5. CheckingContentTypeviaHTTP Recipe 14.6. ResumingtheHTTPDownloadofaFile Recipe 14.7. HandlingCookiesWhileFetchingWebPages Recipe 14.8. AuthenticatingwithaProxyforHTTPSNavigation Recipe 14.9. RunningaServletwithJython Recipe 14.10. FindinganInternetExplorerCookie Recipe 14.11. GeneratingOPMLFiles Recipe 14.12. AggregatingRSSFeeds Recipe 14.13. TurningDataintoWebPagesThroughTemplates Recipe 14.14. RenderingArbitraryObjectswithNevow Chapter15. DistributedProgramming Introduction Recipe 15.1. MakinganXML-RPCMethodCall Recipe 15.2. ServingXML-RPCRequests Recipe 15.3. UsingXML-RPCwithMedusa Recipe 15.4. EnablinganXML-RPCServertoBeTerminatedRemotely Recipe 15.5. ImplementingSimpleXMLRPCServerNiceties Recipe 15.6. GivinganXML-RPCServerawxPythonGUI Recipe 15.7. UsingTwistedPerspectiveBroker Recipe 15.8. ImplementingaCORBAServerandClient
  8. 8. Recipe 15.9. PerformingRemoteLoginsUsingtelnetlib Recipe 15.10. PerformingRemoteLoginswithSSH Recipe 15.11. AuthenticatinganSSLClientoverHTTPS Chapter 16. Programs About Programs Introduction Recipe 16.1. VerifyingWhetheraStringRepresentsaValidNumber Recipe 16.2. ImportingaDynamicallyGeneratedModule Recipe 16.3. Importing from a Module Whose Name Is Determined at Runtime Recipe 16.4. AssociatingParameterswithaFunction(Currying) Recipe 16.5. ComposingFunctions Recipe 16.6. ColorizingPythonSourceUsingtheBuilt-inTokenizer Recipe 16.7. MergingandSplittingTokens Recipe 16.8. CheckingWhetheraStringHasBalancedParentheses Recipe 16.9. SimulatingEnumerationsinPython Recipe 16.10. ReferringtoaListComprehensionWhileBuildingIt Recipe 16.11. Automatingthepy2exeCompilationofScriptsintoWindowsExecutables Recipe 16.12. BindingMainScriptandModulesintoOneExecutableonUnix Chapter17. ExtendingandEmbedding Introduction Recipe 17.1. ImplementingaSimpleExtensionType Recipe 17.2. ImplementingaSimpleExtensionTypewithPyrex Recipe 17.3. ExposingaC++LibrarytoPython Recipe 17.4. CallingFunctionsfromaWindowsDLL Recipe 17.5. UsingSWIG-GeneratedModulesinaMultithreadedEnvironment Recipe 17.6. Translating a Python Sequence into a C Array with the PySequence_Fast Protocol Recipe 17.7. AccessingaPythonSequenceItem-by-ItemwiththeIteratorProtocol Recipe 17.8. ReturningNonefromaPython-CallableCFunction Recipe 17.9. DebuggingDynamicallyLoadedCExtensionswithgdb Recipe 17.10. DebuggingMemoryProblems Chapter18. Algorithms Introduction Recipe 18.1. RemovingDuplicatesfromaSequence Recipe 18.2. RemovingDuplicatesfromaSequenceWhileMaintainingSequenceOrder Recipe 18.3. GeneratingRandomSampleswithReplacement Recipe 18.4. GeneratingRandomSamplesWithoutReplacement Recipe 18.5. Memoizing(Caching)theReturnValuesofFunctions Recipe 18.6. ImplementingaFIFOContainer Recipe 18.7. CachingObjectswithaFIFOPruningStrategy Recipe 18.8. ImplementingaBag(Multiset)CollectionType Recipe 18.9. SimulatingtheTernaryOperatorinPython Recipe 18.10. ComputingPrimeNumbers Recipe 18.11. FormattingIntegersasBinaryStrings Recipe 18.12. FormattingIntegersasStringsinArbitraryBases Recipe 18.13. ConvertingNumberstoRationalsviaFareyFractions Recipe 18.14. DoingArithmeticwithErrorPropagation Recipe 18.15. SummingNumberswithMaximalAccuracy Recipe 18.16. SimulatingFloatingPoint Recipe 18.17. ComputingtheConvexHullsandDiametersof2DPointSets Chapter19. IteratorsandGenerators Introduction Recipe 19.1. Writingarange-likeFunctionwithFloatIncrements Recipe 19.2. BuildingaListfromAnyIterable Recipe 19.3. GeneratingtheFibonacciSequence
  9. 9. Recipe 19.4. UnpackingaFewItemsinaMultipleAssignment Recipe 19.5. AutomaticallyUnpackingtheNeededNumberofItems Recipe 19.6. DividinganIterableintonSlicesofStriden Recipe 19.7. LoopingonaSequencebyOverlappingWindows Recipe 19.8. LoopingThroughMultipleIterablesinParallel Recipe 19.9. LoopingThroughtheCross-ProductofMultipleIterables Recipe 19.10. ReadingaTextFilebyParagraphs Recipe 19.11. ReadingLineswithContinuationCharacters Recipe 19.12. Iterating on a Stream of Data Blocks as a Stream of Lines Recipe 19.13. Fetching Large Record Sets from a Database with a Generator Recipe 19.14. MergingSortedSequences Recipe 19.15. GeneratingPermutations,Combinations,andSelections Recipe 19.16. GeneratingthePartitionsofanInteger Recipe 19.17. DuplicatinganIterator Recipe 19.18. LookingAheadintoanIterator Recipe 19.19. SimplifyingQueue-ConsumerThreads Recipe 19.20. RunninganIteratorinAnotherThread Recipe 19.21. ComputingaSummaryReportwithitertools.groupby Chapter20. Descriptors,Decorators,andMetaclasses Introduction Recipe 20.1. GettingFreshDefaultValuesatEachFunctionCall Recipe 20.2. CodingPropertiesasNestedFunctions Recipe 20.3. AliasingAttributeValues Recipe 20.4. CachingAttributeValues Recipe 20.5. UsingOneMethodasAccessorforMultipleAttributes Recipe 20.6. AddingFunctionalitytoaClassbyWrappingaMethod Recipe 20.7. AddingFunctionalitytoaClassbyEnrichingAllMethods Recipe 20.8. AddingaMethodtoaClassInstanceatRuntime Recipe 20.9. CheckingWhetherInterfacesAreImplemented Recipe 20.10. Using _ _new_ _ and _ _init_ _ Appropriately in Custom Metaclasses Recipe 20.11. AllowingChainingofMutatingListMethods Recipe 20.12. UsingCooperativeSupercallswithTerserSyntax Recipe 20.13. InitializingInstanceAttributesWithoutUsing__init__ Recipe 20.14. AutomaticInitializationofInstanceAttributes Recipe 20.15. UpgradingClassInstancesAutomaticallyonreload Recipe 20.16. BindingConstantsatCompileTime Recipe 20.17. SolvingMetaclassConflicts Colophon Index
  10. 10. Copyright © 2005, 2002 O'Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O'Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O'Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly Media, Inc. The Cookbook series designations, Python Cookbook, the image of a springhaas, and related trade dress are trademarks of O'Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O'Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
  11. 11. Preface This book is not a typical O'Reilly book, written as a cohesive manuscript by one or two authors. Instead, it is a new kind of booka bold attempt at applying some principles of open source development to book authoring. Over 300 members of the Python community contributed materials to this book. In this Preface, we, the editors, want to give you, the reader, some background regarding how this book came about and the processes and people involved, and some thoughts about the implications of this new form.
  12. 12. The Design of the Book In early 2000, Frank Willison, then Editor-in-Chief of O'Reilly & Associates, contacted me (David Ascher) to find out if I wanted to write a book. Frank had been the editor for Learning Python, which I cowrote with Mark Lutz. Since I had just taken a job at what was then considered a Perl shop (ActiveState), I didn't have the bandwidth necessary to write another book, and plans for the project were gently shelved. Periodically, however, Frank would send me an email or chat with me at a conference regarding some of the book topics we had discussed. One of Frank's ideas was to create a Python Cookbook, based on the concept first used by Tom Christiansen and Nathan Torkington with the Perl Cookbook. Frank wanted to replicate the success of the Perl Cookbook, but he wanted a broader set of people to provide input. He thought that, much as in a real cookbook, a larger set of authors would provide for a greater range of tastes. The quality, in his vision, would be ensured by the oversight of a technical editor, combined with O'Reilly's editorial review process. Frank and Dick Hardt, ActiveState's CEO, realized that Frank's goal could be combined with ActiveState's goal of creating a community site for open source programmers, called the ActiveState Programmer's Network (ASPN). ActiveState had a popular web site, with the infrastructure required to host a wide variety of content, but it wasn't in the business of creating original content. ActiveState always felt that the open source communities were the best sources of accurate and up-to-date content, even if sometimes that content was hard to find. The O'Reilly and ActiveState teams quickly realized that the two goals were aligned and that a joint venture would be the best way to achieve the following key objectives: Creating an online repository of Python recipes by Python programmers for Python programmers Publishing a book containing the best of those recipes, accompanied by overviews and background material written by key Python figures Learning what it would take to create a book with a different authoring model At the same time, two other activities were happening. First, those of us at ActiveState, including Paul Prescod, were actively looking for "stars" to join ActiveState's development team. One of the candidates being recruited was the famous (but unknown to us, at the time) Alex Martelli. Alex was famous because of his numerous and exhaustive postings on the Python mailing list, where he exhibited an unending patience for explaining Python's subtleties and joys to the increasing audience of Python programmers. He was unknown because he lived in Italy and, since he was a relative newcomer to the Python community, none of the old Python hands had ever met himtheir paths had not happened to cross back in the 1980s when Alex lived in the United States, working for IBM Research and enthusiastically using and promoting other high- level languages (at the time, mostly IBM's Rexx). ActiveState wooed Alex, trying to convince him to move to Vancouver. We came quite close, but his employer put some golden handcuffs on him, and somehow Vancouver's weather couldn't compete with Italy's. Alex stayed in Italy, much to my disappointment. As it happened, Alex was also at that time negotiating with O'Reilly about writing a book. Alex wanted to write a cookbook, but O'Reilly explained that the cookbook was already signed. Later, Alex and O'Reilly signed a contract for Python in Nutshell. The second ongoing activity was the creation of the Python Software Foundation. For a variety of reasons, best left to discussion over beers at a conference, everyone in the Python community wanted to create a non-profit organization that would be the holder of Python's intellectual property, to ensure that Python would be on a legally strong footing. However, such an organization needed both financial support and buy-in from the Python community to be
  13. 13. successful. Given all these parameters, the various parties agreed to the following plan: ActiveState would build an online cookbook, a mechanism by which anyone could submit a recipe (i.e., a snippet of Python code addressing a particular problem, accompanied by a discussion of the recipe, much like a description of why one should use cream of tartar when whipping egg whites). To foster a community of authors and encourage peer review, the web site would also let readers of the recipes suggest changes, ask questions, and so on. As part of my ActiveState job, I would edit and ensure the quality of the recipes. Alex Martelli joined the project as a co-editor when the material was being prepared for publication, and, with Anna Martelli Ravenscroft, took over as primary editor for the second edition. O'Reilly would publish the best recipes as the Python Cookbook. In lieu of author royalties for the recipes, a portion of the proceeds from the book sales would be donated to the Python Software Foundation.
  14. 14. The Implementation of the Book The online cookbook (at http://aspn.activestate.com/ASPN/Cookbook/Python/) was the entry point for the recipes. Users got free accounts, filled in a form, and presto, their recipes became part of the cookbook. Thousands of people read the recipes, and some added comments, and so, in the publishing equivalent of peer review, the recipes matured and grew. While it was predictable that the chance of getting your name in print would get people attracted to the online cookbook, the ongoing success of the cookbook, with dozens of recipes added monthly and more and more references to it on the newsgroups, is a testament to the value it brings to the readersvalue which is provided by the recipe authors. Starting from the materials available on the site, the implementation of the book was mostly a question of selecting, merging, ordering, and editing the materials. A few more details about this part of the work are in the "Organization" section of this Preface.
  15. 15. Using the Code from This Book This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of code taken from O'Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of code from this book into your product's documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Python Cookbook, 2d ed., by Alex Martelli, Anna Martelli Ravenscroft, and David Ascher (O'Reilly Media, 2005) 0-596-00797-3." If you feel your use of code from this book falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com.
  16. 16. Audience We expect that you know at least some Python. This book does not attempt to teach Python as a whole; rather, it presents some specific techniques and concepts (and occasionally tricks) for dealing with particular tasks. If you are looking for an introduction to Python, consider some of the books described in the Further Reading section of this Preface. However, you don't need to know a lot of Python to find this book helpful. Chapters include recipes demonstrating the best techniques for accomplishing some elementary and general tasks, as well as more complex or specialized ones. We have also added sidebars, here and there, to clarify certain concepts which are used in the book and which you may have heard of, but which might still be unclear to you. However, this is definitely not a book just for beginners. The main target audience is the whole Python community, mostly made up of pretty good programmers, neither newbies nor wizards. And if you do already know a lot about Python, you may be in for a pleasant surprise! We've included recipes that explore some the newest and least well-known areas of Python. You might very well learn a few thingswe did! Regardless of where you fall along the spectrum of Python expertise, and more generally of programming skill, we believe you will get something valuable from this book. If you already own the first edition, you may be wondering whether you need this second edition, too. We think the answer is "yes." The first edition had 245 recipes; we kept 146 of those (with lots of editing in almost all cases), and added 192 new ones, for a total of 338 recipes in this second edition. So, over half of the recipes in this edition are completely new, and all the recipes are updated to apply to today's Pythonreleases 2.3 and 2.4. Indeed, this update is the main factor which lets us have almost 100 more recipes in a book of about the same size. The first edition covered all versions from 1.5.2 (and sometimes earlier) to 2.2; this one focuses firmly on 2.3 and 2.4. Thanks to the greater power of today's Python, and, even more, thanks to the fact that this edition avoids the "historical" treatises about how you had to do things in Python versions released 5 or more years ago, we were able to provide substantially more currently relevant recipes and information in roughly the same amount of space.
  17. 17. Organization This book has 20 chapters. Each chapter is devoted to a particular kind of recipe, such as algorithms, text processing, databases, and so on. The 1st edition had 17 chapters. There have been improvements to Python, both language and library, and to the corpus of recipes the Python community has posted to the cookbook site, that convinced us to add three entirely new chapters: on the iterators and generators introduced in Python 2.3; on Python's support for time and money operations, both old and new; and on new, advanced tools introduced in Python 2.2 and following releases (custom descriptors, decorators, metaclasses). Each chapter contains an introduction, written by an expert in the field, followed by recipes selected from the online cookbook (in some casesabout 5% of this book's recipesa few new recipes were specially written for this volume) and edited to fit the book's formatting and style requirements. Alex (with some help from Anna) did the vast majority of the selectiondetermining which recipes from the first edition to keep and update, and selecting new recipes to add, or merge with others, from the nearly 1,000 available on the site (so, if a recipe you posted to the cookbook site didn't get into this printed edition, it's his fault!). He also decided which subjects just had to be covered and thus might need specially written recipesalthough he couldn't manage to get quite all of the specially written recipes he wanted, so anything that's missing, and wasn't on the cookbook site, might not be entirely his fault. Once the selection was complete, the work turned to editing the recipes, and to merging multiple recipes, as well as incorporating important contents from many significant comments posted about the recipes. This proved to be quite a challenge, just as it had been for the first edition, but even more so. The recipes varied widely in their organization, level of completeness, and sophistication. With over 300 authors involved, over 300 different "voices" were included in the text. We have striven to maintain a variety of styles to reflect the true nature of this book, the book written by the entire Python community. However, we edited each recipe, sometimes quite considerably, to make it as accessible and useful as possible, ensuring enough uniformity in structure and presentation to maximize the usability of the book as a whole. Most recipes, both from the first edition and from the online site, had to be updated, sometimes heavily, to take advantage of new tools and better approaches developed since those recipes were originally posted. We also carefully reconsidered (and slightly altered) the ordering of chapters, and the placement and ordering of recipes within chapters; our goal in this reordering was to maximize the book's usefulness for both newcomers to Python and seasoned veterans, and, also, for both readers tackling the book sequentially, cover to cover, and ones just dipping in, in "random access" fashion, to look for help on some specific area. While the book should thus definitely be accessible "by hops and jumps," we nevertheless believe a first sequential skim will amply repay the modest time you, the reader, invest in it. On such a skim, skip every recipe that you have trouble following or that is of no current interest to you. Despite the skipping, you'll still get a sense of how the whole book hangs together and of where certain subjects are covered, which will stand you in good stead both for later in-depth sequential reading, if that's your choice, and for "random access" reading. To further help you get a sense of what's where in the book, here's a capsule summary of each chapter's contents, and equally capsule bios of the Python experts who were so kind as to take on the task of writing the chapters' "Introduction" sections. Chapter 1, introduction by Fred L. Drake, Jr. This chapter contains recipes for manipulating text in a variety of ways, including combining, filtering, and formatting strings, substituting variables throughout a text document, and dealing with Unicode.
  18. 18. Fred Drake is a member of the PythonLabs group, working on Python development. A father of three, Fred is best known in the Python community for single-handedly maintaining the official documentation. Fred is a co-author of Python & XML (O'Reilly). Chapter 2, introduction by Mark Lutz This chapter presents techniques for working with data in files and for manipulating files and directories within the filesystem, including specific file formats and archive formats such as tar and zip. Mark Lutz is well known to most Python users as the most prolific author of Python books, including Programming Python, Python Pocket Reference, and Learning Python (all from O'Reilly), which he co-authored with David Ascher. Mark is also a leading Python trainer, spreading the Python gospel throughout the world. Chapter 3, introduction by Gustavo Niemeyer and Facundo Batista This chapter (new in this edition) presents tools and techniques for working with dates, times, decimal numbers, and some other money-related issues. Gustavo Niemeyer is the author of the third-party dateutil module, as well as a variety of other Python extensions and projects. Gustavo lives in Brazil. Facundo Batista is the author of the Decimal PEP 327, and of the standard library module decimal, which brought floating-point decimal support to Python 2.4. He lives in Argentina. The editors were delighted to bring them together for this introduction. Chapter 4, introduction by David Ascher This chapter includes recipes for many common techniques that can be used anywhere, or that don't really fit into any of the other, more specific recipe categories. David Ascher is a co-editor of this volume. David's background spans physics, vision research, scientific visualization, computer graphics, a variety of programming languages, co-authoring Learning Python (O'Reilly), teaching Python, and these days, a slew of technical and nontechnical tasks such as managing the ActiveState team. David also gets roped into organizing Python conferences on a regular basis. Chapter 5, introduction by Tim Peters This chapter covers techniques for searching and sorting in Python. Many of the recipes explore creative uses of the stable and fast list.sort in conjunction with the decorate- sort-undecorate (DSU) idiom (newly built in with Python 2.4), while others demonstrate the power of heapq, bisect, and other Python searching and sorting tools. Tim Peters, also known as the tim-bot, is one of the mythological figures of the Python world. He is the oracle, channeling Guido van Rossum when Guido is busy, channeling the IEEE-754 floating-point committee when anyone asks anything remotely relevant, and appearing conservative while pushing for a constant evolution in the language. Tim is a member of the PythonLabs team. Chapter 6, introduction by Alex Martelli This chapter offers a wide range of recipes that demonstrate the power of object-oriented
  19. 19. programming with Python, including fundamental techniques such as delegating and controlling attribute access via special methods, intermediate ones such as the implementation of various design patterns, and some simple but useful applications of advanced concepts, such as custom metaclasses, which are covered in greater depth in Chapter 20. Alex Martelli, also known as the martelli-bot, is a co-editor of this volume. After almost a decade with IBM Research, then a bit more than that with think3, inc., Alex now works as a freelance consultant, most recently for AB Strakt, a Swedish Python-centered firm. He also edits and writes Python articles and books, including Python in a Nutshell (O'Reilly) and, occasionally, research works on the game of contract bridge. Chapter 7, introduction by Aaron Watters This chapter presents Python techniques for persistence, including serialization approaches and interaction with various databases. Aaron Watters was one of the earliest advocates of Python and is an expert in databases. He's known for having been the lead author on the first book on Python (Internet Programming with Python, M&T Books, now out of print), and he has authored many widely used Python extensions, such as kjBuckets and kwParsing. Aaron currently works as a freelance consultant. Chapter 8, introduction by Mark Hammond This chapter includes a collection of recipes that assist with the debugging and testing process, from customizing error logging and traceback information, to unit testing with custom modules, unittest and doctest. Mark Hammond is best known for his work supporting Python on the Windows platform. With Greg Stein, he built an incredible library of modules interfacing Python to a wide variety of APIs, libraries, and component models such as COM. He is also an expert designer and builder of developer tools, most notably Pythonwin and Komodo. Finally, Mark is an expert at debugging even the most messy systemsduring Komodo development, for example, Mark was often called upon to debug problems that spanned three languages (Python, C++, JavaScript), multiple threads, and multiple processes. Mark is also co-author, with Andy Robinson, of Python Programming on Win32 (O'Reilly). Chapter 9, introduction by Greg Wilson This chapter covers a variety of techniques for concurrent programming, including threads, queues, and multiple processes. Greg Wilson writes children's books, as well as books on parallel programming and data crunching. When he's not doing that, he's a contributing editor with Doctor Dobb's Journal, an adjunct professor in Computer Science at the University of Toronto, and a freelance software developer. Greg was the original driving force behind the Software Carpentry project, and he recently received a grant from the Python Software Foundation to develop Pythonic course material for computational scientists and engineers. Chapter 10, introduction by Donn Cave This chapter includes recipes for a number of common system administration tasks, from generating passwords and interacting with the Windows registry, to handling mailbox and
  20. 20. web server issues. Donn Cave is a software engineer at the University of Washington's central computer site. Over the years, Donn has proven to be a fount of information on comp.lang.python on all matters related to system calls, Unix, system administration, files, signals, and the like. Chapter 11, introduction by Fredrik Lundh This chapter contains recipes for common GUI tasks, mostly with Tkinter, but also a smattering of wxPython, Qt, image processing, and GUI recipes specific to Jython (for JVMJava Virtual Machine), Mac OS X, and IronPython (for dotNET). Fredrik Lundh, also known as the eff-bot, is the CTO of Secret Labs AB, a Swedish Python- focused company providing a variety of products and technologies. Fredrik is the world's leading expert on Tkinter (the most popular GUI toolkit for Python), as well as the main author of the Python Imaging Library (PIL). He is also the author of Python Standard Library (O'Reilly), which is a good complement to this volume and focuses on the modules in the standard Python library. Finally, he is a prolific contributor to comp.lang.python, helping novices and experts alik