Programming Python, Second Edition

Book description

Programming Python focuses on advanced uses of the Python programming/scripting language, which has evolved from an emerging language of interest primarily to pioneers, to a widely accepted tool that traditional programmers use for real day-to-day development tasks. With Python, you can do almost anything you can do with C++; but Python is an interpreted language designed for rapid application development and deployment. Among other things, Python supports object-oriented programming; a remarkably simple, readable, and maintainable syntax; integration with C components; and a vast collection of pre-coded interfaces and utilities. As Python has grown to embrace developers on a number of different platforms (Unix, Linux, Windows, Mac), companies have taken notice and are adopting Python for their products. It has shown up animating the latest Star Wars movie, serving up maps and directories on the Internet, guiding users through Linux installations, testing chips and boards, managing Internet discussion forums, scripting online games, and even scripting wireless products. Programming Python is the most comprehensive resource for advanced Python programmers available today. Reviewed and endorsed by Python creator Guido van Rossum, who also provides the foreword, this book zeroes in on real-world Python applications. It's been updated for Python 2.0 and covers Internet scripting, systems programming, Tkinter GUIs, C integration domains, and new Python tools and applications. Among them: IDLE, JYthon, Active Scripting and COM extensions, Zope, PSP server pages, restricted execution mode, the HTMLgen and SWIG code generators, thread support, CGI and Internet protocol modules. Such applications are the heart and soul of this second edition. Veteran O'Reilly author Mark Lutz has included a platform-neutral CD-ROM with book examples and various Python-related packages, including the full Python 2.0 source code distribution.

