Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
Programming Python
A Note Regarding Supplemental Files
Preface
“And Now for Something Completely Different…”
About This Book
This Book’s Ecosystem
What This Book Is Not
About This Fourth Edition
Specific Changes in This Edition
What’s Left, Then?
Python 3.X Impacts on This Book
Specific 3.X Changes
Language Versus Library: Unicode
Python 3.1 Limitations: Email, CGI
Using Book Examples
Where to Look for Examples and Updates
Example Portability
Demo Launchers
Code Reuse Policies
Contacting O’Reilly
Conventions Used in This Book
Acknowledgments
I. The Beginning
1. A Sneak Preview
“Programming Python: The Short Story”
The Task
Step 1: Representing Records
Using Lists
Start-up pointers
A database list
Field labels
Using Dictionaries
Other ways to make dictionaries
Lists of dictionaries
Nested structures
Dictionaries of dictionaries
Step 2: Storing Records Persistently
Using Formatted Files
Test data script
File name conventions
Script start-up pointers
Data format script
Utility scripts
Using Pickle Files
Using Per-Record Pickle Files
Using Shelves
Step 3: Stepping Up to OOP
Using Classes
Adding Behavior
Adding Inheritance
Refactoring Code
Augmenting methods
Display format
Constructor customization
Alternative classes
Adding Persistence
Other Database Options
Step 4: Adding Console Interaction
A Console Shelve Interface
Step 5: Adding a GUI
GUI Basics
Using OOP for GUIs
Getting Input from a User
A GUI Shelve Interface
Coding the GUI
Using the GUI
Future directions
Step 6: Adding a Web Interface
CGI Basics
GUIs versus the Web
Running a Web Server
Using Query Strings and urllib
Formatting Reply Text
A Web-Based Shelve Interface
Coding the website
Directories, string formatting, and security
Using the website
Future directions
The End of the Demo
II. System Programming
2. System Tools
“The os.path to Knowledge”
Why Python Here?
The Next Five Chapters
System Scripting Overview
Python System Modules
Module Documentation Sources
Paging Documentation Strings
A Custom Paging Script
String Method Basics
Other String Concepts in Python 3.X: Unicode and bytes
File Operation Basics
Using Programs in Two Ways
Python Library Manuals
Commercially Published References
Introducing the sys Module
Platforms and Versions
The Module Search Path
The Loaded Modules Table
Exception Details
Other sys Module Exports
Introducing the os Module
Tools in the os Module
Administrative Tools
Portability Constants
Common os.path Tools
Running Shell Commands from Scripts
What’s a shell command?
Running shell commands
Communicating with shell commands
The subprocess module alternative
Shell command limitations
Other os Module Exports
3. Script Execution Context
“I’d Like to Have an Argument, Please”
Current Working Directory
CWD, Files, and Import Paths
CWD and Command Lines
Command-Line Arguments
Parsing Command-Line Arguments
Shell Environment Variables
Fetching Shell Variables
Changing Shell Variables
Shell Variable Fine Points: Parents, putenv, and getenv
Standard Streams
Redirecting Streams to Files and Programs
Chaining programs with pipes
Coding alternatives for adders and sorters
Redirected Streams and User Interaction
Redirecting Streams to Python Objects
The io.StringIO and io.BytesIO Utility Classes
Capturing the stderr Stream
Redirection Syntax in Print Calls
Other Redirection Options: os.popen and subprocess Revisited
Redirecting input or output with os.popen
Redirecting input and output with subprocess
4. File and Directory Tools
“Erase Your Hard Drive in Five Easy Steps!”
File Tools
The File Object Model in Python 3.X
Using Built-in File Objects
Output files
Opening
Writing
Closing
Ensuring file closure: Exception handlers and context managers
Input files
Reading lines with file iterators
Other open options
Binary and Text Files
Unicode encodings for text files
End-of-line translations for text files
Parsing packed binary data with the struct module
Random access files
Lower-Level File Tools in the os Module
Using os.open files
os.open mode flags
Wrapping descriptors in file objects
Other os module file tools
File Scanners
File filters
Directory Tools
Walking One Directory
Running shell listing commands with os.popen
The glob module
The os.listdir call
Splitting and joining listing results
Walking Directory Trees
The os.walk visitor
Recursive os.listdir traversals
Handling Unicode Filenames in 3.X: listdir, walk, glob
Unicode policies: File content versus file names
5. Parallel System Tools
“Telling the Monkeys What to Do”
Forking Processes
The fork/exec Combination
os.exec call formats
Spawned child program
Threads
The _thread Module
Basic usage
Other ways to code threads with _thread
Running multiple threads
Synchronizing access to shared objects and names
Waiting for spawned thread exits
Coding alternatives: busy loops, arguments, and context managers
The threading Module
Other ways to code threads with threading
Synchronizing access to shared objects and names revisited
The queue Module
Arguments versus globals
Program exit with child threads
Running the script
Preview: GUIs and Threads
More on the Global Interpreter Lock
The thread switch interval
Atomic operations
C API thread considerations
A process-based alternative: multiprocessing (ahead)
Program Exits
sys Module Exits
os Module Exits
Shell Command Exit Status Codes
Exit status with os.system and os.popen
Output stream buffering: A first look
Exit status with subprocess
Process Exit Status and Shared State
Thread Exits and Shared State
Interprocess Communication
Anonymous Pipes
Anonymous pipe basics
Wrapping pipe descriptors in file objects
Anonymous pipes and threads
Bidirectional IPC with anonymous pipes
Output stream buffering revisited: Deadlocks and flushes
Named Pipes (Fifos)
Named pipe basics
Named pipe use cases
Sockets: A First Look
Socket basics
Sockets and independent programs
Socket use cases
Signals
The multiprocessing Module
Why multiprocessing?
The Basics: Processes and Locks
Implementation and usage rules
IPC Tools: Pipes, Shared Memory, and Queues
multiprocessing pipes
Shared memory and globals
Queues and subclassing
Starting Independent Programs
And Much More
And a little less…
Why multiprocessing? The Conclusion
Other Ways to Start Programs
The os.spawn Calls
The os.startfile call on Windows
Using the DOS start command
Using start in Python scripts
The os.startfile call
A Portable Program-Launch Framework
Other System Tools Coverage
6. Complete System Programs
“The Greps of Wrath”
A Quick Game of “Find the Biggest Python File”
Scanning the Standard Library Directory
Scanning the Standard Library Tree
Scanning the Module Search Path
Scanning the Entire Machine
Printing Unicode Filenames
Splitting and Joining Files
Splitting Files Portably
Joining Files Portably
Usage Variations
Generating Redirection Web Pages
Page Template File
Page Generator Script
A Regression Test Script
Running the Test Driver
Copying Directory Trees
Comparing Directory Trees
Finding Directory Differences
Finding Tree Differences
Running the Script
Verifying Backups
Reporting Differences and Other Ideas
Searching Directory Trees
Greps and Globs and Finds
Rolling Your Own find Module
The fnmatch module
Cleaning Up Bytecode Files
A Python Tree Searcher
Visitor: Walking Directories “++”
Editing Files in Directory Trees (Visitor)
Global Replacements in Directory Trees (Visitor)
Counting Source Code Lines (Visitor)
Recoding Copies with Classes (Visitor)
Other Visitor Examples (External)
Playing Media Files
The Python webbrowser Module
The Python mimetypes Module
Using mimetypes guesses for SearchVisitor
Running the Script
Automated Program Launchers (External)
III. GUI Programming
7. Graphical User Interfaces
“Here’s Looking at You, Kid”
GUI Programming Topics
Running the Examples
Python GUI Development Options
tkinter Overview
tkinter Pragmatics
tkinter Documentation
tkinter Extensions
tkinter Structure
Implementation structure
Programming structure
Climbing the GUI Learning Curve
“Hello World” in Four Lines (or Less)
tkinter Coding Basics
Making Widgets
Geometry Managers
Running GUI Programs
Avoiding DOS consoles on Windows
tkinter Coding Alternatives
Widget Resizing Basics
Configuring Widget Options and Window Titles
One More for Old Times’ Sake
Packing Widgets Without Saving Them
Adding Buttons and Callbacks
Widget Resizing Revisited: Expansion
Adding User-Defined Callback Handlers
Lambda Callback Handlers
Deferring Calls with Lambdas and Object References
Callback Scope Issues
Arguments versus globals
Passing in enclosing scope values with default arguments
Passing in enclosing scope values with automatic references
But you must still sometimes use defaults instead of enclosing scopes
Bound Method Callback Handlers
Callable Class Object Callback Handlers
Other tkinter Callback Protocols
Binding Events
Adding Multiple Widgets
Widget Resizing Revisited: Clipping
Attaching Widgets to Frames
Layout: Packing Order and Side Attachments
The Packer’s Expand and Fill Revisited
Using Anchor to Position Instead of Stretch
Customizing Widgets with Classes
Standardizing Behavior and Appearance
Common behavior
Common appearance
Reusable GUI Components with Classes
Attaching Class Components
Extending Class Components
Standalone Container Classes
The End of the Tutorial
Python/tkinter for Tcl/Tk Converts
8. A tkinter Tour, Part 1
“Widgets and Gadgets and GUIs, Oh My!”
This Chapter’s Topics
Configuring Widget Appearance
Top-Level Windows
Toplevel and Tk Widgets
Top-Level Window Protocols
Dialogs
Standard (Common) Dialogs
A “smart” and reusable Quit button
A dialog demo launcher bar
Printing dialog results and passing callback data with lambdas
Letting users select colors on the fly
Other standard dialog calls
The Old-Style Dialog Module
Custom Dialogs
Making custom dialogs modal
Other ways to be modal
Binding Events
Other bind Events
More on <Destroy> events and the quit and destroy methods
Message and Entry
Message
Entry
Programming Entry widgets
Laying Out Input Forms
Going modal again
tkinter “Variables” and Form Layout Alternatives
Checkbutton, Radiobutton, and Scale
Checkbuttons
Check buttons and variables
Radio Buttons
Radio buttons and variables
Radio buttons without variables
Hold onto your variables!
Scales (Sliders)
Scales and variables
Running GUI Code Three Ways
Attaching Frames
Importing by name string
Configuring at construction time
Independent Windows
Running Programs
Launching GUIs as programs other ways: multiprocessing
Cross-program communication
Coding for reusability
Images
Fun with Buttons and Pictures
Viewing and Processing Images with PIL
PIL Basics
Displaying Other Image Types with PIL
Displaying all images in a directory
Creating Image Thumbnails with PIL
Performance: Saving thumbnail files
Layout options: Gridding
Layout options: Fixed-size buttons
Scrolling and canvases (ahead)
9. A tkinter Tour, Part 2
“On Today’s Menu: Spam, Spam, and Spam”
Menus
Top-Level Window Menus
Frame- and Menubutton-Based Menus
Using Menubuttons and Optionmenus
Windows with Both Menus and Toolbars
Using images in toolbars, too
Automating menu construction
Listboxes and Scrollbars
Programming Listboxes
Programming Scroll Bars
Packing Scroll Bars
Text
Programming the Text Widget
Text is a Python string
String positions
Text indexes
Text marks
Text tags
Adding Text-Editing Operations
Using the clipboard
Composition versus inheritance
It’s called “Simple” for a reason: PyEdit (ahead)
Unicode and the Text Widget
String types in the Text widget
Unicode text in strings
Unicode text in files
Unicode and the Text widget
The problem with treating text as bytes
Other binary mode considerations
Supporting Unicode in PyEdit (ahead)
Advanced Text and Tag Operations
Canvas
Basic Canvas Operations
Programming the Canvas Widget
Coordinates
Object construction
Object identifiers and operations
Canvas object tags
Scrolling Canvases
Scrollable Canvases and Image Thumbnails
Scrolling images too: PyPhoto (ahead)
Using Canvas Events
Binding events on specific items
Grids
Why Grids?
Grid Basics: Input Forms Revisited
Comparing grid and pack
Combining grid and pack
Making Gridded Widgets Expandable
Resizing in grids
Spanning columns and rows
Laying Out Larger Tables with grid
Time Tools, Threads, and Animation
Using Threads with tkinter GUIs
Using the after Method
Hiding and redrawing widgets and windows
Simple Animation Techniques
Using time.sleep loops
Using widget.after events
Using multiple time.sleep loop threads
Other Animation Topics
Other animation effects
Threads and animation
Graphics and gaming toolkits
The End of the Tour
Other Widgets and Options
10. GUI Coding Techniques
“Building a Better Mousetrap”
GuiMixin: Common Tool Mixin Classes
Widget Builder Functions
Mixin Utility Classes
GuiMaker: Automating Menus and Toolbars
Subclass Protocols
GuiMaker Classes
GuiMaker Self-Test
BigGui: A Client Demo Program
ShellGui: GUIs for Command-Line Tools
A Generic Shell-Tools Display
Application-Specific Tool Set Classes
Adding GUI Frontends to Command Lines
Non-GUI scripts
GUI input dialogs
Room for improvement
GuiStreams: Redirecting Streams to Widgets
Using Redirection for the Packing Scripts
Reloading Callback Handlers Dynamically
Wrapping Up Top-Level Window Interfaces
GUIs, Threads, and Queues
Placing Data on Queues
Recoding with classes and bound methods
Thread exits in GUIs
Placing Callbacks on Queues
Passing bound method callbacks on queues
More Ways to Add GUIs to Non-GUI Code
Popping Up GUI Windows on Demand
Adding a GUI As a Separate Program: Sockets (A Second Look)
Adding a GUI As a Separate Program: Command Pipes
The specter of blocking input calls
Updating GUIs within threads…and other nonsolutions
Avoiding blocking input calls with non-GUI threads
Sockets and pipes: Compare and contrast
Other uses for threaded pipe GUIs
The PyDemos and PyGadgets Launchers
PyDemos Launcher Bar (Mostly External)
PyGadgets Launcher Bar
11. Complete GUI Programs
“Python, Open Source, and Camaros”
Examples in Other Chapters
This Chapter’s Strategy
PyEdit: A Text Editor Program/Object
Running PyEdit
Menus and toolbars
Dialogs
Running program code
Multiple windows
Other PyEdit examples and screenshots in this book
PyEdit Changes in Version 2.0 (Third Edition)
Font dialog
Undo, redo, and modified tests
Configuration module
PyEdit Changes in Version 2.1 (Fourth Edition)
Modal dialog state fix
Cross-process change tests on Quit
New Grep dialog: Threaded and Unicode-aware file tree search
Grep threading model
Grep Unicode model
Update for initial positioning
Improvements for running code
Unicode (Internationalized) text support
Unicode file and display model
Unicode options and choices
More on Quit checks: The <Destroy> event revisited
PyEdit Source Code
User configurations file
Windows (and other) launch files
Main implementation file
PyPhoto: An Image Viewer and Resizer
Running PyPhoto
PyPhoto Source Code
PyView: An Image and Notes Slideshow
Running PyView
Embedding PyEdit in PyView
PyView Source Code
PyDraw: Painting and Moving Graphics
Running PyDraw
PyDraw Source Code
PyClock: An Analog/Digital Clock Widget
A Quick Geometry Lesson
Running PyClock
PyClock Source Code
PyToe: A Tic-Tac-Toe Game Widget
Running PyToe
PyToe Source Code (External)
Where to Go from Here
IV. Internet Programming
12. Network Scripting
“Tune In, Log On, and Drop Out”
Internet Scripting Topics
What we will cover
What we won’t cover
Other themes in this part of the book
Running Examples in This Part of the Book
Python Internet Development Options
Plumbing the Internet
The Socket Layer
Machine identifiers
The Protocol Layer
Port number rules
Clients and servers
Protocol structures
Python’s Internet Library Modules
Socket Programming
Socket Basics
Server socket calls
Transferring byte strings and objects
Client socket calls
Running Socket Programs Locally
Running Socket Programs Remotely
Socket pragmatics
Spawning Clients in Parallel
Preview: Denied client connections
Talking to Reserved Ports
Binding reserved port servers
Handling Multiple Clients
Forking Servers
Running the forking server
Other run modes: Local servers with Cygwin and remote clients
Forked processes and sockets
Exiting from children
Killing the zombies: Don’t fear the reaper!
Preventing zombies with signal handlers on Linux
Why multiprocessing doesn’t help with socket server portability
Threading Servers
Standard Library Server Classes
Multiplexing Servers with select
A select-based echo server
Running the select server
Summary: Choosing a Server Scheme
Making Sockets Look Like Files and Streams
A Stream Redirection Utility
Text-mode files and buffered output streams
Stream requirements
Line buffering
Solutions
Buffering in other contexts: Command pipes revisited
Sockets versus command pipes
A Simple Python File Server
Running the File Server and Clients
Adding a User-Interface Frontend
Using row frames and command lines
Using grids and function calls
Using a reusable form-layout class
13. Client-Side Scripting
“Socket to Me!”
FTP: Transferring Files over the Net
Transferring Files with ftplib
Using urllib to Download Files
FTP get and put Utilities
Download utility
Upload utility
Playing the Monty Python theme song
Adding a User Interface
Transferring Directories with ftplib
Downloading Site Directories
Uploading Site Directories
Refactoring Uploads and Downloads for Reuse
Refactoring with functions
Refactoring with classes
Transferring Directory Trees with ftplib
Uploading Local Trees
Deleting Remote Trees
Downloading Remote Trees
Processing Internet Email
Unicode in Python 3.X and Email Tools
POP: Fetching Email
Mail Configuration Module
POP Mail Reader Script
Fetching Messages
Fetching Email at the Interactive Prompt
SMTP: Sending Email
SMTP Mail Sender Script
Sending Messages
Verifying receipt
Manipulating both From and To
Sending Email at the Interactive Prompt
email: Parsing and Composing Mail Content
Message Objects
Basic email Package Interfaces in Action
Handling multipart messages
Unicode, Internationalization, and the Python 3.1 email Package
Parser decoding requirement
Text payload encodings: Handling mixed type results
Text payload encodings: Using header information to decode
Message header encodings: email package support
Message address header encodings and parsing, and header creation
Workaround: Message text generation for binary attachment payloads is broken
Workaround: Message composition for non-ASCII text parts is broken
Summary: Solutions and workarounds
A Console-Based Email Client
Running the pymail Console Client
The mailtools Utility Package
Initialization File
MailTool Class
MailSender Class
Unicode issues for attachments, save files, and headers
MailFetcher Class
General usage
Unicode decoding for full mail text on fetches
Inbox synchronization tools
MailParser Class
Unicode decoding for text part payloads and message headers
Self-Test Script
Running the self-test
Updating the pymail Console Client
Running the pymail2 console client
NNTP: Accessing Newsgroups
HTTP: Accessing Websites
The urllib Package Revisited
Other urllib Interfaces
Invoking programs and escaping text
Other Client-Side Scripting Options
14. The PyMailGUI Client
“Use the Source, Luke”
Source Code Modules and Size
Code size
Code Structure
Why PyMailGUI?
Running PyMailGUI
Presentation Strategy
Major PyMailGUI Changes
New in Version 2.1 and 2.0 (Third Edition)
New in Version 3.0 (Fourth Edition)
Version 3.0 Unicode support policies
A PyMailGUI Demo
Getting Started
Loading Mail
Threading Model
Threading model implementation
Load Server Interface
Offline Processing with Save and Open
Sending Email and Attachments
Viewing Email and Attachments
Email Replies and Forwards and Recipient Options
Deleting Email
POP Message Numbers and Synchronization
Handling HTML Content in Email
Mail Content Internationalization Support
Alternative Configurations and Accounts
Multiple Windows and Status Messages
PyMailGUI Implementation
PyMailGUI: The Main Module
SharedNames: Program-Wide Globals
ListWindows: Message List Windows
ViewWindows: Message View Windows
messagecache: Message Cache Manager
popuputil: General-Purpose GUI Pop Ups
wraplines: Line Split Tools
html2text: Extracting Text from HTML (Prototype, Preview)
mailconfig: User Configurations
textConfig: Customizing Pop-Up PyEdit Windows
PyMailGUIHelp: User Help Text and Display
altconfigs: Configuring for Multiple Accounts
Ideas for Improvement
15. Server-Side Scripting
“Oh, What a Tangled Web We Weave”
What’s a Server-Side CGI Script?
The Script Behind the Curtain
Writing CGI Scripts in Python
Running Server-Side Examples
Web Server Options
Running a Local Web Server
The Server-Side Examples Root Page
Viewing Server-Side Examples and Output
Climbing the CGI Learning Curve
A First Web Page
HTML basics
Internet addresses (URLs)
Using minimal URLs
HTML file permission constraints
A First CGI Script
Installing CGI scripts
Finding Python on remote servers
Adding Pictures and Generating Tables
Table tags
Adding User Interaction
Submission page
More on form tags
Response script
Passing parameters in URLs
Testing outside browsers with the module urllib.request
Using Tables to Lay Out Forms
Converting strings in CGI scripts
Debugging CGI scripts
Adding Common Input Devices
Changing Input Layouts
Keeping display and logic separate
Passing Parameters in Hardcoded URLs
Passing Parameters in Hidden Form Fields
Saving State Information in CGI Scripts
URL Query Parameters
Hidden Form Input Fields
HTTP “Cookies”
Creating a cookie
Receiving a cookie
Using cookies in CGI scripts
Handling cookies with the urllib.request module
Server-Side Databases
Extensions to the CGI Model
Combining Techniques
The Hello World Selector
Checking for Missing and Invalid Inputs
Refactoring Code for Maintainability
Step 1: Sharing Objects Between Pages—A New Input Form
Step 2: A Reusable Form Mock-Up Utility
Step 3: Putting It All Together—A New Reply Script
More on HTML and URL Escapes
URL Escape Code Conventions
Python HTML and URL Escape Tools
Escaping HTML Code
Escaping URLs
Escaping URLs Embedded in HTML Code
HTML and URL conflicts: &
Avoiding conflicts
Transferring Files to Clients and Servers
Displaying Arbitrary Server Files on the Client
Handling private files and errors
Uploading Client Files to the Server
Handling client path formats
More Than One Way to Push Bits over the Net
16. The PyMailCGI Server
“Things to Do When Visiting Chicago”
The PyMailCGI Website
Implementation Overview
New in This Fourth Edition (Version 3.0)
New in the Prior Edition (Version 2.0)
Presentation Overview
Running This Chapter’s Examples
The Root Page
Configuring PyMailCGI
Sending Mail by SMTP
The Message Composition Page
The Send Mail Script
Error Pages
Common Look-and-Feel
Using the Send Mail Script Outside a Browser
Reading POP Email
The POP Password Page
The Mail Selection List Page
Passing State Information in URL Link Parameters
Security Protocols
Reading mail with direct URLs
The Message View Page
Passing State Information in HTML Hidden Input Fields
Escaping Mail Text and Passwords in HTML
Processing Fetched Mail
Reply and Forward
Delete
Deletions and POP Message Numbers
Inbox synchronization error potential
Alternative: Passing header text in hidden input fields (PyMailCGI_2.1)
Alternative: Server-side files for headers
Alternative: Delete on load
Utility Modules
External Components and Configuration
POP Mail Interface
POP Password Encryption
Manual data encryption: rotor (defunct)
Manual data encryption: PyCrypto
HTTPS: Secure HTTP transmissions
Secure cookies
The secret.py module
Rolling your own encryptor
Common Utilities Module
Web Scripting Trade-Offs
PyMailCGI Versus PyMailGUI
The Web Versus the Desktop
Other Approaches
V. Tools and Techniques
17. Databases and Persistence
“Give Me an Order of Persistence, but Hold the Pickles”
Persistence Options in Python
DBM Files
Using DBM Files
DBM Details: Files, Portability, and Close
Pickled Objects
Using Object Pickling
Pickling in Action
Pickle Details: Protocols, Binary Modes, and _pickle
Shelve Files
Using Shelves
Storing Built-in Object Types in Shelves
Storing Class Instances in Shelves
Changing Classes of Objects Stored in Shelves
Shelve Constraints
Keys must be strings (and str)
Objects are unique only within a key
Updates must treat shelves as fetch-modify-store mappings
Concurrent updates are not directly supported
Underlying DBM format portability
Pickled Class Constraints
Other Shelve Limitations
The ZODB Object-Oriented Database
The Mostly Missing ZODB Tutorial
SQL Database Interfaces
SQL Interface Overview
An SQL Database API Tutorial with SQLite
Getting started
Making databases and tables
Adding records
Running queries
Running updates
Building Record Dictionaries
Using table descriptions
Record dictionaries construction
Automating with scripts and modules
Tying the Pieces Together
Loading Database Tables from Files
Loading with SQL and Python
Python versus SQL
SQL Utility Scripts
Table load scripts
Table display script
Using the scripts
SQL Resources
ORMs: Object Relational Mappers
PyForm: A Persistent Object Viewer (External)
18. Data Structures
“Roses Are Red, Violets Are Blue; Lists Are Mutable, and So Is Set Foo”
Implementing Stacks
Built-in Options
A Stack Module
A Stack Class
Customization: Performance Monitors
Optimization: Tuple Tree Stacks
Optimization: In-Place List Modifications
Timing the Improvements
Results under Python 3.1
More on performance analysis
Implementing Sets
Built-in Options
Set Functions
Supporting multiple operands
Set Classes
Optimization: Moving Sets to Dictionaries
Timing the results under Python 3.1
Adding Relational Algebra to Sets (External)
Subclassing Built-in Types
Binary Search Trees
Built-in Options
Implementing Binary Trees
Trees with Both Keys and Values
Graph Searching
Implementing Graph Search
Moving Graphs to Classes
Permuting Sequences
Reversing and Sorting Sequences
Implementing Reversals
Implementing Sorts
Adding comparison functions
Data Structures Versus Built-ins: The Conclusion
PyTree: A Generic Tree Object Viewer
19. Text and Language
“See Jack Hack. Hack, Jack, Hack”
Strategies for Processing Text in Python
String Method Utilities
Templating with Replacements and Formats
Parsing with Splits and Joins
Summing Columns in a File
Summing with zips and comprehensions
Summing with dictionaries
Parsing and Unparsing Rule Strings
More on the holmes expert system shell
Regular Expression Pattern Matching
The re Module
First Examples
String Operations Versus Patterns
Using the re Module
Module functions
Compiled pattern objects
Match objects
Regular expression patterns
More Pattern Examples
Scanning C Header Files for Patterns
XML and HTML Parsing
XML Parsing in Action
Regular expression parsing
SAX parsing
DOM parsing
ElementTree parsing
Other XML topics
HTML Parsing in Action
Handling HTML entity references (revisited)
Extracting plain text from HTML (revisited)
Advanced Language Tools
Custom Language Parsers
The Expression Grammar
The Parser’s Code
Adding a Parse Tree Interpreter
Parse Tree Structure
Exploring Parse Trees with the PyTree GUI
Parsers Versus Python
PyCalc: A Calculator Program/Object
A Simple Calculator GUI
Building the GUI
Running code strings
Extending and attaching
PyCalc—A “Real” Calculator GUI
Running PyCalc
Evaluating expressions with stacks
PyCalc source code
Using PyCalc as a component
Adding new buttons in new components
20. Python/C Integration
“I Am Lost at C”
Extending and Embedding
Extending Python in C: Overview
A Simple C Extension Module
The SWIG Integration Code Generator
A Simple SWIG Example
Wrapping C Environment Calls
Adding Wrapper Classes to Flat Libraries
Wrapping C Environment Calls with SWIG
Wrapping C++ Classes with SWIG
A Simple C++ Extension Class
Wrapping the C++ Class with SWIG
Using the C++ Class in Python
Using the low-level extension module
Subclassing the C++ class in Python
Exploring the wrappers interactively
Other Extending Tools
Embedding Python in C: Overview
The C Embedding API
What Is Embedded Code?
Basic Embedding Techniques
Running Simple Code Strings
Compiling and running
Running Code Strings with Results and Namespaces
Calling Python Objects
Running Strings in Dictionaries
Precompiling Strings to Bytecode
Registering Callback Handler Objects
Registration Implementation
Using Python Classes in C
Other Integration Topics
VI. The End
21. Conclusion: Python and the Development Cycle
“That’s the End of the Book, Now Here’s the Meaning of Life”
“Something’s Wrong with the Way We Program Computers”
The “Gilligan Factor”
Doing the Right Thing
The Static Language Build Cycle
Artificial Complexities
One Language Does Not Fit All
Enter Python
But What About That Bottleneck?
Python Provides Immediate Turnaround
Python Is “Executable Pseudocode”
Python Is OOP Done Right
Python Fosters Hybrid Applications
On Sinking the Titanic
So What’s “Python: The Sequel”?
In the Final Analysis…
Index
About the Author
Colophon
← Prev
Back
Next →
← Prev
Back
Next →