SitemapTable of ContentsCopyrightPrefaceThe Design of the BookThe Implementation of the BookUsing the Code from This BookAudienceOrganizationFurther ReadingConventions Used in This BookHow to Contact UsSafari® EnabledAcknowledgmentsChapter 1. TextIntroductionRecipe 1.1. Processing a String One Character at a TimeRecipe 1.2. Converting Between Characters and Numeric CodesRecipe 1.3. Testing Whether an Object Is String-likeRecipe 1.4. Aligning StringsRecipe 1.5. Trimming Space from the Ends of a StringRecipe 1.6. Combining StringsRecipe 1.7. Reversing a String by Words or CharactersRecipe 1.8. Checking Whether a String Contains a Set of CharactersRecipe 1.9. Simplifying Usage of Strings'' translate MethodRecipe 1.10. Filtering a String for a Set of CharactersRecipe 1.11. Checking Whether a String Is Text or BinaryRecipe 1.12. Controlling CaseRecipe 1.13. Accessing SubstringsRecipe 1.14. Changing the Indentation of a Multiline StringRecipe 1.15. Expanding and Compressing TabsRecipe 1.16. Interpolating Variables in a StringRecipe 1.17. Interpolating Variables in a Stringin Python 2.4Recipe 1.18. Replacing Multiple Patterns in a Single PassRecipe 1.19. Checking a String for Any of Multiple EndingsRecipe 1.20. Handling International Text with UnicodeRecipe 1.21. Converting Between Unicode and Plain StringsRecipe 1.22. Printing Unicode Charactersto Standard OutputRecipe 1.23. Encoding Unicode Data for XML and HTMLRecipe 1.24. Making Some Strings Case-InsensitiveRecipe 1.25. Converting HTML Documents to Texton a Unix TerminalChapter 2. FilesIntroductionRecipe 2.1. Reading from a FileRecipe 2.2. Writing to a FileRecipe 2.3. Searching and Replacing Text in a FileRecipe 2.4. Reading a Specific Line from a FileRecipe 2.5. Counting Lines in a FileRecipe 2.6. Processing Every Word in a FileRecipe 2.7. Using Random-Access Input/OutputRecipe 2.8. Updating a Random-Access FileRecipe 2.9. Reading Data from zip FilesRecipe 2.10. Handling a zip File Inside a StringRecipe 2.11. Archiving a Tree of Files into a Compressed tar FileRecipe 2.12. Sending Binary Data to Standard Output Under WindowsRecipe 2.13. Using a C++-like iostream SyntaxRecipe 2.14. Rewinding an Input File to the BeginningRecipe 2.15. Adapting a File-like Object to a True File ObjectRecipe 2.16. Walking Directory TreesRecipe 2.17. Swapping One File Extension for Another Throughout a Directory TreeRecipe 2.18. Finding a File Given a Search PathRecipe 2.19. Finding Files Given a Search Path and a PatternRecipe 2.20. Finding a File on the Python Search PathRecipe 2.21. Dynamically Changing the PythonSearch PathRecipe 2.22. Computing the Relative Path from One Directory to AnotherRecipe 2.23. Reading an Unbuffered Character in a Cross-Platform WayRecipe 2.24. Counting Pages of PDF Documents on Mac OS XRecipe 2.25. Changing File Attributes on WindowsRecipe 2.26. Extracting Text from OpenOffice.org DocumentsRecipe 2.27. Extracting Text from Microsoft Word DocumentsRecipe 2.28. File Locking Using a Cross-Platform APIRecipe 2.29. Versioning FilenamesRecipe 2.30. Calculating CRC-64 Cyclic Redundancy ChecksChapter 3. Time and MoneyIntroductionRecipe 3.1. Calculating Yesterday and TomorrowRecipe 3.2. Finding Last FridayRecipe 3.3. Calculating Time Periods in a Date RangeRecipe 3.4. Summing Durations of SongsRecipe 3.5. Calculating the Number of Weekdays Between Two DatesRecipe 3.6. Looking up Holidays AutomaticallyRecipe 3.7. Fuzzy Parsing of DatesRecipe 3.8. Checking Whether Daylight Saving Time Is Currently in EffectRecipe 3.9. Converting Time ZonesRecipe 3.10. Running a Command RepeatedlyRecipe 3.11. Scheduling CommandsRecipe 3.12. Doing Decimal ArithmeticRecipe 3.13. Formatting Decimals as CurrencyRecipe 3.14. Using Python as a Simple Adding MachineRecipe 3.15. Checking a Credit Card ChecksumRecipe 3.16. Watching Foreign Exchange RatesChapter 4. Python ShortcutsIntroductionRecipe 4.1. Copying an ObjectRecipe 4.2. Constructing Lists with List ComprehensionsRecipe 4.3. Returning an Element of a List If It ExistsRecipe 4.4. Looping over Items and Their Indices in a SequenceRecipe 4.5. Creating Lists of Lists Without Sharing ReferencesRecipe 4.6. Flattening a Nested SequenceRecipe 4.7. Removing or Reordering Columnsin a List of RowsRecipe 4.8. Transposing Two-Dimensional ArraysRecipe 4.9. Getting a Value from a DictionaryRecipe 4.10. Adding an Entry to a DictionaryRecipe 4.11. Building a Dictionary Without Excessive QuotingRecipe 4.12. Building a Dict from a List of Alternating Keys and ValuesRecipe 4.13. Extracting a Subset of a DictionaryRecipe 4.14. Inverting a DictionaryRecipe 4.15. Associating Multiple Values with Each Key in a DictionaryRecipe 4.16. Using a Dictionary to Dispatch Methods or FunctionsRecipe 4.17. Finding Unions and Intersections of DictionariesRecipe 4.18. Collecting a Bunch of Named ItemsRecipe 4.19. Assigning and Testing with One StatementRecipe 4.20. Using printf in PythonRecipe 4.21. Randomly Picking Items with Given ProbabilitiesRecipe 4.22. Handling Exceptions Within an ExpressionRecipe 4.23. Ensuring a Name Is Defined in a Given ModuleChapter 5. Searching and SortingIntroductionRecipe 5.1. Sorting a DictionaryRecipe 5.2. Sorting a List of Strings Case-InsensitivelyRecipe 5.3. Sorting a List of Objects by an Attribute of the ObjectsRecipe 5.4. Sorting Keys or Indices Basedon the Corresponding ValuesRecipe 5.5. Sorting Strings with Embedded NumbersRecipe 5.6. Processing All of a List''s Items in Random OrderRecipe 5.7. Keeping a Sequence Ordered as Items Are AddedRecipe 5.8. Getting the First Few Smallest Items of a SequenceRecipe 5.9. Looking for Items in a Sorted SequenceRecipe 5.10. Selecting the nth Smallest Element of a SequenceRecipe 5.11. Showing off quicksort in Three LinesRecipe 5.12. Performing Frequent Membership Tests on a SequenceRecipe 5.13. Finding SubsequencesRecipe 5.14. Enriching the Dictionary Type with Ratings FunctionalityRecipe 5.15. Sorting Names and Separating Them by InitialsChapter 6. Object-Oriented ProgrammingIntroductionRecipe 6.1. Converting Among Temperature ScalesRecipe 6.2. Defining ConstantsRecipe 6.3. Restricting Attribute SettingRecipe 6.4. Chaining Dictionary LookupsRecipe 6.5. Delegating Automatically as an Alternative to InheritanceRecipe 6.6. Delegating Special Methods in ProxiesRecipe 6.7. Implementing Tuples with Named ItemsRecipe 6.8. Avoiding Boilerplate Accessors for PropertiesRecipe 6.9. Making a Fast Copy of an ObjectRecipe 6.10. Keeping References to Bound Methods Without Inhibiting Garbage CollectionRecipe 6.11. Implementing a Ring BufferRecipe 6.12. Checking an Instance for Any State ChangesRecipe 6.13. Checking Whether an Object Has Necessary AttributesRecipe 6.14. Implementing the State Design PatternRecipe 6.15. Implementing the Recipe 6.16. Avoiding the Recipe 6.17. Implementing the Null Object Design PatternRecipe 6.18. Automatically Initializing Instance Variables from _ _init_ _ ArgumentsRecipe 6.19. Calling a Superclass _ _init_ _ Method If It ExistsRecipe 6.20. Using Cooperative Supercalls Concisely and SafelyChapter 7. Persistence and DatabasesIntroductionRecipe 7.1. Serializing Data Using the marshal ModuleRecipe 7.2. Serializing Data Using the pickle and cPickle ModulesRecipe 7.3. Using Compression with PicklingRecipe 7.4. Using the cPickle Module on Classes and InstancesRecipe 7.5. Holding Bound Methods in a Picklable WayRecipe 7.6. Pickling Code ObjectsRecipe 7.7. Mutating Objects with shelveRecipe 7.8. Using the Berkeley DB DatabaseRecipe 7.9. Accesssing a MySQL DatabaseRecipe 7.10. Storing a BLOB in a MySQL DatabaseRecipe 7.11. Storing a BLOB in a PostgreSQL DatabaseRecipe 7.12. Storing a BLOB in a SQLite DatabaseRecipe 7.13. Generating a Dictionary Mapping Field Names to Column NumbersRecipe 7.14. Using dtuple for Flexible Accessto Query ResultsRecipe 7.15. Pretty-Printing the Contents of Database CursorsRecipe 7.16. Using a Single Parameter-Passing Style Across Various DB API ModulesRecipe 7.16. Using a Single Parameter-Passing Style Across Various DB API ModulesRecipe 7.17. Using Microsoft Jet via ADORecipe 7.18. Accessing a JDBC Database from a Jython ServletRecipe 7.19. Using ODBC to Get Excel Data with JythonChapter 8. Debugging and TestingIntroductionRecipe 8.1. Disabling Execution of Some Conditionals and LoopsRecipe 8.2. Measuring Memory Usage on LinuxRecipe 8.3. Debugging the Garbage-Collection ProcessRecipe 8.4. Trapping and Recording ExceptionsRecipe 8.5. Tracing Expressions and Comments in Debug ModeRecipe 8.6. Getting More Information from TracebacksRecipe 8.7. Starting the Debugger Automatically After an Uncaught ExceptionRecipe 8.8. Running Unit Tests Most SimplyRecipe 8.9. Running Unit Tests AutomaticallyRecipe 8.10. Using doctest with unittest in Python 2.4Recipe 8.11. Checking Values Against Intervals in Unit TestingChapter 9. Processes, Threads, and SynchronizationIntroductionRecipe 9.1. Synchronizing All Methods in an ObjectRecipe 9.2. Terminating a ThreadRecipe 9.3. Using a Queue.Queue as a Priority QueueRecipe 9.4. Working with a Thread PoolRecipe 9.5. Executing a Function in Parallel on Multiple Argument SetsRecipe 9.6. Coordinating Threads by Simple Message PassingRecipe 9.7. Storing Per-Thread InformationRecipe 9.8. Multitasking Cooperatively Without ThreadsRecipe 9.9. Determining Whether Another Instanceof a Script Is Already Running in WindowsRecipe 9.10. Processing Windows Messages Using MsgWaitForMultipleObjectsRecipe 9.11. Driving an External Process with popenRecipe 9.12. Capturing the Output and Error Streams from a Unix Shell CommandRecipe 9.13. Forking a Daemon Process on UnixChapter 10. System AdministrationIntroductionRecipe 10.1. Generating Random PasswordsRecipe 10.2. Generating Easily Remembered Somewhat-Random PasswordsRecipe 10.3. Authenticating Users by Means of a POP ServerRecipe 10.4. Calculating Apache Hits per IP AddressRecipe 10.5. Calculating the Rate of Client Cache Hits on ApacheRecipe 10.6. Spawning an Editor from a ScriptRecipe 10.7. Backing Up FilesRecipe 10.8. Selectively Copying a Mailbox FileRecipe 10.9. Building a Whitelist of Email Addresses From a MailboxRecipe 10.10. Blocking Duplicate MailsRecipe 10.11. Checking Your Windows Sound SystemRecipe 10.12. Registering or Unregistering a DLL on WindowsRecipe 10.13. Checking and Modifying the Set of Tasks Windows Automatically Runs at LoginRecipe 10.14. Creating a Share on WindowsRecipe 10.15. Connecting to an Already Running Instance of Internet ExplorerRecipe 10.16. Reading Microsoft Outlook ContactsRecipe 10.17. Gathering Detailed System Informationon Mac OS XChapter 11. User InterfacesIntroductionRecipe 11.1. Showing a Progress Indicator on a Text ConsoleRecipe 11.2. Avoiding lambda in Writing Callback FunctionsRecipe 11.3. Using Default Values and Bounds with tkSimpleDialog FunctionsRecipe 11.4. Adding Drag and Drop Reordering to a Tkinter ListboxRecipe 11.5. Entering Accented Characters in Tkinter WidgetsRecipe 11.6. Embedding Inline GIFs Using TkinterRecipe 11.7. Converting Among Image FormatsRecipe 11.8. Implementing a Stopwatch in TkinterRecipe 11.9. Combining GUIs and Asynchronous I/Owith ThreadsRecipe 11.10. Using IDLE''s Tree Widget in TkinterRecipe 11.11. Supporting Multiple Values per Row in a Tkinter ListboxRecipe 11.12. Copying Geometry Methods and Options Between Tkinter WidgetsRecipe 11.13. Implementing a Tabbed Notebook for TkinterRecipe 11.14. Using a wxPython Notebook with PanelsRecipe 11.15. Implementing an ImageJ Plug-in in JythonRecipe 11.16. Viewing an Image from a URL with Swing and JythonRecipe 11.17. Getting User Input on Mac OSRecipe 11.18. Building a Python Cocoa GUI ProgrammaticallyRecipe 11.19. Implementing Fade-in Windows with IronPythonChapter 12. Processing XMLIntroductionRecipe 12.1. Checking XML Well-FormednessRecipe 12.2. Counting Tags in a DocumentRecipe 12.3. Extracting Text from an XML DocumentRecipe 12.4. Autodetecting XML EncodingRecipe 12.5. Converting an XML Document into a Tree of Python ObjectsRecipe 12.6. Removing Whitespace-only Text Nodes from an XML DOM Node''s SubtreeRecipe 12.7. Parsing Microsoft Excel''s XMLRecipe 12.8. Validating XML DocumentsRecipe 12.9. Filtering Elements and Attributes Belonging to a Given NamespaceRecipe 12.10. Merging Continuous Text Events with a SAX FilterRecipe 12.11. Using MSHTML to Parse XML or HTMLChapter 13. Network ProgrammingIntroductionRecipe 13.1. Passing Messages with Socket DatagramsRecipe 13.2. Grabbing a Document from the WebRecipe 13.3. Filtering a List of FTP SitesRecipe 13.4. Getting Time from a Server via the SNTP ProtocolRecipe 13.5. Sending HTML MailRecipe 13.6. Bundling Files in a MIME MessageRecipe 13.7. Unpacking a Multipart MIME MessageRecipe 13.8. Removing Attachments from an Email MessageRecipe 13.9. Fixing Messages Parsed by Python 2.4 email.FeedParserRecipe 13.10. Inspecting a POP3 Mailbox InteractivelyRecipe 13.11. Detecting Inactive ComputersRecipe 13.12. Monitoring a Network with HTTPRecipe 13.13. Forwarding and Redirecting Network PortsRecipe 13.14. Tunneling SSL Through a ProxyRecipe 13.15. Implementing the Dynamic IP ProtocolRecipe 13.16. Connecting to IRC and Logging Messages to DiskRecipe 13.17. Accessing LDAP ServersChapter 14. Web ProgrammingIntroductionRecipe 14.1. Testing Whether CGI Is WorkingRecipe 14.2. Handling URLs Within a CGI ScriptRecipe 14.3. Uploading Files with CGIRecipe 14.4. Checking for a Web Page''s ExistenceRecipe 14.5. Checking Content Type via HTTPRecipe 14.6. Resuming the HTTP Download of a FileRecipe 14.7. Handling Cookies While Fetching Web PagesRecipe 14.8. Authenticating with a Proxy for HTTPS NavigationRecipe 14.9. Running a Servlet with JythonRecipe 14.10. Finding an Internet Explorer CookieRecipe 14.11. Generating OPML FilesRecipe 14.12. Aggregating RSS FeedsRecipe 14.13. Turning Data into Web Pages Through TemplatesRecipe 14.14. Rendering Arbitrary Objects with NevowChapter 15. Distributed ProgrammingIntroductionRecipe 15.1. Making an XML-RPC Method CallRecipe 15.2. Serving XML-RPC RequestsRecipe 15.3. Using XML-RPC with MedusaRecipe 15.4. Enabling an XML-RPC Server to Be Terminated RemotelyRecipe 15.5. Implementing SimpleXMLRPCServer NicetiesRecipe 15.6. Giving an XML-RPC Server a wxPython GUIRecipe 15.7. Using Twisted Perspective BrokerRecipe 15.8. Implementing a CORBA Server and ClientRecipe 15.9. Performing Remote Logins Using telnetlibRecipe 15.10. Performing Remote Logins with SSHRecipe 15.11. Authenticating an SSL Client over HTTPSChapter 16. Programs About ProgramsIntroductionRecipe 16.1. Verifying Whether a String Represents a Valid NumberRecipe 16.2. Importing a Dynamically Generated ModuleRecipe 16.3. Importing from a Module Whose Name Is Determined at RuntimeRecipe 16.4. Associating Parameters with a Function (Currying)Recipe 16.4. Associating Parameters with a Function (Currying)Recipe 16.5. Composing FunctionsRecipe 16.6. Colorizing Python Source Using the Built-in Tokenizer