Table of contents

  1. Programming Python, 2nd Edition
    1. Foreword
    2. Preface
      1. “And Now for Something Completely Different . . . Again”
      2. Signs of the Python Times
      3. Why This Edition?
      4. Major Changes in This Edition
        1. It’s Been Updated for Python 2.0
        2. It’s Been Refocused for a More Advanced Audience
        3. It Covers New Topics
        4. It’s More Example-Oriented
        5. It’s More Platform-Neutral
      5. Using the Examples and Demos
        1. The Short Story
        2. The Details
        3. Where It’s At
      6. Conventions Used in This Book
      7. Where to Look for Updates
      8. Contacting O’Reilly
      9. Acknowledgments
    3. 1. Introducing Python
      1. “And Now for Something Completely Different”
      2. The Life of Python
      3. The Compulsory Features List
      4. What’s Python Good For?
      5. What’s Python Not Good For?
    4. I. System Interfaces
      1. 2. System Tools
        1. “The os.path to Knowledge”
        2. Why Python Here?
        3. System Scripting Overview
          1. Python System Modules
          2. Module Documentation Sources
          3. Paging Documentation Strings
          4. Introducing the string Module
          5. File Operation Basics
          6. Using Programs Two Ways
          7. Python Library Manuals
          8. Commercially Published References
        4. The sys Module
          1. Platforms and Versions
          2. The Module Search Path
          3. The Loaded Modules Table
          4. Exception Details
          5. Other sys Module Exports
        5. The os Module
          1. The Big os Lists
          2. Administrative Tools
          3. Portability Constants
          4. Basic os.path Tools
          5. Running Shell Commands from Scripts
            1. What’s a shell command?
            2. Running shell commands
            3. Communicating with shell commands
            4. Shell command limitations
          6. Other os Module Exports
        6. Script Execution Context
        7. Current Working Directory
          1. CWD, Files, and Import Paths
          2. CWD and Command Lines
        8. Command-Line Arguments
        9. Shell Environment Variables
          1. Fetching Shell Variables
          2. Changing Shell Variables
        10. Standard Streams
          1. Redirecting Streams to Files and Programs
            1. Redirecting streams to files
            2. Chaining programs with pipes
            3. Redirected streams and user interaction
              1. Reading keyboard input
          2. Redirecting Streams to Python Objects
          3. Other Redirection Options
        11. File Tools
          1. Built-in File Objects
            1. Output files
              1. Opening
              2. Writing
              3. Closing
            2. Input files
            3. Other file object modes
            4. Binary data files
            5. End-of-line translations on Windows
          2. File Tools in the os Module
            1. Open mode flags
            2. Other os file tools
          3. File Scanners
          4. Making Files Look Like Lists
        12. Directory Tools
          1. Walking One Directory
            1. Running shell listing commands with os.popen
            2. The glob module
            3. The os.listdir call
            4. Splitting and joining listing results
          2. Walking Directory Trees
            1. The find module
            2. The os.path.walk visitor
            3. Recursive os.listdir traversals
          3. Rolling Your Own find Module
      2. 3. Parallel System Tools
        1. “Telling the Monkeys What to Do”
        2. Forking Processes
          1. The fork/exec Combination
            1. os.exec call formats
            2. Spawned child program
        3. Threads
          1. The thread Module
            1. Synchronizing access to global objects
            2. Waiting for spawned thread exits
          2. The threading Module
        4. Program Exits
          1. os Module Exits
          2. Exit Status Codes
          3. Thread Exits
        5. Interprocess Communication
        6. Pipes
          1. Anonymous Pipe Basics
          2. Bidirectional IPC with Pipes
            1. Deadlocks, flushes, and unbuffered streams
          3. Named Pipes (Fifos)
        7. Signals
        8. Launching Programs on Windows
          1. The os.spawnv Call
          2. Running DOS Command Lines
            1. Using the DOS start command
            2. Using start in Python scripts
          3. A Portable Program-Launch Framework
        9. Other System Tools
      3. 4. Larger System Examples I
        1. “Splits and Joins and Alien Invasions”
        2. Splitting and Joining Files
          1. Splitting Files Portably
            1. Operation modes
            2. Binary file access
            3. Manually closing files
          2. Joining Files Portably
            1. Reading by blocks or files
            2. Sorting filenames
          3. Usage Variations
        3. Generating Forward-Link Web Pages
          1. Page Template File
          2. Page Generator Script
        4. A Regression Test Script
        5. Packing and Unpacking Files
          1. Packing Files “++”
          2. Application Hierarchy Superclasses
            1. StreamApp: Adding stream redirection
            2. App: The root class
            3. Why use classes here?
        6. User-Friendly Program Launchers
          1. Launcher Module Clients
          2. Launching Programs Without Environment Settings
          3. Launching Web Browsers Portably
            1. Launching browsers with command lines
            2. Launching browsers with function calls
            3. A Python “multimedia extravaganza”
      4. 5. Larger System Examples II
        1. “The Greps of Wrath”
        2. Fixing DOS Line Ends
          1. Converting Line Ends in One File
            1. Slinging bytes and verifying results
            2. Nonintrusive conversions
            3. Slicing strings out-of-bounds
            4. Binary file mode revisited
          2. Converting Line Ends in One Directory
          3. Converting Line Ends in an Entire Tree
            1. The view from the top
        3. Fixing DOS Filenames
          1. Rewriting with os.path.walk
        4. Searching Directory Trees
          1. Greps and Globs in Shells and Python
            1. Cleaning up bytecode files
          2. A Python Tree Searcher
        5. Visitor: Walking Trees Generically
          1. Editing Files in Directory Trees
          2. Global Replacements in Directory Trees
          3. Collecting Matched Files in Trees
            1. Suppressing status messages
          4. Recoding Fixers with Visitors
          5. Fixing File Permissions in Trees
        6. Copying Directory Trees
          1. A Python Tree Copy Script
          2. Recoding Copies with a Visitor-Based Class
        7. Deleting Directory Trees
          1. Recoding Deletions for Generality
        8. Comparing Directory Trees
          1. Finding Directory Differences
          2. Finding Tree Differences
            1. Verifying CD backups
    5. II. GUI Programming
      1. 6. Graphical User Interfaces
        1. “Here’s Looking at You, Kid”
          1. GUI Programming Topics
        2. Python GUI Development Options
        3. Tkinter Overview
          1. Tkinter Documentation
          2. Tkinter Extensions
          3. Tkinter Structure
        4. Climbing the GUI Learning Curve
          1. “Hello World” in Four Lines (or Less)
          2. Tkinter Coding Basics
            1. Making widgets
            2. Geometry managers
            3. Running GUI programs
            4. Avoiding DOS consoles on Windows
          3. Tkinter Coding Alternatives
            1. Widget resizing basics
            2. Configuring widget options and window titles
            3. One more for old times’ sake
            4. Packing widgets without saving them
          4. Adding Buttons and Callbacks
            1. Widget resizing revisited: expansion
          5. Adding User-Defined Callback Handlers
            1. Lambda callback handlers
            2. Bound method callback handlers
            3. Callable class object callback handlers
            4. Other Tkinter callback protocols
            5. Binding events
          6. Adding Multiple Widgets
            1. Widget resizing revisited: clipping
            2. Attaching widgets to frames
            3. Packing order and side attachments
            4. The packer’s expand and fill revisited
            5. Using anchor to position instead of stretch
          7. Customizing Widgets with Classes
          8. Reusable GUI Components with Classes
            1. Attaching class components
            2. Extending class components
            3. Standalone container classes
        5. The End of the Tutorial
        6. Python/Tkinter for Tcl/Tk Converts
      2. 7. A Tkinter Tour, Part 1
        1. “Widgets and Gadgets and GUIs, Oh My!”
          1. This Chapter’s Topics
        2. Configuring Widget Appearance
        3. Toplevel Windows
          1. Toplevel and Tk Widgets
          2. Top-Level Window Protocols
        4. Dialogs
          1. Standard (Common) Dialogs
            1. A “smart” and reusable quit button
            2. A dialog demo launcher bar
            3. Printing dialog results (and passing callback data with lambdas)
            4. Letting users select colors on the fly
            5. Other standard dialog calls
          2. The Old-Style Dialog Module
          3. Custom Dialogs
            1. Making custom dialogs modal
            2. Other ways to be modal
        5. Binding Events
        6. Message and Entry
          1. Message
          2. Entry
            1. Programming Entry widgets
            2. Laying out input forms
            3. Going modal again
            4. Tkinter “variables”
        7. Checkbutton, Radiobutton, and Scale
          1. Checkbuttons
            1. Checkbuttons and variables
          2. Radiobuttons
            1. Radiobuttons and variables
            2. Radiobuttons without variables
            3. Hold on to your variables
          3. Scales (Sliders)
            1. Scales and variables
        8. Running GUI Code Three Ways
          1. Attaching Frames
          2. Independent Windows
          3. Running Programs
            1. Cross-program communication
            2. Coding for reusability
        9. Images
          1. Fun with Buttons and Pictures
      3. 8. A Tkinter Tour, Part 2
        1. “On Today’s Menu: Spam, Spam, and Spam”
        2. Menus
          1. Top-Level Window Menus
          2. Frame- and Menubutton-Based Menus
            1. Using Menubuttons and Optionmenus
          3. Windows with Both Menus and Toolbars
            1. Automating menu construction
        3. Listboxes and Scrollbars
          1. Programming Listboxes
          2. Programming Scrollbars
          3. Packing Scrollbars
        4. Text
          1. Programming the Text Widget
            1. Text is a Python string
            2. String positions
              1. Text indexes
              2. Text marks
              3. Text tags
          2. Adding Text-Editing Operations
            1. Using the clipboard
            2. Composition versus inheritance
            3. It’s called “Simple” for a reason
          3. Advanced Text and Tag Operations
        5. Canvas
          1. Basic Canvas Operations
          2. Programming the Canvas Widget
            1. Coordinates
            2. Object construction
            3. Object identifiers and operations
            4. Canvas object tags
          3. Scrolling Canvases
          4. Using Canvas Events
            1. Binding events on specific items
        6. Grids
          1. Grid Basics
          2. grid Versus pack
          3. Combining grid and pack
          4. Making Gridded Widgets Expandable
            1. Resizing in grids
            2. Spanning columns and rows
          5. Laying Out Larger Tables with grid
        7. Time Tools, Threads, and Animation
          1. Using Threads with GUIs
          2. Using the after Method
            1. Hiding and redrawing widgets and windows
          3. Simple Animation Techniques
            1. Using time.sleep loops
            2. Using widget.after events
            3. Using multiple time.sleep loop threads
            4. Other animation options
        8. The End of the Tour
        9. The PyDemos and PyGadgets Launchers
          1. PyDemos Launcher Bar
          2. PyGadgets Launcher Bar
      4. 9. Larger GUI Examples
        1. “Building a Better Mouse Trap”
          1. Examples in Other Chapters
          2. This Chapter’s Strategy
        2. Advanced GUI Coding Techniques
          1. GuiMixin: Shared Behavior in “Mixin” Classes
          2. GuiMaker: Automating Menus and Toolbars
            1. Subclass protocols
            2. GuiMaker classes
            3. GuiMaker self-test
          3. BigGui: A Client Demo Program
          4. ShellGui: Adding GUIs to Command-Line Tools
            1. A generic shell-tools display
            2. Application-specific tool set classes
            3. Adding GUI frontends to command lines
          5. GuiStreams: Redirecting Streams to GUI Widgets
            1. Using redirection for the packing scripts
          6. Reloading GUI Callback Handlers Dynamically
        3. Complete Program Examples
        4. PyEdit: A Text Editor Program/Object
          1. Running PyEdit
          2. PyEdit Source Code
        5. PyView: An Image and Notes Slideshow
          1. Running PyView
          2. PyView Source Code
        6. PyDraw: Painting and Moving Graphics
          1. Running PyDraw
          2. PyDraw Source Code
        7. PyClock: An Analog/Digital Clock Widget
          1. A Quick Geometry Lesson
          2. Running PyClock
          3. PyClock Source Code
        8. PyToe: A Tic-Tac-Toe Game Widget
          1. Running PyToe
          2. PyToe Source Code (on CD)
        9. Where to Go from Here
    6. III. Internet Scripting
      1. 10. Network Scripting
        1. “Tune in, Log on, and Drop out”
          1. Internet Scripting Topics
            1. What we will cover
            2. What we won’t cover
            3. Running examples in this part of the book
        2. Plumbing the Internet
          1. The Socket Layer
            1. Machine identifiers
          2. The Protocol Layer
            1. Port number rules
            2. Clients and servers
            3. Protocol structures
          3. Python’s Internet Library Modules
        3. Socket Programming
          1. Socket Basics
            1. Server socket calls
            2. Client socket calls
            3. Running socket programs locally
            4. Running socket programs remotely
            5. Socket pragmatics
            6. Spawning clients in parallel
            7. Talking to reserved ports
        4. Handling Multiple Clients
          1. Forking Servers
            1. Running the forking server
            2. Forking processes
            3. Exiting from children
            4. Killing the zombies
            5. Preventing zombies with signal handlers
          2. Threading Servers
          3. Doing It with Classes: Server Frameworks
          4. Multiplexing Servers with select
            1. A select-based echo server
            2. Running the select server
          5. Choosing a Server Scheme
        5. A Simple Python File Server
          1. Running the File Server and Clients
          2. Adding a User-Interface Frontend
            1. Using Frames and command lines
            2. Using grids and function calls
            3. Using a reusable form-layout class
      2. 11. Client-Side Scripting
        1. “Socket to Me!”
        2. Transferring Files over the Net
          1. FTP: Fetching Python with Python
            1. Using urllib to FTP files
          2. FTP get and put Utilities
            1. Download utility
            2. Upload utility
            3. Playing the Monty Python theme song
            4. Adding user interfaces
          3. Downloading Web Sites (Mirrors)
          4. Uploading Web Sites
          5. Uploads with Subdirectories
        3. Processing Internet Email
          1. POP: Reading Email
            1. Mail configuration module
            2. POP mail reader module
          2. SMTP: Sending Email
            1. Sending messages
            2. More ways to abuse the Net
            3. Back to the big Internet picture
          3. A Command-Line Email Client
            1. Running the pymail command-line client
          4. Decoding Mail Message Attachments
            1. Decoding base64 data
            2. Extracting and decoding all parts of a message
        4. The PyMailGui Email Client
          1. Why PyMailGui?
          2. Running PyMailGui
          3. Presentation Strategy
          4. Interacting with PyMailGui
            1. Getting started
            2. Loading mail
            3. Threading long-running email transfers
            4. Load server interface
            5. Sending email
            6. Viewing email
            7. Email replies and forwards
            8. Saving and deleting email
            9. POP message numbers
            10. Windows and status messages
          5. Implementing PyMailGui
            1. Help text module
            2. Main module
        5. Other Client-Side Tools
          1. NNTP: Accessing Newsgroups
          2. HTTP: Accessing Web Sites
            1. urllib revisited
            2. Other urllib interfaces
          3. Other Client-Side Scripting Options
      3. 12. Server-Side Scripting
        1. “Oh What a Tangled Web We Weave”
        2. What’s a Server-Side CGI Script?
          1. The Script Behind the Curtain
          2. Writing CGI Scripts in Python
          3. Running Server-Side Examples
            1. Changing server-side examples
            2. Viewing server-side examples and output
        3. Climbing the CGI Learning Curve
          1. A First Web Page
            1. HTML file permission constraints
            2. HTML basics
            3. Internet addresses (URLs)
            4. Using minimal URLs
          2. A First CGI Script
            1. Installing CGI scripts
            2. Automating installation steps
            3. Automating site move edits
            4. Finding Python on the server
          3. Adding Pictures and Generating Tables
            1. Table tags
          4. Adding User Interaction
            1. Submission
            2. More on form tags
            3. Response
            4. Passing parameters in URLs
          5. Using Tables to Lay Out Forms
            1. Converting strings in CGI scripts
            2. Debugging CGI scripts
          6. Adding Common Input Devices
            1. Changing input layouts
          7. Passing Parameters in Hardcoded URLs
            1. Saving CGI script state information
        4. The Hello World Selector
          1. Checking for Missing and Invalid Inputs
        5. Coding for Maintainability
          1. Step 1: Sharing Objects Between Pages
          2. Step 2: A Reusable Form Mock-up Utility
          3. Step 3: Putting It All Together -- A New Reply Script
        6. More on HTML and URL Escapes
          1. URL Escape Code Conventions
          2. Python HTML and URL Escape Tools
          3. Escaping HTML Code
          4. Escaping URLs
          5. Escaping URLs Embedded in HTML Code
        7. Sending Files to Clients and Servers
          1. Displaying Arbitrary Server Files on the Client
            1. Handling private files and errors
          2. Uploading Client Files to the Server
            1. Handling client path formats
          3. More Than One Way to Push Bits Over the Net
      4. 13. Larger Web Site Examples I
        1. “Things to Do When Visiting Chicago”
        2. The PyMailCgi Web Site
          1. Implementation Overview
          2. Presentation Overview
        3. The Root Page
        4. Sending Mail by SMTP
          1. The Message Composition Page
          2. Send Mail Script
            1. Using the send mail script outside a browser
        5. Reading POP Email
          1. The POP Password Page
          2. The Mail Selection List Page
            1. Passing state information in URL link parameters
            2. Security protocols
          3. The Message View Page
            1. Passing state information in HTML hidden input fields
            2. Escaping mail text and passwords in HTML
          4. The Message Action Pages
            1. Reply and forward
            2. Delete
        6. Utility Modules
          1. External Components
          2. POP Mail Interface
          3. POP Password Encryption
            1. Default encryption scheme: rotor
            2. Alternative encryption schemes
          4. Common Utilities Module
        7. CGI Script Trade-offs
      5. 14. Larger Web Site Examples II
        1. “Typos Happen”
        2. The PyErrata Web Site
          1. System Goals
          2. Implementation Overview
          3. Presentation Strategy
        3. The Root Page
        4. Browsing PyErrata Reports
          1. User Interface: Browsing Comment Reports
          2. User Interface: Browsing Errata Reports
          3. Using Explicit URLs with PyErrata
          4. Implementation: Browsing Comment Reports
          5. Implementation: Browsing Errata Reports
          6. Common Browse Utility Modules
        5. Submitting PyErrata Reports
          1. User Interface: Submitting Comment Reports
          2. User Interface: Submitting Errata Reports
          3. Implementation: Submitting Comment Reports
          4. Implementation: Submitting Errata Reports
          5. Common Submit Utility Module
        6. PyErrata Database Interfaces
          1. The Specter of Concurrent Updates
          2. Database Storage Structure
            1. Shelve database
            2. Flat-file database
          3. Database Switch
          4. Storage-Specific Classes for Files and Shelves
          5. Top-Level Database Interface Class
          6. Mutual Exclusion for Shelves
            1. Using fcntl.flock to lock files
            2. Mutex test scripts
            3. Mutex class test scripts
        7. Administrative Tools
          1. Backup Tools
          2. Display Tools
          3. Report State-Change Tools
        8. Designing for Reuse and Growth
          1. Reusability
          2. Scalability
            1. Multiple shelve field indexing
      6. 15. Advanced Internet Topics
        1. “Surfing on the Shoulders of Giants”
        2. Zope: A Web Publishing Framework
          1. Zope Components
          2. What’s Object Publishing?
        3. HTMLgen: Web Pages from Objects
          1. A Brief HTMLgen Tutorial
        4. JPython ( Jython): Python for Java
          1. A Quick Introduction to JPython
          2. A Simple JPython Example
          3. Interface Automation Tricks
          4. Writing Java Applets in JPython
          5. JPython Trade-offs
          6. Picking Your Python
        5. Grail: A Python-Based Web Browser
          1. A Simple Grail Applet Example
        6. Python Restricted Execution Mode
          1. Using rexec
        7. XML Processing Tools
        8. Windows Web Scripting Extensions
          1. Active Scripting: Client-Side Embedding
            1. Active Scripting basics
            2. Teaching IE about Python
          2. Active Server Pages: Server-Side Embedding
            1. A short ASP example
          3. The COM Connection
            1. A brief introduction to COM
            2. Python COM clients
            3. Python COM servers
              1. Using the Python server from a Python client
              2. Using the Python server from a VB client
            4. The bigger COM picture
        9. Python Server Pages
        10. Rolling Your Own Servers in Python
          1. Coding Solutions
          2. Packaged Solutions
    7. IV. Assorted Topics
      1. 16. Databases and Persistence
        1. “Give Me an Order of Persistence, but Hold the Pickles”
        2. Persistence Options in Python
        3. DBM Files
          1. Using DBM Files
        4. Pickled Objects
          1. Using Object Pickling
        5. Shelve Files
          1. Using Shelves
          2. Storing Built-in Object Types
          3. Storing Class Instances
          4. Changing Classes of Stored Objects
          5. Shelve Constraints
            1. Keys must be strings
            2. Objects are only unique within a key
            3. Updates must treat shelves as fetch-modify-store mappings
            4. Concurrent updates not allowed
            5. Pickler class constraints
            6. Other persistence limitations
        6. SQL Database Interfaces
          1. Interface Overview
          2. Resources
        7. PyForm: A Persistent Object Viewer
          1. Doing It the Hard Way
          2. Doing It the Graphical Way
            1. PyForm GUI code
            2. PyForm table wrappers
            3. PyForm creation and view utility scripts
            4. PyForm limitations
      2. 17. Data Structures
        1. “Roses Are Red, Violets Are Blue; Lists Are Mutable, and So Is Class Foo”
        2. Implementing Stacks
          1. A Stack Module
          2. A Stack Class
          3. Customization: Performance Monitors
          4. Optimization: Tuple Tree Stacks
          5. Optimization: In-place List Modifications
          6. Timing the Improvements
        3. Implementing Sets
          1. Set Functions
            1. Supporting multiple operands
          2. Set Classes
          3. Optimization: Moving Sets to Dictionaries
            1. Timing the results
          4. Optimizing fastset by Coding Techniques (or Not)
          5. Adding Relational Algebra to Sets (CD)
        4. Binary Search Trees
        5. Graph Searching
          1. Moving Graphs to Classes
        6. Reversing Sequences
        7. Permuting Sequences
        8. Sorting Sequences
          1. Adding Comparison Functions
        9. Data Structures Versus Python Built-ins
        10. PyTree: A Generic Tree Object Viewer
          1. Running PyTree
          2. Pytree Source Code
            1. Tree-independent GUI implementation
            2. Tree wrappers and test widgets
          3. Pytree Does Parse Trees, Too
      3. 18. Text and Language
        1. “See Jack Hack. Hack, Jack, Hack”
        2. Strategies for Parsing Text in Python
        3. String Module Utilities
          1. Summing Columns in a File
          2. Parsing and Unparsing Rule Strings
            1. More on the holmes expert system shell
        4. Regular Expression Matching
          1. Using the re Module
            1. Module functions
            2. Compiled pattern objects
            3. Match objects
            4. Regular expression patterns
          2. Basic Patterns
          3. Scanning C Header Files for Patterns
          4. A File Pattern Search Utility
        5. Parser Generators
        6. Hand-Coded Parsers
          1. The Expression Grammar
          2. The Parser’s Code
          3. Adding a Parse Tree Interpreter
          4. Parse Tree Structure
          5. Exploring Parse Trees with Pytree
          6. Parsers Versus Python
        7. PyCalc: A Calculator Program/Object
          1. A Simple Calculator GUI
            1. Building the GUI
            2. Running code strings
            3. Extending and attaching
          2. Pycalc -- A Real Calculator GUI
            1. Running PyCalc
            2. Evaluating expressions with stacks
            3. PyCalc source code
            4. Using PyCalc as a component
            5. Adding new buttons in new components
    8. V. Integration
      1. 19. Extending Python
        1. “I Am Lost at C”
          1. Integration Topics
        2. C Extensions Overview
        3. A Simple C Extension Module
          1. Compilation and Linking
            1. Dynamic binding
            2. Static binding
            3. Static versus dynamic binding
          2. Anatomy of a C Extension Module
          3. Data conversions
            1. Python to C: Using Python argument lists
            2. Python to C: Using Python return values
            3. C to Python: Returning values to Python
            4. Common conversion codes
          4. Error Handling
            1. Raising Python exceptions in C
            2. Detecting errors that occur in Python
          5. Reference Counts
        4. The SWIG Integration Code Generator
          1. A Simple SWIG Example
          2. SWIG Details
        5. Wrapping C Environment Calls
          1. But Don’t Do That Either -- SWIG
        6. A C Extension Module String Stack
          1. But Don’t Do That Either -- SWIG
        7. A C Extension Type String Stack
          1. Anatomy of a C Extension Type
          2. Compiling and Running
          3. Timing the C Implementations
          4. Wrapping C Types in Classes
          5. But Don’t Do That Either -- SWIG
        8. Wrapping C++ Classes with SWIG
          1. A Little C++ Class (But Not Too Much)
          2. Wrapping the C++ Class with SWIG
          3. Using the C++ Class in Python
      2. 20. Embedding Python
        1. “Add Python. Mix Well. Repeat.”
        2. C Embedding API Overview
          1. What Is Embedded Code?
        3. Basic Embedding Techniques
          1. Running Simple Code Strings
            1. Compiling and running
          2. Running Code Strings with Results and Namespaces
          3. Calling Python Objects
          4. Running Strings in Dictionaries
          5. Precompiling Strings to Bytecode
        4. Registering Callback Handler Objects
        5. Using Python Classes in C
        6. ppembed: A High-Level Embedding API
          1. Running Objects with ppembed
          2. Running Code Strings with ppembed
          3. Running Customizable Validations
          4. ppembed Implementation
          5. Other Integration Examples on the CD
        7. Other Integration Topics
          1. JPython (a.k.a. Jython) Integration
          2. COM Integration on Windows
          3. CORBA Integration
          4. Integration Versus Optimization
            1. Framework roles
            2. Extension module roles
            3. Picking an integration technology
    9. VI. The End
      1. 21. Conclusion: Python and the Development Cycle
        1. “That’s the End of the Book, Now Here’s the Meaning of Life”
        2. “Something’s Wrong with the Way We Program Computers”
        3. The “Gilligan Factor”
        4. Doing the Right Thing
          1. The Static Language Build Cycle
          2. Artificial Complexities
          3. One Language Does Not Fit All
        5. Enter Python
        6. But What About That Bottleneck?
          1. Python Provides Immediate Turnaround
          2. Python Is “Executable Pseudocode”
          3. Python Is OOP Done Right
          4. Python Fosters Hybrid Applications
        7. On Sinking the Titanic
        8. So What’s Python: The Sequel
        9. In the Final Analysis...
        10. Postscript to the Second Edition
          1. Integration Isn’t Everything
          2. The End of the Java Wars
          3. We’re Not Off That Island Yet
      2. A. Recent Python Changes
        1. Major Changes in 2.0
          1. Core Language Changes
            1. Augmented assignment
            2. List comprehensions
            3. Extended import statements
            4. Extended print statement
            5. Optional collection of cyclical garbage
          2. Selected Library Changes
            1. New zip function
            2. XML support
            3. New web browser module
          3. Python/C Integration API Changes
          4. Windows Changes
        2. Major Changes in 1.6
          1. Incompatibilities
          2. Core Language Changes
            1. Unicode strings
            2. String methods
            3. New (internal) regular expression engine
            4. apply-like function calls syntax
            5. String to number conversion bases
            6. Better errors for local name oddities
            7. Membership operator overloading
          3. Selected Library Module Changes
          4. Selected Tools Changes
        3. Major Changes Between 1.3 and 1.5.2
          1. Core Language Changes
            1. Pseudo-private class attributes
            2. Class exceptions
            3. Package imports
            4. New assert statement
            5. Reserved word changes
            6. New dictionary methods
            7. New list methods
            8. “Raw” string constants
            9. Complex number type
            10. Printing cyclic objects doesn’t core dump
            11. raise without arguments: re-raise
            12. raise forms for class exceptions
            13. Power operator X ** Y
            14. Generalized sequence assignments
            15. It’s faster
          2. Library Changes
            1. dir(X) now works on more objects
            2. New conversions: int(X), float(X), list(S)
            3. The new re regular expression module
            4. splitfields/joinfields became split/join
            5. Persistence: unpickler no longer calls __init__
            6. Object pickler coded in C: cPickle
            7. anydbm.open now expects a “c” second argument for prior behavior
            8. rand module replaced by random module
            9. Assorted Tkinter changes
            10. CGI module interface change
            11. site.py, user.py, and PYTHONHOME
            12. Assignment to os.environ[key] calls putenv
            13. New sys.exc_info( ) tuple
            14. The new operator module
          3. Tool Changes
            1. JPython (a.k.a. Jython): a Python-to-Java compiler
            2. MS-Windows ports: COM, Tkinter
            3. SWIG growth, C++ shadow classes
            4. Zope (formerly Bobo): Python objects for the Web
            5. HTMLgen: making HTML from Python classes
            6. PMW: Python mega-widgets for Tkinter
            7. IDLE: an integrated development environment GUI
            8. Other tool growth: PIL, NumPy, Database API
          4. Python/C Integration API Changes
            1. A single Python.h header file
            2. A single libpython*.a C library file
            3. The “Great (Grand?) Renaming” is complete
            4. Threading support, multiple interpreters
            5. New Python C API documentation
      3. B. Pragmatics
        1. Installing Python
          1. Windows
          2. Unix and Linux
          3. Macintosh and Others
        2. Book Examples Distribution
          1. The Book Examples Package
          2. Running the Demo Launcher Scripts
        3. Environment Configuration
          1. Shell Variables
          2. Configuration Settings
          3. Configuring from a Program
        4. Running Python Programs
        5. Python Internet Resources
      4. C. Python Versus C++
    10. Index
    11. Colophon

Product information

  • Title: Programming Python, Second Edition
  • Author(s): Mark Lutz
  • Release date: March 2001
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9780596000851