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