My Account
View Cart
Home
Community
Books & Videos
Safari Books Online
Conferences
Training
School of Technology
About
Complete List
Bestsellers
New Releases
Rough Cuts
Upcoming Titles
Ebooks
By Publisher
By Series
Out of Print
Order Info
Search
Search Tips
Tell a friend
Python Cookbook, Second Edition
By
Alex Martelli
,
Anna Martelli Ravenscroft
,
David Ascher
March 2005
Pages: 844
|
Table of Contents
|
Index
|
Sample Chapter
|
Colophon
Table of Contents
Chapter 1
Text
Introduction
Processing a String One Character at a Time
Converting Between Characters and Numeric Codes
Testing Whether an Object Is String-like
Aligning Strings
Trimming Space from the Ends of a String
Combining Strings
Reversing a String by Words or Characters
Checking Whether a String Contains a Set of Characters
Simplifying Usage of Strings' translate Method
Filtering a String for a Set of Characters
Checking Whether a String Is Text or Binary
Controlling Case
Accessing Substrings
Changing the Indentation of a Multiline String
Expanding and Compressing Tabs
Interpolating Variables in a String
Interpolating Variables in a Stringin Python 2.4
Replacing Multiple Patterns in a Single Pass
Checking a String for Any of Multiple Endings
Handling International Text with Unicode
Converting Between Unicode and Plain Strings
Printing Unicode Charactersto Standard Output
Encoding Unicode Data for XML and HTML
Making Some Strings Case-Insensitive
Converting HTML Documents to Texton a Unix Terminal
Chapter 2
Files
Introduction
Reading from a File
Writing to a File
Searching and Replacing Text in a File
Reading a Specific Line from a File
Counting Lines in a File
Processing Every Word in a File
Using Random-Access Input/Output
Updating a Random-Access File
Reading Data from zip Files
Handling a zip File Inside a String
Archiving a Tree of Files into a Compressed tar File
Sending Binary Data to Standard Output Under Windows
Using a C++-like iostream Syntax
Rewinding an Input File to the Beginning
Adapting a File-like Object to a True File Object
Walking Directory Trees
Swapping One File Extension for Another Throughout a Directory Tree
Finding a File Given a Search Path
Finding Files Given a Search Path and a Pattern
Finding a File on the Python Search Path
Dynamically Changing the PythonSearch Path
Computing the Relative Path from One Directory to Another
Reading an Unbuffered Character in a Cross-Platform Way
Counting Pages of PDF Documents on Mac OS X
Changing File Attributes on Windows
Extracting Text from OpenOffice.org Documents
Extracting Text from Microsoft Word Documents
File Locking Using a Cross-Platform API
Versioning Filenames
Calculating CRC-64 Cyclic Redundancy Checks
Chapter 3
Time and Money
Introduction
Calculating Yesterday and Tomorrow
Finding Last Friday
Calculating Time Periods in a Date Range
Summing Durations of Songs
Calculating the Number of Weekdays Between Two Dates
Looking up Holidays Automatically
Fuzzy Parsing of Dates
Checking Whether Daylight Saving Time Is Currently in Effect
Converting Time Zones
Running a Command Repeatedly
Scheduling Commands
Doing Decimal Arithmetic
Formatting Decimals as Currency
Using Python as a Simple Adding Machine
Checking a Credit Card Checksum
Watching Foreign Exchange Rates
Chapter 4
Python Shortcuts
Introduction
Copying an Object
Constructing Lists with List Comprehensions
Returning an Element of a List If It Exists
Looping over Items and Their Indices in a Sequence
Creating Lists of Lists Without Sharing References
Flattening a Nested Sequence
Removing or Reordering Columnsin a List of Rows
Transposing Two-Dimensional Arrays
Getting a Value from a Dictionary
Adding an Entry to a Dictionary
Building a Dictionary Without Excessive Quoting
Building a Dict from a List of Alternating Keys and Values
Extracting a Subset of a Dictionary
Inverting a Dictionary
Associating Multiple Values with Each Key in a Dictionary
Using a Dictionary to Dispatch Methods or Functions
Finding Unions and Intersections of Dictionaries
Collecting a Bunch of Named Items
Assigning and Testing with One Statement
Using printf in Python
Randomly Picking Items with Given Probabilities
Handling Exceptions Within an Expression
Ensuring a Name Is Defined in a Given Module
Chapter 5
Searching and Sorting
Introduction
Sorting a Dictionary
Sorting a List of Strings Case-Insensitively
Sorting a List of Objects by an Attribute of the Objects
Sorting Keys or Indices Basedon the Corresponding Values
Sorting Strings with Embedded Numbers
Processing All of a List's Items in Random Order
Keeping a Sequence Ordered as Items Are Added
Getting the First Few Smallest Items of a Sequence
Looking for Items in a Sorted Sequence
Selecting the nth Smallest Element of a Sequence
Showing off quicksort in Three Lines
Performing Frequent Membership Tests on a Sequence
Finding Subsequences
Enriching the Dictionary Type with Ratings Functionality
Sorting Names and Separating Them by Initials
Chapter 6
Object-Oriented Programming
Introduction
Converting Among Temperature Scales
Defining Constants
Restricting Attribute Setting
Chaining Dictionary Lookups
Delegating Automatically as an Alternative to Inheritance
Delegating Special Methods in Proxies
Implementing Tuples with Named Items
Avoiding Boilerplate Accessors for Properties
Making a Fast Copy of an Object
Keeping References to Bound Methods Without Inhibiting Garbage Collection
Implementing a Ring Buffer
Checking an Instance for Any State Changes
Checking Whether an Object Has Necessary Attributes
Implementing the State Design Pattern
Implementing the "Singleton" Design Pattern
Avoiding the "Singleton" Design Pattern with the Borg Idiom
Implementing the Null Object Design Pattern
Automatically Initializing Instance Variables from _ _init_ _ Arguments
Calling a Superclass _ _init_ _ Method If It Exists
Using Cooperative Supercalls Concisely and Safely
Chapter 7
Persistence and Databases
Introduction
Serializing Data Using the marshal Module
Serializing Data Using the pickle and cPickle Modules
Using Compression with Pickling
Using the cPickle Module on Classes and Instances
Holding Bound Methods in a Picklable Way
Pickling Code Objects
Mutating Objects with shelve
Using the Berkeley DB Database
Accessing a MySQL Database
Storing a BLOB in a MySQL Database
Storing a BLOB in a PostgreSQL Database
Storing a BLOB in a SQLite Database
Generating a Dictionary Mapping Field Names to Column Numbers
Using dtuple for Flexible Accessto Query Results
Pretty-Printing the Contents of Database Cursors
Using a Single Parameter-Passing Style Across Various DB API Modules
Using Microsoft Jet via ADO
Accessing a JDBC Database from a Jython Servlet
Using ODBC to Get Excel Data with Jython
Chapter 8
Debugging and Testing
Introduction
Disabling Execution of Some Conditionals and Loops
Measuring Memory Usage on Linux
Debugging the Garbage-Collection Process
Trapping and Recording Exceptions
Tracing Expressions and Comments in Debug Mode
Getting More Information from Tracebacks
Starting the Debugger Automatically After an Uncaught Exception
Running Unit Tests Most Simply
Running Unit Tests Automatically
Using doctest with unittest in Python 2.4
Checking Values Against Intervals in Unit Testing
Chapter 9
Processes, Threads, and Synchronization
Introduction
Synchronizing All Methods in an Object
Terminating a Thread
Using a Queue.Queue as a Priority Queue
Working with a Thread Pool
Executing a Function in Parallel on Multiple Argument Sets
Coordinating Threads by Simple Message Passing
Storing Per-Thread Information
Multitasking Cooperatively Without Threads
Determining Whether Another Instanceof a Script Is Already Running in Windows
Processing Windows Messages Using MsgWaitForMultipleObjects
Driving an External Process with popen
Capturing the Output and Error Streams from a Unix Shell Command
Forking a Daemon Process on Unix
Chapter 10
System Administration
Introduction
Generating Random Passwords
Generating Easily Remembered Somewhat-Random Passwords
Authenticating Users by Means of a POP Server
Calculating Apache Hits per IP Address
Calculating the Rate of Client Cache Hits on Apache
Spawning an Editor from a Script
Backing Up Files
Selectively Copying a Mailbox File
Building a Whitelist of Email Addresses From a Mailbox
Blocking Duplicate Mails
Checking Your Windows Sound System
Registering or Unregistering a DLL on Windows
Checking and Modifying the Set of Tasks Windows Automatically Runs at Login
Creating a Share on Windows
Connecting to an Already Running Instance of Internet Explorer
Reading Microsoft Outlook Contacts
Gathering Detailed System Informationon Mac OS X
Chapter 11
User Interfaces
Introduction
Showing a Progress Indicator on a Text Console
Avoiding lambda in Writing Callback Functions
Using Default Values and Bounds with tkSimpleDialog Functions
Adding Drag and Drop Reordering to a Tkinter Listbox
Entering Accented Characters in Tkinter Widgets
Embedding Inline GIFs Using Tkinter
Converting Among Image Formats
Implementing a Stopwatch in Tkinter
Combining GUIs and Asynchronous I/Owith Threads
Using IDLE's Tree Widget in Tkinter
Supporting Multiple Values per Row in a Tkinter Listbox
Copying Geometry Methods and Options Between Tkinter Widgets
Implementing a Tabbed Notebook for Tkinter
Using a wxPython Notebook with Panels
Implementing an ImageJ Plug-in in Jython
Viewing an Image from a URL with Swing and Jython
Getting User Input on Mac OS
Building a Python Cocoa GUI Programmatically
Implementing Fade-in Windows with IronPython
Chapter 12
Processing XML
Introduction
Checking XML Well-Formedness
Counting Tags in a Document
Extracting Text from an XML Document
Autodetecting XML Encoding
Converting an XML Document into a Tree of Python Objects
Removing Whitespace-only Text Nodes from an XML DOM Node's Subtree
Parsing Microsoft Excel's XML
Validating XML Documents
Filtering Elements and Attributes Belonging to a Given Namespace
Merging Continuous Text Events with a SAX Filter
Using MSHTML to Parse XML or HTML
Chapter 13
Network Programming
Introduction
Passing Messages with Socket Datagrams
Grabbing a Document from the Web
Filtering a List of FTP Sites
Getting Time from a Server via the SNTP Protocol
Sending HTML Mail
Bundling Files in a MIME Message
Unpacking a Multipart MIME Message
Removing Attachments from an Email Message
Fixing Messages Parsed by Python 2.4 email.FeedParser
Inspecting a POP3 Mailbox Interactively
Detecting Inactive Computers
Monitoring a Network with HTTP
Forwarding and Redirecting Network Ports
Tunneling SSL Through a Proxy
Implementing the Dynamic IP Protocol
Connecting to IRC and Logging Messages to Disk
Accessing LDAP Servers
Chapter 14
Web Programming
Introduction
Testing Whether CGI Is Working
Handling URLs Within a CGI Script
Uploading Files with CGI
Checking for a Web Page's Existence
Checking Content Type via HTTP
Resuming the HTTP Download of a File
Handling Cookies While Fetching Web Pages
Authenticating with a Proxy for HTTPS Navigation
Running a Servlet with Jython
Finding an Internet Explorer Cookie
Generating OPML Files
Aggregating RSS Feeds
Turning Data into Web Pages Through Templates
Rendering Arbitrary Objects with Nevow
Chapter 15
Distributed Programming
Introduction
Making an XML-RPC Method Call
Serving XML-RPC Requests
Using XML-RPC with Medusa
Enabling an XML-RPC Server to Be Terminated Remotely
Implementing SimpleXMLRPCServer Niceties
Giving an XML-RPC Server a wxPython GUI
Using Twisted Perspective Broker
Implementing a CORBA Server and Client
Performing Remote Logins Using telnetlib
Performing Remote Logins with SSH
Authenticating an SSL Client over HTTPS
Chapter 16
Programs About Programs
Introduction
Verifying Whether a String Represents a Valid Number
Importing a Dynamically Generated Module
Importing from a Module Whose Name Is Determined at Runtime
Associating Parameters with a Function (Currying)
Composing Functions
Colorizing Python Source Using the Built-in Tokenizer
Merging and Splitting Tokens
Checking Whether a String Has Balanced Parentheses
Simulating Enumerations in Python
Referring to a List Comprehension While Building It
Automating the py2exe Compilation of Scripts into Windows Executables
Binding Main Script and Modules into One Executable on Unix
Chapter 17
Extending and Embedding
Introduction
Implementing a Simple Extension Type
Implementing a Simple Extension Type with Pyrex
Exposing a C++ Library to Python
Calling Functions from a Windows DLL
Using SWIG-Generated Modules in a Multithreaded Environment
Translating a Python Sequence into a C Array with the PySequence_Fast Protocol
Accessing a Python Sequence Item-by-Item with the Iterator Protocol
Returning None from a Python-Callable C Function
Debugging Dynamically Loaded C Extensions with gdb
Debugging Memory Problems
Chapter 18
Algorithms
Introduction
Removing Duplicates from a Sequence
Removing Duplicates from a Sequence While Maintaining Sequence Order
Generating Random Samples with Replacement
Generating Random Samples Without Replacement
Memoizing (Caching) the Return Values of Functions
Implementing a FIFO Container
Caching Objects with a FIFO Pruning Strategy
Implementing a Bag (Multiset) Collection Type
Simulating the Ternary Operator in Python
Computing Prime Numbers
Formatting Integers as Binary Strings
Formatting Integers as Strings in Arbitrary Bases
Converting Numbers to Rationals via Farey Fractions
Doing Arithmetic with Error Propagation
Summing Numbers with Maximal Accuracy
Simulating Floating Point
Computing the Convex Hulls and Diameters of 2D Point Sets
Chapter 19
Iterators and Generators
Introduction
Writing a range-like Function with Float Increments
Building a List from Any Iterable
Generating the Fibonacci Sequence
Unpacking a Few Items in a Multiple Assignment
Automatically Unpacking the Needed Number of Items
Dividing an Iterable into n Slices of Stride n
Looping on a Sequence by Overlapping Windows
Looping Through Multiple Iterables in Parallel
Looping Through the Cross-Product of Multiple Iterables
Reading a Text File by Paragraphs
Reading Lines with Continuation Characters
Iterating on a Stream of Data Blocks as a Stream of Lines
Fetching Large Record Sets from a Database with a Generator
Merging Sorted Sequences
Generating Permutations, Combinations, and Selections
Generating the Partitions of an Integer
Duplicating an Iterator
Looking Ahead into an Iterator
Simplifying Queue-Consumer Threads
Running an Iterator in Another Thread
Computing a Summary Report with itertools.groupby
Chapter 20
Descriptors, Decorators,and Metaclasses
Introduction
Getting Fresh Default Values at Each Function Call
Coding Properties as Nested Functions
Aliasing Attribute Values
Caching Attribute Values
Using One Method as Accessorfor Multiple Attributes
Adding Functionality to a Class by Wrapping a Method
Adding Functionality to a Class by Enriching All Methods
Adding a Method to a Class Instance at Runtime
Checking Whether Interfaces Are Implemented
Using _ _new_ _ and _ _init_ _ Appropriately in Custom Metaclasses
Allowing Chaining of Mutating List Methods
Using Cooperative Super calls with Terser Syntax
Initializing Instance Attributes Without Using _ _init_ _
Automatic Initialization of Instance Attributes
Upgrading Class Instances Automatically on reload
Binding Constants at Compile Time
Solving Metaclass Conflicts
Colophon
Return to
Python Cookbook