python in a nutshell 2nd edition

736 7.4K 0
python in a nutshell 2nd edition

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

www.it-ebooks.info www.it-ebooks.info Second Edition PYTHON IN A NUTSHELL Alex Martelli Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo www.it-ebooks.info Python in a Nutshell, Second Edition by Alex Martelli Copyright © 2006, 2003 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: Mary T. O’Brien Production Editor: Matt Hutchinson Copyeditor: Linley Dolby Proofreader: Matt Hutchinson Indexer: Johnna Dinse Cover Designer: Emma Colby Interior Designer: Brett Kerr Cover Illustrator: Karen Montgomery Illustrators: Robert Romano and Jessamyn Read Printing History: March 2003: First Edition. July 2006: Second Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. The In a Nutshell series designations, Python in a Nutshell, the image of an African rock python, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-0596-10046-9 [LSI] [2011-07-01] www.it-ebooks.info iii Chapter 1 Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Part I. Getting Started with Python 1. Introduction to Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 The Python Language 3 The Python Standard Library and Extension Modules 5 Python Implementations 5 Python Development and Versions 8 Python Resources 9 2. Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Installing Python from Source Code 14 Installing Python from Binaries 18 Installing Jython 20 Installing IronPython 21 3. The Python Interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 The python Program 22 Python Development Environments 26 Running Python Programs 28 The jython Interpreter 29 The IronPython Interpreter 30 www.it-ebooks.info iv | Table of Contents Part II. Core Python Language and Built-ins 4. The Python Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Lexical Structure 33 Data Types 38 Variables and Other References 46 Expressions and Operators 50 Numeric Operations 52 Sequence Operations 53 Set Operations 58 Dictionary Operations 59 The print Statement 61 Control Flow Statements 62 Functions 70 5. Object-Oriented Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Classes and Instances 82 Special Methods 104 Decorators 115 Metaclasses 116 6. Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 The try Statement 121 Exception Propagation 126 The raise Statement 128 Exception Objects 129 Custom Exception Classes 132 Error-Checking Strategies 134 7. Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Module Objects 139 Module Loading 144 Packages 149 The Distribution Utilities (distutils) 150 8. Core Built-ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Built-in Types 154 Built-in Functions 158 The sys Module 168 The copy Module 172 The collections Module 173 www.it-ebooks.info Table of Contents | v The functional Module 175 The bisect Module 176 The heapq Module 177 The UserDict Module 178 The optparse Module 179 The itertools Module 183 9. Strings and Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 Methods of String Objects 186 The string Module 191 String Formatting 193 The pprint Module 197 The repr Module 198 Unicode 198 Regular Expressions and the re Module 201 Part III. Python Library and Extension Modules 10. File and Text Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 Other Chapters That Also Deal with Files 215 Organization of This Chapter 215 File Objects 216 Auxiliary Modules for File I/O 224 The StringIO and cStringIO Modules 229 Compressed Files 230 The os Module 240 Filesystem Operations 241 Text Input and Output 256 Richer-Text I/O 258 Interactive Command Sessions 265 Internationalization 269 11. Persistence and Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Serialization 278 DBM Modules 285 Berkeley DB Interfacing 288 The Python Database API (DBAPI) 2.0 292 www.it-ebooks.info vi | Table of Contents 12. Time Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 The time Module 302 The datetime Module 306 The pytz Module 313 The dateutil Module 313 The sched Module 316 The calendar Module 317 The mx.DateTime Module 319 13. Controlling Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 Dynamic Execution and the exec Statement 328 Internal Types 331 Garbage Collection 332 Termination Functions 337 Site and User Customization 338 14. Threads and Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 Threads in Python 341 The thread Module 341 The Queue Module 342 The threading Module 344 Threaded Program Architecture 350 Process Environment 353 Running Other Programs 354 The mmap Module 360 15. Numeric Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 The math and cmath Modules 365 The operator Module 368 Random and Pseudorandom Numbers 370 The decimal Module 372 The gmpy Module 373 16. Array Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 The array Module 375 Extensions for Numeric Array Computation 377 The Numeric Package 378 Array Objects 378 Universal Functions (ufuncs) 399 Auxiliary Numeric Modules 403 www.it-ebooks.info Table of Contents | vii 17. Tkinter GUIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 Tkinter Fundamentals 406 Widget Fundamentals 408 Commonly Used Simple Widgets 415 Container Widgets 420 Menus 423 The Text Widget 426 The Canvas Widget 436 Layout Management 442 Tkinter Events 446 18. Testing, Debugging, and Optimizing . . . . . . . . . . . . . . . . . . . . . . . . . 451 Testing 452 Debugging 461 The warnings Module 471 Optimization 474 Part IV. Network and Web Programming 19. Client-Side Network Protocol Modules . . . . . . . . . . . . . . . . . . . . . . . 493 URL Access 493 Email Protocols 503 The HTTP and FTP Protocols 506 Network News 511 Telnet 515 Distributed Computing 517 Other Protocols 519 20. Sockets and Server-Side Network Protocol Modules . . . . . . . . . . . . 520 The socket Module 521 The SocketServer Module 528 Event-Driven Socket Programs 533 21. CGI Scripting and Alternatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545 CGI in Python 546 Cookies 553 Other Server-Side Approaches 557 www.it-ebooks.info viii | Table of Contents 22. MIME and Network Encodings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561 Encoding Binary Data as Text 561 MIME and Email Format Handling 564 23. Structured Text: HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575 The sgmllib Module 576 The htmllib Module 580 The HTMLParser Module 583 The BeautifulSoup Extension 585 Generating HTML 586 24. Structured Text: XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591 An Overview of XML Parsing 592 Parsing XML with SAX 593 Parsing XML with DOM 598 Changing and Generating XML 606 Part V. Extending and Embedding 25. Extending and Embedding Classic Python . . . . . . . . . . . . . . . . . . . . 613 Extending Python with Python’s C API 614 Extending Python Without Python’s C API 645 Embedding Python 647 Pyrex 650 26. Extending and Embedding Jython . . . . . . . . . . . . . . . . . . . . . . . . . . . 655 Importing Java Packages in Jython 656 Embedding Jython in Java 659 Compiling Python into Java 662 27. Distributing Extensions and Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666 Python’s distutils 666 py2exe 675 py2app 676 cx_Freeze 676 PyInstaller 676 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677 www.it-ebooks.info [...]... and Databases Introduces Python s serialization and persistence mechanisms, as well as Python s interfaces to DBM databases, the Berkeley Database, and relational (SQL-based) databases Chapter 12, Time Operations Covers how to deal with times and dates in Python, using the standard library and popular extensions Chapter 13, Controlling Execution Explains how to achieve advanced execution control in Python, ... frameworks For optimal use of Jython, you need some familiarity with fundamental Java classes You do not have to code in Java, but documentation and examples for existing Java classes are couched in Java terms, so you need a nodding acquaintance with Java to read and understand them You also need to use Java supporting tools for tasks such as manipulating jar files and signing applets This book deals... Visual Basic NET, or other CLR-compliant languages A Jython-coded application is a 100 percent pure Java application, with all of Java’s deployment advantages and issues, and runs on any target machine having a suitable JVM Packaging opportunities are also identical to Java’s Similarly, an IronPython-coded application is entirely compliant with NET’s specifications Jython, IronPython, and CPython are all... to Python www.it-ebooks.info Each minor release 2.x starts with alpha releases, tagged as 2.xa0, 2.xa1, and so on After the alphas comes at least one beta release, 2.xb1, and after the betas, at least one release candidate, 2.xrc1 By the time the final release of 2.x comes out, it is always solid, reliable, and well tested on all major platforms Any Python programmer can help ensure this by downloading... special user when you run make install A common idiom for this purpose is sudo make install: if sudo prompts for a password, enter your current user’s password, not root’s Installing Python from Binaries If your platform is popular and current, you may find pre-built and packaged binary versions of Python ready for installation Binary packages are typically self-installing, 18 | Chapter 2: Installation... the basics of both Python and many other technologies that can help you build dynamic web sites, including TCP/IP, HTTP, HTML, XML, and relational databases The book offers substantial examples, including a complete database-backed site • Dive Into Python, by Mark Pilgrim (APress), teaches by example in a fastpaced and thorough way that is very suitable for people who are already expert programmers in. .. www.it-ebooks.info either directly as executable programs, or via appropriate system tools, such as the RedHat Package Manager (RPM) on Linux and the Microsoft Installer (MSI) on Windows Once you have downloaded a package, install it by running the program and interactively choosing installation parameters, such as the directory where Python is to be installed http://www .python. org/ftp /python/ 2.4.3 /Python- 2.4.3.msi... version and enhancements by following the instructions and links at http://www .python. org/ download/releases/2.4.3/; due to Apple’s release cycles, the Python version included with Mac OS is generally somewhat out of date, and lacks some functionality, such as bsddb and readline Python s latest version installs in addition Installing Python from Binaries www.it-ebooks.info | 19 Installation To download Python. .. parameters, so parameter names are not significant Some optional parameters are best explained in terms of their presence or absence, rather than through default values In such cases, I indicate that a parameter is optional by enclosing it in brackets ([]) When more than one argument is optional, the brackets are nested Typographic Conventions Italic Used for filenames, program names, URLs, and to introduce... software maintenance, particularly in large projects, where many developers cooperate and often maintain code originally written by others 3 www.it-ebooks.info Python is simple, but not simplistic It adheres to the idea that if a language behaves a certain way in some contexts, it should ideally work similarly in all contexts Python also follows the principle that a language should not have “convenient” . products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While. DBM databases, the Berkeley Database, and relational (SQL-based) databases. Chapter 12, Time Operations Covers how to deal with times and dates in Python, using the standard library and popular. both in standard library modules and in third-party extension packages; in particular, the chapter covers how to use decimal floating-point numbers instead of the default binary floating-point

Ngày đăng: 05/05/2014, 12:16

Từ khóa liên quan

Mục lục

  • Copyright

  • Table of Contents

  • Preface

    • How This Book Is Organized

      • Part I, Getting Started with Python

      • Part II, Core Python Language and Built-ins

      • Part III, Python Library and Extension Modules

      • Part IV, Network and Web Programming

      • Part V, Extending and Embedding

    • Conventions Used in This Book

      • Reference Conventions

      • Typographic Conventions

    • Using Code Examples

    • How to Contact Us

    • Safari® Enabled

    • Acknowledgments

  • I

    • Chapter 1. Introduction to Python

      • The Python Language

      • The Python Standard Library and Extension Modules

      • Python Implementations

        • CPython

        • Jython

        • IronPython

        • Choosing Between CPython, Jython, and IronPython

        • PyPy and Other Experimental Versions

        • Licensing and Price Issues

      • Python Development and Versions

      • Python Resources

        • Documentation

        • Newsgroups and Mailing Lists

        • Special-Interest Groups

        • Python Business Forum

        • Python Journal

        • Extension Modules and Python Sources

        • The Python Cookbook

        • Books and Magazines

    • Chapter 2. Installation

      • Installing Python from Source Code

        • Windows

          • Uncompressing and unpacking the Python source code

          • Building the Python source code with Microsoft Visual Studio 2003

          • Building Python for debugging

          • Installing after the build

          • Building Python for Cygwin

        • Unix-Like Platforms

          • Uncompressing and unpacking the Python source code

          • Configuring, building, and testing

          • Installing after the build

      • Installing Python from Binaries

        • Apple Macintosh

      • Installing Jython

      • Installing IronPython

    • Chapter 3. The Python Interpreter

      • The python Program

        • Environment Variables

        • Command-Line Syntax and Options

        • Interactive Sessions

      • Python Development Environments

        • IDLE

        • Other Free Cross-Platform Python IDEs

        • Platform-Specific Free Python IDEs

        • Commercial Python IDEs

        • Free Text Editors with Python Support

        • Tools for Checking Python Programs

      • Running Python Programs

      • The jython Interpreter

      • The IronPython Interpreter

  • II

    • Chapter 4. The Python Language

      • Lexical Structure

        • Lines and Indentation

        • Character Sets

        • Tokens

          • Identifiers

          • Keywords

          • Operators

          • Delimiters

          • Literals

        • Statements

          • Simple statements

          • Compound statements

      • Data Types

        • Numbers

          • Integer numbers

          • Floating-point numbers

          • Complex numbers

        • Sequences

          • Iterables

          • Strings

          • Tuples

          • Lists

        • Sets

        • Dictionaries

        • None

        • Callables

        • Boolean Values

      • Variables and Other References

        • Variables

          • Object attributes and items

          • Accessing nonexistent references

        • Assignment Statements

          • Plain assignment

          • Augmented assignment

        • del Statements

      • Expressions and Operators

        • Comparison Chaining

        • Short-Circuiting Operators

          • The Python 2.5 ternary operator

      • Numeric Operations

        • Numeric Conversions

        • Arithmetic Operations

          • Division

          • Exponentiation

        • Comparisons

        • Bitwise Operations on Integers

      • Sequence Operations

        • Sequences in General

          • Sequence conversions

          • Concatenation and repetition

          • Membership testing

          • Indexing a sequence

          • Slicing a sequence

        • Strings

        • Tuples

        • Lists

          • Modifying a list

          • In-place operations on a list

          • List methods

          • Sorting a list

      • Set Operations

        • Set Membership

        • Set Methods

      • Dictionary Operations

        • Dictionary Membership

        • Indexing a Dictionary

        • Dictionary Methods

      • The print Statement

      • Control Flow Statements

        • The if Statement

        • The while Statement

        • The for Statement

          • Iterators

          • range and xrange

          • List comprehensions

        • The break Statement

        • The continue Statement

        • The else Clause on Loop Statements

        • The pass Statement

        • The try and raise Statements

        • The with Statement

      • Functions

        • The def Statement

        • Parameters

        • Attributes of Function Objects

          • Docstrings

          • Other attributes of function objects

        • The return Statement

        • Calling Functions

          • The semantics of argument passing

          • Kinds of arguments

        • Namespaces

          • The global statement

          • Nested functions and nested scopes

        • lambda Expressions

        • Generators

          • Generator expressions

          • Generators in Python 2.5

        • Recursion

    • Chapter 5. Object-Oriented Python

      • Classes and Instances

        • Python Classes

        • The class Statement

        • The Class Body

          • Attributes of class objects

          • Function definitions in a class body

          • Class-private variables

          • Class documentation strings

        • Descriptors

          • Overriding and nonoverriding descriptors

        • Instances

          • __init__

          • Attributes of instance objects

          • The factory-function idiom

          • __new__

        • Attribute Reference Basics

          • Getting an attribute from a class

          • Getting an attribute from an instance

          • Setting an attribute

        • Bound and Unbound Methods

          • Unbound method details

          • Bound method details

        • Inheritance

          • Method resolution order

          • Overriding attributes

          • Delegating to superclass methods

          • Cooperative superclass method calling

          • “Deleting” class attributes

        • The Built-in object Type

        • Class-Level Methods

          • Static methods

          • Class methods

        • Properties

          • Why properties are important

          • Properties and inheritance

        • __slots__

        • __getattribute__

        • Per-Instance Methods

        • Inheritance from Built-in Types

      • Special Methods

        • General-Purpose Special Methods

          • __call__

          • __cmp__

          • __del__

          • __delattr__

          • __eq__, __ge__, __gt__, __le__, __lt__, __ne__

          • __getattr__

          • __get- attribute__

          • __hash__

          • __init__

          • __new__

          • __nonzero__

          • __repr__

          • __setattr__

          • __str__

          • __unicode__

        • Special Methods for Containers

          • Sequences

          • Mappings

          • Sets

          • Container slicing

          • Container methods

          • __contains__

          • __delitem__

          • __getitem__

          • __iter__

          • __len__

          • __setitem__

        • Special Methods for Numeric Objects

          • __abs__, __invert__, __neg__, __pos__

          • __add__, __div__, __floordiv__, __mod__, __mul__, __sub__, __truediv__

          • __and__, __lshift__, __or__, __rshift__, __xor__

          • __coerce__

          • __complex__, __float__, __int__, __long__

          • __divmod__

          • __hex__, __oct__

          • __iadd__, __idiv__, __ifloordiv__, __imod__, __imul__, __isub__, __itru...

          • __iand__, __ilshift__, __ior__, __irshift__, __ixor__

          • __index__

          • __ipow__

          • __pow__

          • __radd__, __rdiv__, __rmod__, __rmul__, __rsub__

          • __rand__, __rlshift__, __ror__, __rrshift__, __rxor__

          • __rdivmod__

          • __rpow__

      • Decorators

      • Metaclasses

        • How Python Determines a Class’s Metaclass

        • How a Metaclass Creates a Class

          • Defining and using your own metaclasses

          • A substantial custom metaclass example

    • Chapter 6. Exceptions

      • The try Statement

        • try/except

        • try/finally

        • Python 2.5 Exception-Related Enhancements

          • The try/except/finally statement

          • The with statement

          • Generator enhancements

      • Exception Propagation

      • The raise Statement

      • Exception Objects

        • The Hierarchy of Standard Exceptions

        • Standard Exception Classes

      • Custom Exception Classes

        • Custom Exceptions and Multiple Inheritance

        • Other Exceptions Used in the Standard Library

      • Error-Checking Strategies

        • LBYL Versus EAFP

          • Proper usage of EAFP

        • Handling Errors in Large Programs

        • Logging Errors

          • The logging module

        • The assert Statement

          • The __debug__ built-in variable

    • Chapter 7. Modules

      • Module Objects

        • The import Statement

          • Module body

          • Attributes of module objects

          • Python built-ins

          • Module documentation strings

          • Module-private variables

        • The from Statement

          • The from … import * statement

          • from versus import

      • Module Loading

        • Built-in Modules

        • Searching the Filesystem for a Module

        • The Main Program

        • The reload Function

        • Circular Imports

        • sys.modules Entries

        • Custom Importers

          • Rebinding __import__

          • Import hooks

      • Packages

        • Special attributes of package objects

        • Absolute Versus Relative Imports

      • The Distribution Utilities (distutils)

        • Python Eggs

    • Chapter 8. Core Built-ins

      • Built-in Types

        • basestring

        • bool

        • buffer

        • classmethod

        • complex

        • dict

        • enumerate

        • file, open

        • float

        • frozenset

        • int

        • list

        • long

        • object

        • property

        • reversed

        • set

        • slice

        • staticmethod

        • str

        • super

        • tuple

        • type

        • unicode

        • xrange

      • Built-in Functions

        • __import__

        • abs

        • all

        • any

        • callable

        • chr

        • cmp

        • coerce

        • compile

        • delattr

        • dir

        • divmod

        • eval

        • execfile

        • filter

        • getattr

        • globals

        • hasattr

        • hash

        • hex

        • id

        • input

        • intern

        • isinstance

        • issubclass

        • iter

        • len

        • locals

        • map

        • max

        • min

        • oct

        • ord

        • pow

        • range

        • raw_input

        • reduce

        • reload

        • repr

        • round

        • setattr

        • sorted

        • sum

        • unichr

        • vars

        • zip

      • The sys Module

        • argv

        • displayhook

        • excepthook

        • exc_info

        • exit

        • getdefaulten- coding

        • getrefcount

        • getrecursionlimit

        • _getframe

        • maxint

        • modules

        • path

        • platform

        • ps1, ps2

        • setdefault- encoding

        • setprofile

        • setrecursionlimit

        • settrace

        • stdin, stdout, stderr

        • tracebacklimit

        • version

      • The copy Module

        • copy

        • deepcopy

      • The collections Module

        • deque

          • append

          • appendleft

          • clear

          • extend

          • extendleft

          • pop

          • popleft

          • rotate

        • defaultdict

      • The functional Module

        • partial

      • The bisect Module

        • bisect

        • insort

      • The heapq Module

        • heapify

        • heappop

        • heappush

        • heapreplace

        • nlargest

        • nsmallest

      • The UserDict Module

      • The optparse Module

        • add_option

        • parse_args

      • The itertools Module

        • chain

        • count

        • cycle

        • ifilter

        • imap

        • islice

        • izip

        • repeat

        • tee

    • Chapter 9. Strings and Regular Expressions

      • Methods of String Objects

        • capitalize

        • center

        • count

        • decode

        • encode

        • endswith

        • expandtabs

        • find

        • index

        • isalnum

        • isalpha

        • isdigit

        • islower

        • isspace

        • istitle

        • isupper

        • join

        • ljust

        • lower

        • lstrip

        • replace

        • rfind

        • rindex

        • rjust

        • rstrip

        • split

        • splitlines

        • startswith

        • strip

        • swapcase

        • title

        • translate

        • upper

      • The string Module

        • Locale Sensitivity

        • The maketrans Function

          • maketrans

      • String Formatting

        • Format Specifier Syntax

        • Common String-Formatting Idioms

        • Template Strings

          • Template

          • safe_substitute

          • substitute

        • Text Wrapping and Filling

          • wrap

          • fill

      • The pprint Module

        • pformat

        • pprint

      • The repr Module

        • repr

      • Unicode

        • The codecs Module

          • register_error

          • EncodedFile

          • open

        • The unicodedata Module

      • Regular Expressions and the re Module

        • Pattern-String Syntax

        • Common Regular Expression Idioms

        • Sets of Characters

        • Alternatives

        • Groups

        • Optional Flags

        • Match Versus Search

        • Anchoring at String Start and End

        • Regular Expression Objects

          • findall

          • finditer

          • match

          • search

          • split

          • sub

          • subn

        • Match Objects

          • end, span, start

          • expand

          • group

          • groups

          • groupdict

        • Functions of Module re

          • compile

          • escape

  • III

    • Chapter 10. File and Text Operations

      • Other Chapters That Also Deal with Files

      • Organization of This Chapter

      • File Objects

        • Creating a File Object with open

          • File mode

          • Binary and text modes

          • Buffering

          • Sequential and nonsequential access

        • Attributes and Methods of File Objects

          • close

          • closed

          • encoding

          • flush

          • isatty

          • fileno

          • mode

          • name

          • newlines

          • read

          • readline

          • readlines

          • seek

          • softspace

          • tell

          • truncate

          • write

          • writelines

        • Iteration on File Objects

        • File-Like Objects and Polymorphism

        • The tempfile Module

          • mkstemp

          • mkdtemp

          • TemporaryFile

          • NamedTempor- aryFile

      • Auxiliary Modules for File I/O

        • The fileinput Module

          • close

          • FileInput

          • filelineno

          • filename

          • input

          • isfirstline

          • isstdin

          • lineno

          • nextfile

        • The linecache Module

          • checkcache

          • clearcache

          • getline

          • getlines

        • The struct Module

          • calcsize

          • pack

          • unpack

      • The StringIO and cStringIO Modules

        • StringIO

        • getvalue

      • Compressed Files

        • The gzip Module

          • GzipFile

          • open

        • The bz2 Module

          • BZ2File

          • compress

          • decompress

        • The tarfile Module

          • is_tarfile

          • TarInfo

          • open

          • add

          • addfile

          • close

          • extract

          • extractfile

          • getmember

          • getmembers

          • getnames

          • gettarinfo

          • list

        • The zipfile Module

          • is_zipfile

          • ZipInfo

          • ZipFile

          • close

          • getinfo

          • infolist

          • namelist

          • printdir

          • read

          • testzip

          • write

          • writestr

        • The zlib Module

          • compress

          • decompress

      • The os Module

        • OSError Exceptions

        • The errno Module

      • Filesystem Operations

        • Path-String Attributes of the os Module

        • Permissions

        • File and Directory Functions of the os Module

          • access

          • chdir

          • chmod

          • getcwd

          • listdir

          • makedirs, mkdir

          • remove, unlink

          • removedirs

          • rename

          • renames

          • rmdir

          • stat

          • tempnam, tmpnam

          • utime

          • walk

        • The os.path Module

          • abspath

          • basename

          • commonprefix

          • dirname

          • exists

          • expandvars

          • getatime, getmtime, getsize

          • isabs

          • isfile

          • isdir

          • islink

          • ismount

          • join

          • normcase

          • normpath

          • split

          • splitdrive

          • splitext

          • walk

        • The stat Module

          • S_IFMT

          • S_IMODE

        • The filecmp Module

          • cmp

          • cmpfiles

          • dircmp

        • The shutil Module

          • copy

          • copy2

          • copyfile

          • copyfileobj

          • copymode

          • copystat

          • copytree

          • move

          • rmtree

        • File Descriptor Operations

          • close

          • dup

          • dup2

          • fdopen

          • fstat

          • lseek

          • open

          • pipe

          • read

          • write

      • Text Input and Output

        • Standard Output and Standard Error

        • The print Statement

        • Standard Input

        • The getpass Module

          • getpass

          • getuser

      • Richer-Text I/O

        • The readline Module

          • add_history

          • clear_history

          • get_completer

          • get_history_ length

          • parse_and_ bind

          • read_history_ file

          • read_init_file

          • set_completer

          • set_history_ length

          • write_history_ file

        • Console I/O

          • The curses package

          • wrapper

          • addstr

          • clrtobot, clrtoeol

          • delch

          • deleteln

          • erase

          • getch

          • getyx

          • insstr

          • move

          • nodelay

          • refresh

          • Textpad

          • The msvcrt Module

          • getch, getche

          • kbhit

          • ungetch

          • The WConio and Console modules

      • Interactive Command Sessions

        • Initializing a Cmd Instance

          • __init__

        • Methods of Cmd Instances

          • cmdloop

          • default

          • do_help

          • emptyline

          • onecmd

          • postcmd

          • postloop

          • precmd

          • preloop

        • Attributes of Cmd Instances

        • A Cmd Example

      • Internationalization

        • The locale Module

          • atof

          • atoi

          • format

          • getdefaultlocale

          • getlocale

          • localeconv

          • normalize

          • resetlocale

          • setlocale

          • str

          • strcoll

          • strxfrm

        • The gettext Module

          • Using gettext for localization

          • Essential gettext functions

          • install

          • translation

        • More Internationalization Resources

    • Chapter 11. Persistence and Databases

      • Serialization

        • The marshal Module

          • dump, dumps

          • load, loads

          • A marshaling example

        • The pickle and cPickle Modules

          • Functions of pickle and cPickle

          • dump, dumps

          • load, loads

          • Pickler

          • Unpickler

          • A pickling example

          • Pickling instances

          • Pickling customization with the copy_reg module

          • constructor

          • pickle

        • The shelve Module

          • A shelving example

      • DBM Modules

        • The anydbm Module

          • open

        • The dumbdbm Module

        • The dbm, gdbm, and dbhash Modules

        • The whichdb Module

          • whichdb

        • Examples of DBM-Like File Use

      • Berkeley DB Interfacing

        • Simplified and Complete BSD DB Python Interfaces

        • Module bsddb

          • btopen, hashopen, rnopen

          • close

          • first

          • has_key

          • keys

          • last

          • next

          • previous

          • set_location

        • Examples of Berkeley DB Use

      • The Python Database API (DBAPI) 2.0

        • Exception Classes

        • Thread Safety

        • Parameter Style

        • Factory Functions

          • Binary

          • Date

          • DateFromTicks

          • Time

          • TimeFromTicks

          • Timestamp

          • Timestamp- FromTicks

        • Type Description Attributes

        • The connect Function

        • Connection Objects

          • close

          • commit

          • cursor

          • rollback

        • Cursor Objects

          • close

          • description

          • execute

          • executemany

          • fetchall

          • fetchmany

          • fetchone

          • rowcount

        • DBAPI-Compliant Modules

        • Gadfly

          • gadfly

          • gfclient

        • SQLite

    • Chapter 12. Time Operations

      • The time Module

        • asctime

        • clock

        • ctime

        • gmtime

        • localtime

        • mktime

        • sleep

        • strftime

        • strptime

        • time

        • timezone

        • tzname

      • The datetime Module

        • Class date

          • date

          • fromordinal

          • fromtimestamp

          • today

          • ctime

          • isocalendar

          • isoformat

          • isoweekday

          • replace

          • strftime

          • timetuple

          • toordinal

          • weekday

        • Class time

          • time

          • isoformat

          • replace

          • strftime

        • Class datetime

          • datetime

          • combine

          • fromordinal

          • fromtimestamp

          • now

          • today

          • utcfromtime- stamp

          • utcnow

          • astimezone

          • ctime

          • date

          • isocalendar

          • isoformat

          • isoweekday

          • replace

          • strftime

          • time

          • timetz

          • timetuple

          • toordinal

          • utctimetuple

          • weekday

        • Class timedelta

          • timedelta

      • The pytz Module

        • country_ timezones

        • timezone

      • The dateutil Module

        • easter

        • parser

        • relativedelta

        • rrule

        • after

        • before

        • between

        • count

      • The sched Module

        • scheduler

        • cancel

        • empty

        • enterabs

        • enter

        • run

      • The calendar Module

        • calendar

        • firstweekday

        • isleap

        • leapdays

        • month

        • monthcalendar

        • monthrange

        • prcal

        • prmonth

        • setfirstweekday

        • timegm

        • weekday

      • The mx.DateTime Module

        • Date and Time Types

        • The DateTime Type

          • Factory functions for DateTime

          • DateTime, Date, Timestamp

          • DateTimeFrom, TimestampFrom

          • DateTime- FromAbsDays

          • DateTime- FromCOMDate

          • DateFromTicks

          • gmt, utc

          • gmtime, utctime

          • localtime

          • mktime

          • now

          • Timestamp- FromTicks

          • today

          • Methods of DateTime instances

          • absvalues

          • COMDate

          • gmticks

          • gmtime

          • gmtoffset

          • localtime

          • strftime, Format

          • ticks

          • tuple

          • Attributes of DateTime instances

          • Arithmetic on DateTime instances

        • The DateTimeDelta Type

          • Factory functions for DateTimeDelta

          • DateTimeDelta

          • DateTimeDelta- From

          • DateTimeDelta- FromSeconds

          • TimeDelta, Time

          • TimeDeltaFrom, TimeFrom

          • TimeFromTicks

          • Methods of DateTimeDelta instances

          • absvalues

          • strftime, Format

          • tuple

          • Attributes of DateTimeDelta instances

          • Arithmetic on DateTimeDelta instances

        • Other Attributes

          • cmp

        • Submodules

    • Chapter 13. Controlling Execution

      • Dynamic Execution and the exec Statement

        • Avoiding exec

        • Expressions

        • Compile and Code Objects

        • Never exec nor eval Untrusted Code

      • Internal Types

        • Type Objects

        • The Code Object Type

        • The frame Type

      • Garbage Collection

        • The gc Module

          • collect

          • disable

          • enable

          • garbage

          • get_debug

          • get_objects

          • get_referrers

          • get_threshold

          • isenabled

          • set_debug

          • set_threshold

        • The weakref Module

          • getweakrefcount

          • getweakrefs

          • proxy

          • ref

          • WeakKeyDic- tionary

          • WeakValueDic- tionary

      • Termination Functions

        • register

      • Site and User Customization

        • The site and sitecustomize Modules

        • User Customization

    • Chapter 14. Threads and Processes

      • Threads in Python

      • The thread Module

        • acquire

        • locked

        • release

      • The Queue Module

        • Queue

        • Empty

        • Full

        • Methods of Queue Instances

          • empty

          • full

          • get, get_nowait

          • put, put_nowait

          • qsize

        • Customizing Class Queue by Subclassing

      • The threading Module

        • currentThread

        • Thread Objects

          • Thread

          • getName, setName

          • isAlive

          • isDaemon, setDaemon

          • join

          • run

          • start

        • Thread Synchronization Objects

          • Timeout parameters

          • Lock and RLock objects

          • Condition objects

          • Condition

          • acquire, release

          • notify, notifyAll

          • wait

          • Event objects

          • Event

          • clear

          • isSet

          • set

          • wait

          • Semaphore objects

          • Semaphore

          • acquire

          • release

        • Thread Local Storage

      • Threaded Program Architecture

      • Process Environment

      • Running Other Programs

        • Running Other Programs with the os Module

          • execl, execle, execlp, execv, execve, execvp, execvpe

          • popen

          • popen2, popen3, popen4

          • spawnv, spawnve

          • system

        • The Subprocess Module

          • Popen

          • What to run, and how: args, executable, shell

          • Subprocess files: stdin, stdout, stderr, bufsize, universal_newlines, close_fds

          • Other arguments: preexec_fn, cwd, env, startupinfo, creationflags

          • Attributes of subprocess.Popen instances

          • Methods of subprocess.Popen instances

          • communicate

          • poll

          • wait

      • The mmap Module

        • mmap

        • Methods of mmap Objects

          • close

          • find

          • flush

          • move

          • read

          • read_byte

          • readline

          • resize

          • seek

          • size

          • tell

          • write

          • write_byte

        • Using mmap Objects for IPC

    • Chapter 15. Numeric Processing

      • The math and cmath Modules

        • acos

        • acosh

        • asin

        • asinh

        • atan

        • atanh

        • atan2

        • ceil

        • cos

        • cosh

        • e

        • exp

        • fabs

        • floor

        • fmod

        • frexp

        • hypot

        • ldexp

        • log

        • log10

        • modf

        • pi

        • pow

        • sin

        • sinh

        • sqrt

        • tan

        • tanh

      • The operator Module

        • attrgetter

        • itemgetter

      • Random and Pseudorandom Numbers

        • Physically random and cryptographically strong random numbers

        • urandom

        • The random module

        • choice

        • getrandbits

        • getstate

        • jumpahead

        • random

        • randrange

        • sample

        • seed

        • setstate

        • shuffle

        • uniform

      • The decimal Module

      • The gmpy Module

    • Chapter 16. Array Processing

      • The array Module

        • array

        • byteswap

        • fromfile

        • fromlist

        • fromstring

        • tofile

        • tolist

        • tostring

      • Extensions for Numeric Array Computation

      • The Numeric Package

      • Array Objects

        • Typecodes

        • Shape and Indexing

        • Storage

        • Slicing

          • Slicing examples

          • Assigning to array slices

        • Truth Values and Comparisons of Arrays

        • Factory Functions

          • array, asarray

          • arrayrange, arange

          • fromstring

          • identity

          • empty

          • ones

          • zeros

        • Attributes and Methods

          • astype

          • byteswapped

          • copy

          • flat

          • imag, imaginary, real

          • iscontiguous

          • itemsize

          • savespace

          • shape

          • spacesaver

          • tolist

          • toscalar

          • tostring

          • typecode

        • Operations on Arrays

          • Broadcasting

          • In-place operations

        • Functions

          • allclose

          • argmax, argmin

          • argsort

          • around

          • array2string

          • average

          • choose

          • clip

          • compress

          • concatenate

          • convolve

          • cross_correlate

          • diagonal

          • dot

          • indices

          • innerproduct

          • matrixmultiply

          • nonzero

          • outerproduct

          • put

          • putmask

          • rank

          • ravel

          • repeat

          • reshape

          • resize

          • searchsorted

          • shape

          • size

          • sort

          • swapaxes

          • take

          • trace

          • transpose

          • vdot

          • where

      • Universal Functions (ufuncs)

        • The Optional output Argument

        • Callable Attributes

          • accumulate

          • outer

          • reduce

          • reduceat

        • ufunc Objects Supplied by Numeric

        • Shorthand for Commonly Used ufunc Methods

      • Auxiliary Numeric Modules

    • Chapter 17. Tkinter GUIs

      • Tkinter Fundamentals

        • Dialogs

          • The tkMessageBox module

          • The tkSimpleDialog module

          • The tkFileDialog module

          • The tkColorChooser module

      • Widget Fundamentals

        • Common Widget Options

          • Color options

          • Length options

          • Options expressing numbers of characters

          • Other common options

        • Common Widget Methods

          • cget

          • config

          • focus_set

          • grab_set, grab_release

          • mainloop

          • quit

          • update

          • update_ idletasks

          • wait_variable

          • wait_visibility

          • wait_window

          • winfo_height

          • winfo_width

        • Tkinter Variable Objects

        • Tkinter Images

      • Commonly Used Simple Widgets

        • Button

          • flash

          • invoke

        • Checkbutton

          • deselect

          • flash

          • invoke

          • select

          • toggle

        • Entry

        • Label

        • Listbox

          • curselection

          • select_clear

          • select_set

        • Radiobutton

          • deselect

          • flash

          • invoke

          • select

        • Scale

          • get

          • set

        • Scrollbar

      • Container Widgets

        • Frame

        • Toplevel

          • deiconify

          • geometry

          • iconify

          • maxsize

          • minsize

          • overrideredirect

          • protocol

          • resizable

          • state

          • title

          • withdraw

      • Menus

        • Menu-Specific Methods

          • add, add_cascade, add_ checkbutton, add_command, add_ radiobutton, add_separator

          • delete

          • entryconfigure, entryconfig

          • insert, insert_cascade, insert_ checkbutton, insert_ command, insert_ radiobutton, insert_ separator

          • invoke

          • post

          • unpost

        • Menu Entries

        • Menu Example

      • The Text Widget

        • The ScrolledText Module

        • Text Widget Methods

          • delete

          • get

          • image_create

          • insert

          • search

          • see

          • window_create

          • xview, yview

        • Marks

          • mark_gravity

          • mark_set

          • mark_unset

        • Tags

          • tag_add

          • tag_bind

          • tag_cget

          • tag_config

          • tag_delete

          • tag_lower

          • tag_names

          • tag_raise

          • tag_ranges

          • tag_remove

          • tag_unbind

        • Indices

          • compare

          • index

        • Fonts

          • actual

          • cget

          • config

          • copy

        • Text Example

      • The Canvas Widget

        • Canvas Methods on Items

          • bbox

          • coords

          • delete

          • gettags

          • itemcget

          • itemconfig

          • tag_bind

          • tag_unbind

        • The Line Canvas Item

          • create_line

        • The Polygon Canvas Item

          • create_polygon

        • The Rectangle Canvas Item

          • create_ rectangle

        • The Text Canvas Item

          • create_text

        • A Simple Plotting Example

      • Layout Management

        • The Packer

          • pack

          • pack_forget

          • pack_info

        • The Gridder

          • grid

          • grid_forget

          • grid_info

        • The Placer

          • place

          • place_forget

          • place_info

      • Tkinter Events

        • The Event Object

        • Binding Callbacks to Events

        • Event Names

          • Keyboard events

          • Mouse events

        • Event-Related Methods

          • bind

          • bind_all

          • unbind

          • unbind_all

        • An Events Example

        • Other Callback-Related Methods

          • after

          • after_cancel

          • after_idle

    • Chapter 18. Testing, Debugging, and Optimizing

      • Testing

        • Unit Testing and System Testing

        • The doctest Module

        • The unittest Module

          • The TestCase class

          • assert_, failUnless

          • assertAlmost- Equal, failUnlessAl- mostEqual

          • assertEqual, failUnlessEqual

          • assertNotAl- mostEqual, failIfAlmost- Equal

          • assertNotEqual, failIfEqual

          • assertRaises, failUnlessRaises

          • fail

          • failIf

          • setUp

          • tearDown

          • Unit tests dealing with large amounts of data

      • Debugging

        • Before You Debug

        • The inspect Module

          • getargspec, formatargspec

          • getargvalues, formatarg- values

          • currentframe

          • getdoc

          • getfile, getsourcefile

          • getmembers

          • getmodule

          • getmro

          • getsource, getsourcelines

          • isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule, isroutine

          • stack

          • An example of using inspect

        • The traceback Module

          • print_exc

        • The pdb Module

          • !

          • alias, unalias

          • args, a

          • break, b

          • clear, cl

          • condition

          • continue, c, cont

          • disable

          • down, d

          • enable

          • ignore

          • list, l

          • next, n

          • print, p

          • quit, q

          • return, r

          • step, s

          • tbreak

          • up, u

          • where, w

        • Debugging in IDLE

      • The warnings Module

        • Classes

        • Objects

        • Filters

        • Functions

          • filterwarnings

          • formatwarning

          • resetwarnings

          • showwarning

          • warn

      • Optimization

        • Developing a Fast-Enough Python Application

        • Benchmarking

        • Large-Scale Optimization

          • List operations

          • String operations

          • Dictionary operations

          • Set operations

          • Summary of big-O times for operations on Python built-in types

        • Profiling

          • The profile module

          • run

          • Calibration

          • calibrate

          • The pstats module

          • Stats

          • add

          • print_callees, print_callers

          • print_stats

          • sort_stats

          • strip_dirs

        • Small-Scale Optimization

          • Module timeit

          • Building up a string from pieces

          • Searching and sorting

          • Avoiding exec and from...import *

          • Optimizing loops

          • Optimizing I/O

  • IV

    • Chapter 19. Client-Side Network Protocol Modules

      • URL Access

        • The urlparse Module

          • urljoin

          • urlsplit

          • urlunsplit

        • The urllib Module

          • Functions

          • quote

          • quote_plus

          • unquote

          • unquote_plus

          • urlcleanup

          • urlencode

          • urlopen

          • urlretrieve

          • The FancyURLopener class

          • prompt_user_ passwd

          • version

        • The urllib2 Module

          • Functions

          • build_opener

          • install_opener

          • urlopen

          • The Request class

          • Request

          • add_data

          • add_header

          • add_unredirec- ted_header

          • get_data

          • get_full_url

          • get_host

          • get_method

          • get_selector

          • get_type

          • has_data

          • has_header

          • set_proxy

          • The OpenerDirector class

          • Handler classes

          • Handling authentication

          • add_password

      • Email Protocols

        • The poplib Module

          • POP3

          • dele

          • list

          • pass_

          • quit

          • retr

          • set_debuglevel

          • stat

          • top

          • user

        • The smtplib Module

          • SMTP

          • connect

          • login

          • quit

          • sendmail

      • The HTTP and FTP Protocols

        • The httplib Module

          • HTTPConnection

          • close

          • getresponse

          • request

        • The ftplib Module

          • FTP

          • abort

          • connect

          • cwd

          • delete

          • getwelcome

          • login

          • mkd

          • pwd

          • quit

          • rename

          • retrbinary

          • retrlines

          • rmd

          • sendcmd

          • set_pasv

          • size

          • storbinary

          • storlines

      • Network News

        • NNTP

        • Response Strings

        • Methods

          • article

          • body

          • group

          • head

          • last

          • list

          • newgroups

          • newnews

          • next

          • post

          • quit

          • stat

        • Example

      • Telnet

        • Telnet

        • close

        • expect

        • interact

        • open

        • read_all

        • read_eager

        • read_some

        • read_until

        • write

      • Distributed Computing

        • Binary

        • DateTime

        • ServerProxy

      • Other Protocols

    • Chapter 20. Sockets and Server-Side Network Protocol Modules

      • The socket Module

        • socket Functions

          • getdefault- timeout

          • getfqdn

          • gethostbyaddr

          • gethostby- name_ex

          • htonl

          • htons

          • inet_aton

          • inet_ntoa

          • ntohl

          • ntohs

          • setdefault- timeout

          • socket

        • The socket Class

          • accept

          • bind

          • close

          • connect

          • getpeername

          • getsockname

          • getsockopt

          • gettimeout

          • listen

          • makefile

          • recv

          • recvfrom

          • send

          • sendall

          • sendto

        • Echo Server and Client Using TCP Sockets

        • Echo Server and Client Using UDP Sockets

        • Socket Timeout Behavior

      • The SocketServer Module

        • The BaseRequestHandler Class

          • client_address

          • handle

          • request

          • server

        • HTTP Servers

          • The BaseHTTPServer module

          • command

          • handle

          • end_headers

          • path

          • rfile

          • send_header

          • send_error

          • send_response

          • wfile

          • The SimpleHTTPServer module

          • The CGIHTTPServer module

          • The SimpleXMLRPCServer module

          • register_ function

          • register_ instance

      • Event-Driven Socket Programs

        • The select Module

          • select

        • The asyncore and asynchat Modules

          • The asyncore module

          • loop

          • create_socket

          • handle_accept

          • handle_close

          • handle_connect

          • handle_read

          • handle_write

          • send

          • The asynchat module

          • collect_ incoming_data

          • found_ terminator

          • push

          • set_terminator

        • The Twisted Framework

          • The twisted.internet and twisted.protocols packages

          • Reactors

          • callLater

          • callInThread

          • callFromThread

          • callWhenRun- ning

          • connectTCP

          • listenTCP

          • run

          • stop

          • Transports

          • getHost

          • getPeer

          • loseConnection

          • write

          • writeSequence

          • Protocol handlers and factories

          • connectionLost

          • connection- Made

          • dataReceived

          • makeConnec- tion

          • Echo server using Twisted

    • Chapter 21. CGI Scripting and Alternatives

      • CGI in Python

        • Form Submission Methods

        • The cgi Module

          • escape

          • FieldStorage

          • getfirst

          • getlist

        • CGI Output and Errors

          • Error messages

          • The cgitb module

          • handle

          • enable

        • Installing Python CGI Scripts

          • Python CGI scripts on Microsoft web servers

          • Python CGI scripts on Apache

          • Python CGI scripts on Xitami

      • Cookies

        • The Cookie Module

          • Morsel

          • SimpleCookie

          • SmartCookie

          • Cookie methods

          • js_output

          • load

          • output

          • Morsel attributes and methods

          • js_output

          • output

          • OutputString

          • set

          • Using module Cookie

      • Other Server-Side Approaches

        • FastCGI

        • WSGI

        • mod_python

        • Custom Pure Python Servers

        • Other Higher-Level-of-Abstraction Frameworks

          • Webware

          • Quixote

          • web.py

    • Chapter 22. MIME and Network Encodings

      • Encoding Binary Data as Text

        • The base64 Module

          • decode

          • decodestring

          • encode

          • encodestring

        • The quopri Module

          • decode

          • decodestring

          • encode

          • encodestring

        • The uu Module

          • decode

          • encode

      • MIME and Email Format Handling

        • Functions in Package email

          • message_ from_string

          • message_ from_file

        • The email.Message Module

          • add_header

          • as_string

          • attach

          • epilogue

          • get_all

          • get_boundary

          • get_charsets

          • get_content_ maintype

          • get_content_ subtype

          • get_content_ type

          • get_filename

          • get_param

          • get_params

          • get_payload

          • get_unixfrom

          • is_multipart

          • preamble

          • set_boundary

          • set_payload

          • set_unixfrom

          • walk

        • The email.Generator Module

          • Generator

        • Creating Messages

          • MIMEAudio

          • MIMEBase

          • MIMEImage

          • MIMEMessage

          • MIMEText

        • The email.Encoders Module

          • encode_base64

          • encode_noop

          • encode_quopri

          • encode_7or8bit

        • The email.Utils Module

          • formataddr

          • formatdate

          • getaddresses

          • mktime_tz

          • parseaddr

          • parsedate

          • parsedate_tz

          • quote

          • unquote

        • Example Uses of the email Package

        • The Message Classes of the rfc822 and mimetools Modules

          • getmaintype

          • getparam

          • getsubtype

          • gettype

    • Chapter 23. Structured Text: HTML

      • The sgmllib Module

        • close

        • do_tag

        • end_tag

        • feed

        • handle_charref

        • handle_ comment

        • handle_data

        • handle_endtag

        • handle_ entityref

        • handle_starttag

        • report_ unbalanced

        • start_tag

        • unknown_ charref

        • unknown_ endtag

        • unknown_ entityref

        • unknown_ starttag

        • Parsing HTML with sgmllib

      • The htmllib Module

        • anchor_bgn

        • anchor_end

        • anchorlist

        • formatter

        • handle_image

        • nofill

        • save_bgn

        • save_end

        • The formatter Module

          • Abstract- Formatter

          • AbstractWriter

          • DumbWriter

          • NullFormatter

          • NullWriter

        • The htmlentitydefs Module

        • Parsing HTML with htmllib

      • The HTMLParser Module

        • close

        • feed

        • handle_charref

        • handle_ comment

        • handle_data

        • handle_endtag

        • handle_ entityref

        • handle_starttag

        • Parsing HTML with HTMLParser

      • The BeautifulSoup Extension

        • Parsing HTML with BeautifulSoup

      • Generating HTML

        • Embedding

        • Templating

        • The Cheetah Package

          • The Cheetah templating language

          • The Template class

          • Template

          • A Cheetah example

    • Chapter 24. Structured Text: XML

      • An Overview of XML Parsing

      • Parsing XML with SAX

        • The xml.sax Package

          • make_parser

          • parse

          • parseString

          • ContentHandler

          • Attributes

          • getValueByQ- Name

          • getNameByQ- Name

          • getQNameBy- Name

          • getQNames

          • Incremental parsing

          • close

          • feed

          • reset

          • The xml.sax.saxutils module

          • escape

          • quoteattr

          • XMLGenerator

        • Parsing XHTML with xml.sax

      • Parsing XML with DOM

        • The xml.dom Package

        • The xml.dom.minidom Module

          • parse

          • parseString

          • Node objects

          • attributes

          • childNodes

          • firstChild

          • hasChildNodes

          • isSameNode

          • lastChild

          • localName

          • namespaceURI

          • nextSibling

          • nodeName

          • nodeType

          • nodeValue

          • normalize

          • ownerDocument

          • parentNode

          • prefix

          • previousSibling

          • Attr objects

          • ownerElement

          • specified

          • Document objects

          • doctype

          • document- Element

          • getElementById

          • getElementsBy- TagName

          • getElementsBy- TagNameNS

          • Element objects

          • getAttribute

          • getAttributeNS

          • getAttribute- Node

          • getAttribute- NodeNS

          • getElementsBy- TagName

          • getElementsBy- TagNameNS

          • hasAttribute

          • hasAttributeNS

        • Parsing XHTML with xml.dom.minidom

        • The xml.dom.pulldom Module

          • parse

          • parseString

          • expandNode

        • Parsing XHTML with xml.dom.pulldom

      • Changing and Generating XML

        • Factory Methods of a Document Object

          • createComment

          • createElement

          • createTextNode

        • Mutating Methods of an Element Object

          • removeAttribute

          • setAttribute

        • Mutating Methods of a Node Object

          • appendChild

          • insertBefore

          • removeChild

          • replaceChild

        • Output Methods of a Node Object

          • toprettyxml

          • toxml

          • writexml

        • Changing and Outputting XHTML with xml.dom.minidom

  • V

    • Chapter 25. Extending and Embedding Classic Python

      • Extending Python with Python’s C API

        • Building and Installing C-Coded Python Extensions

          • The C compiler you need

          • Compatibility of C-coded extensions among Python versions

        • Overview of C-Coded Python Extension Modules

        • Return Values of Python’s C API Functions

        • Module Initialization

          • Py_InitModule3

          • PyModule_ AddIntConstant

          • PyModule_ AddObject

          • PyModule_ AddStringCon- stant

          • PyModule_ GetDict

          • PyImport_ Import

          • The PyMethodDef structure

        • Reference Counting

        • Accessing Arguments

          • PyArg_ ParseTuple

          • PyArg_ ParseTuple- AndKeywords

        • Creating Python Values

          • Py_BuildValue

        • Exceptions

          • PyErr_Format

          • PyErr_ NewException

          • PyErr_ NoMemory

          • PyErr_SetObject

          • PyErr_ SetFromErrno

          • PyErr_ SetFromErrno- WithFilename

          • PyErr_Clear

          • PyErr_ Exception- Matches

          • PyErr_Occurred

          • PyErr_Print

        • Abstract Layer Functions

          • PyCallable_ Check

          • PyEval_ CallObject

          • PyEval_ CallObjectWith- Keywords

          • PyIter_Check

          • PyIter_Next

          • PyNumber_ Check

          • PyObject_ CallFunction

          • PyObject_ CallMethod

          • PyObject_Cmp

          • PyObject_ DelAttrString

          • PyObject_ DelItem

          • PyObject_ DelItemString

          • PyObject_ GetAttrString

          • PyObject_ GetItem

          • PyObject_ GetItemString

          • PyObject_ GetIter

          • PyObject_ HasAttrString

          • PyObject_IsTrue

          • PyObject_ Length

          • PyObject_ Repr

          • PyObject_ RichCompare

          • PyObject_ RichCompare- Bool

          • PyObject_ SetAttrString

          • PyObject_ SetItem

          • PyObject_ SetItemString

          • PyObject_Str

          • PyObject_Type

          • PyObject_ Unicode

          • PySequence_ Contains

          • PySequence_ DelSlice

          • PySequence_ Fast

          • PySequence_ Fast_GET_ITEM

          • PySequence_ Fast_GET_SIZE

          • PySequence_ GetSlice

          • PySequence_ List

          • PySequence_ SetSlice

          • PySequence_ Tuple

          • PyNumber_ Power

        • Concrete Layer Functions

          • PyDict_GetItem

          • PyDict_ GetItemString

          • PyDict_Next

          • PyDict_Merge

          • PyDict_ MergeFromSeq2

          • PyFloat_AS_ DOUBLE

          • PyList_New

          • PyList_GET_ ITEM

          • PyList_SET_ ITEM

          • PyString_AS_ STRING

          • PyString_ AsStringAndSize

          • PyString_ FromFormat

          • PyString_ FromStringAnd- Size

          • PyTuple_New

          • PyTuple_GET_ ITEM

          • PyTuple_SET_ ITEM

        • A Simple Extension Example

        • Defining New Types

          • Per-instance data

          • The PyTypeObject definition

          • Instance initialization and finalization

          • Attribute access

          • Type definition example

      • Extending Python Without Python’s C API

      • Embedding Python

        • Installing Resident Extension Modules

          • PyImport_ AppendInittab

        • Setting Arguments

          • Py_SetPro- gramName

          • PySys_SetArgv

        • Python Initialization and Finalization

          • Py_Finalize

          • Py_Initialize

        • Running Python Code

          • PyRun_File

          • PyRun_String

          • PyModule_New

          • Py_ CompileString

          • PyEval_ EvalCode

      • Pyrex

        • The cdef Statement and Function Parameters

          • External declarations

          • cdef classes

        • The ctypedef Statement

        • The for...from Statement

        • Pyrex Expressions

        • A Pyrex Example: Greatest Common Divisor

    • Chapter 26. Extending and Embedding Jython

      • Importing Java Packages in Jython

        • The Jython Registry

        • Accessibility

        • Type Conversions

          • Calling overloaded Java methods

          • The jarray module

          • array

          • zeros

          • The java.util collection classes

        • Subclassing a Java Class

        • JavaBeans

      • Embedding Jython in Java

        • The PythonInterpreter Class

          • eval

          • exec

          • execfile

          • get

          • set

          • The __builtin__ class

        • The PyObject Class

        • The Py Class

      • Compiling Python into Java

        • The jythonc Command

        • Adding Java-Visible Methods

        • Python Applets and Servlets

          • Python applets

          • Python servlets

    • Chapter 27. Distributing Extensions and Programs

      • Python’s distutils

        • The Distribution and Its Root

        • The setup.py Script

        • Metadata About the Distribution

        • Distribution Contents

          • Python source files

          • packages

          • py_modules

          • scripts

          • Datafiles

          • data_files

          • C-coded extensions

          • ext_modules

          • Extension

        • The setup.cfg File

        • The MANIFEST.in and MANIFEST Files

        • Creating Prebuilt Distributions with distutils

      • py2exe

      • py2app

      • cx_Freeze

      • PyInstaller

  • Index

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan