Front Matter

lib.html | lib.html | contents.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# Front Matter
Copyright © 2001 Python Software Foundation.
All rights reserved.
Copyright © 2000 BeOpen.com.
All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives.
All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum.
All rights reserved.
See the end of this document for complete license and permissions
information.
### Abstract:
Python is an extensible, interpreted, object-oriented programming
language. It supports a wide range of applications, from simple text
processing scripts to interactive Web browsers.
While the Python Reference Manual (../ref/ref.html)
describes the exact syntax and semantics of the language, it does not
describe the standard library that is distributed with the language,
and which greatly enhances its immediate usability. This library
contains built-in modules (written in C) that provide access to system
functionality such as file I/O that would otherwise be inaccessible to
Python programmers, as well as modules written in Python that provide
standardized solutions for many problems that occur in everyday
programming. Some of these modules are explicitly designed to
encourage and enhance the portability of Python programs.
This library reference manual documents Python's standard library, as
well as many optional library modules (which may or may not be
available, depending on whether the underlying platform supports them
and on the configuration choices made at compile time). It also
documents the standard types of the language and its built-in
functions and exceptions, many of which are not or incompletely
documented in the Reference Manual.
This manual assumes basic knowledge about the Python language. For an
informal introduction to Python, see the
Python Tutorial (../tut/tut.html); the
Python Reference Manual (../ref/ref.html) remains the
highest authority on syntactic and semantic questions. Finally, the
manual entitled Extending and Embedding
the Python Interpreter (../ext/ext.html) describes how to add new extensions to Python
and how to embed it in other applications.


11.5.16 FTPHandler Objects

file-handler-objects.html | module-urllib2.html | cacheftp-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.5.16 FTPHandler Objects


11.7.1 FTP Objects

module-ftplib.html | module-ftplib.html | module-gopherlib.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.7.1 FTP Objects
Several methods are available in two flavors: one for handling text
files and another for binary files. These are named for the command
which is used followed by "lines" for the text version or
"binary" for the binary version.
FTP instances have the following methods:


11.2.4 Functions

node281.html | module-cgi.html | node283.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.2.4 Functions
These are useful if you want more control, or if you want to employ
some of the algorithms implemented in this module in other
circumstances.


Index

modindex.html | lib.html | about.html | Python Library Reference | contents.html | modindex.html
---
## Index
---
. (#letter-.) |
< (#letter-<) |
= (#letter-=) |
_ (#letter-_) |
a (#letter-a) |
b (#letter-b) |
c (#letter-c) |
d (#letter-d) |
e (#letter-e) |
f (#letter-f) |
g (#letter-g) |
h (#letter-h) |
i (#letter-i) |
j (#letter-j) |
k (#letter-k) |
l (#letter-l) |
m (#letter-m) |
n (#letter-n) |
o (#letter-o) |
p (#letter-p) |
q (#letter-q) |
r (#letter-r) |
s (#letter-s) |
t (#letter-t) |
u (#letter-u) |
v (#letter-v) |
w (#letter-w) |
x (#letter-x) |
y (#letter-y) |
z (#letter-z)
---
## . (dot)
---
## <
---
## =
---
## _ (underscore)
---
## A
---
## B
---
## C
---
## D
---
## E
---
## F
---
## G
---
## H
---
## I
---
## J
---
## K
---
## L
---
## M
---
## N
---
## O
---
## P
---
## Q
---
## R
---
## S
---
## T
---
## U
---
## V
---
## W
---
## X
---
## Y
---
## Z


11.5.18 GopherHandler Objects

cacheftp-handler-objects.html | module-urllib2.html | unknown-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.5.18 GopherHandler Objects


22.2.1 Registry Handle Objects

module--winreg.html | module--winreg.html | module-winsound.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 22.2.1 Registry Handle Objects
This object wraps a Windows HKEY object, automatically closing it when
the object is destroyed. To guarantee cleanup, you can call either
the Close() method on the object, or the
CloseKey() function.
All registry functions in this module return one of these objects.
All registry functions in this module which accept a handle object
also accept an integer, however, use of the handle object is
encouraged.
Handle objects provide semantics for __nonzero__() - thus
```text

if handle:
print "Yes"
```
will print `Yes` if the handle is currently valid (has not been
closed or detached).
The object also support comparison semantics, so handle
objects will compare true if they both reference the same
underlying Windows handle value.
Handle objects can be converted to an integer (eg, using the
builtin int() function, in which case the underlying
Windows handle value is returned. You can also use the
Detach() method to return the integer handle, and
also disconnect the Windows handle from the handle object.


13.3.1 HTMLParser Objects

module-htmllib.html | module-htmllib.html | module-htmlentitydefs.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 13.3.1 HTMLParser Objects
In addition to tag methods, the HTMLParser class provides some
additional methods and instance variables for use within tag methods.


13.1.1 Example HTML Parser

module-HTMLParser.html | module-HTMLParser.html | module-sgmllib.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 13.1.1 Example HTML Parser
As a basic example, below is a very basic HTML parser that uses the
HTMLParser class to print out tags as they are encountered:


11.5.8 HTTPBasicAuthHandler Objects

abstract-basic-auth-handler.html | module-urllib2.html | proxy-basic-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.5.8 HTTPBasicAuthHandler Objects


11.5.11 HTTPDigestAuthHandler Objects

abstract-digest-auth-handler.html | module-urllib2.html | proxy-digest-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.5.11 HTTPDigestAuthHandler Objects


11.5.13 HTTPHandler Objects

proxy-digest-auth-handler.html | module-urllib2.html | https-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.5.13 HTTPHandler Objects


11.5.6 HTTPPasswordMgr Objects

proxy-handler.html | module-urllib2.html | abstract-basic-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.5.6 HTTPPasswordMgr Objects
These methods are available on HTTPPasswordMgr and
HTTPPasswordMgrWithDefaultRealm objects.


11.5.4 HTTPRedirectHandler Objects

base-handler-objects.html | module-urllib2.html | proxy-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.5.4 HTTPRedirectHandler Objects
Note:
303 redirection is not supported by this version of
urllib2.


11.6.1 HTTPConnection Objects

module-httplib.html | module-httplib.html | httpresponse-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.6.1 HTTPConnection Objects
HTTPConnection instances have the following methods:


11.6.3 Examples

httpresponse-objects.html | module-httplib.html | module-ftplib.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.6.3 Examples
Here is an example session that uses the "GET" method:
```text

>>> import httplib
>>> conn = httplib.HTTPConnection("www.python.org")
>>> conn.request("GET", "/index.html")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print r2.status, r2.reason
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
```
Here is an example session that shows how to "POST" requests:


11.6.2 HTTPResponse Objects

httpconnection-objects.html | module-httplib.html | httplib-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.6.2 HTTPResponse Objects
HTTPResponse instances have the following methods and attributes:


11.5.14 HTTPSHandler Objects

http-handler-objects.html | module-urllib2.html | file-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.5.14 HTTPSHandler Objects


16.5 Idle

pen-rawpen-objects.html | tkinter.html | node532.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 16.5 Idle
Idle is the Python IDE built with the Tkinter (module-Tkinter.html) GUI toolkit.
IDLE has the following features:
- coded in 100% pure Python, using the Tkinter (module-Tkinter.html) GUI toolkit
- cross-platform: works on Windows and Unix (on Mac OS, there are
currently problems with Tcl/Tk)
- multi-window text editor with multiple undo, Python colorizing
and many other features, e.g. smart indent and call tips
- Python shell window (a.k.a. interactive interpreter)
- debugger (not complete, but you can set breakpoints, view and step)


11.10.2 IMAP4 Example

imap4-objects.html | module-imaplib.html | module-nntplib.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.10.2 IMAP4 Example
Here is a minimal example (without error checking) that opens a
mailbox and retrieves and prints all messages:


11.10.1 IMAP4 Objects

module-imaplib.html | module-imaplib.html | imap4-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.10.1 IMAP4 Objects
All IMAP4rev1 commands are represented by methods of the same name,
either upper-case or lower-case.
All arguments to commands are converted to strings, except for
"AUTHENTICATE", and the last argument to "APPEND" which is
passed as an IMAP4 literal. If necessary (the string contains IMAP4
protocol-sensitive characters and isn't enclosed with either
parentheses or double quotes) each string is quoted. However, the
password argument to the "LOGIN" command is always quoted.
If you want to avoid having an argument string quoted
(eg: the flags argument to "STORE") then enclose the string in
parentheses (eg: `r'(\Deleted)'`).
Each command returns a tuple: `( type , [ data ,
...])` where type is usually `'OK'` or `'NO'`,
and data is either the text from the command response, or
mandated results from the command.
An IMAP4 instance has the following methods:
The following attributes are defined on instances of IMAP4:


13.12.2 IncrementalParser Objects

xmlreader-objects.html | module-xml.sax.xmlreader.html | locator-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 13.12.2 IncrementalParser Objects
Instances of IncrementalParser offer the following additional
methods:


Python Library Reference

../index.html | front.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# Python Library Reference
Guido van Rossum
Fred L. Drake, Jr., editor
PythonLabs
Email: python-docs@python.org
Release 2.2
December 21, 2001


13.12.4 InputSource Objects

locator-objects.html | module-xml.sax.xmlreader.html | attributes-impl-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 13.12.4 InputSource Objects


3.11.3 Classes and functions

inspect-source.html | module-inspect.html | inspect-stack.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 3.11.3 Classes and functions


3.11.2 Retrieving source code

inspect-types.html | module-inspect.html | inspect-classes-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 3.11.2 Retrieving source code


3.11.4 The interpreter stack

inspect-classes-functions.html | module-inspect.html | module-traceback.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 3.11.4 The interpreter stack
When the following functions return ``frame records,'' each record
is a tuple of six items: the frame object, the filename,
the line number of the current line, the function name, a list of
lines of context from the source code, and the index of the current
line within that list.
The optional context argument specifies the number of lines of
context to return, which are centered around the current line.
Warning:
Keeping references to frame objects, as found in
the first element of the frame records these functions return, can
cause your program to create reference cycles. Once a reference cycle
has been created, the lifespan of all objects which can be accessed
from the objects which form the cycle can become much longer even if
Python's optional cycle detector is enabled. If such cycles must be
created, it is important to ensure they are explicitly broken to avoid
the delayed destruction of objects and increased memory consumption
which occurs.


3.11.1 Types and members

module-inspect.html | module-inspect.html | inspect-source.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 3.11.1 Types and members
The getmembers() function retrieves the members
of an object such as a class or module.
The nine functions whose names begin with ``is'' are mainly
provided as convenient choices for the second argument to
getmembers(). They also help you determine when
you can expect to find the following special attributes:
Note:
(1): Changed in version 2.2:
im_class used to refer to the class that
defined the method.


11. Internet Protocols and Support

node289.html | lib.html | module-webbrowser.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11. Internet Protocols and Support
The modules described in this chapter implement Internet protocols and
support for related technology. They are all implemented in Python.
Most of these modules require the presence of the system-dependent
module socket (module-socket.html), which is currently
supported on most popular platforms. Here is an overview:


3.22.1 Interactive Interpreter Objects

module-code.html | module-code.html | console-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 3.22.1 Interactive Interpreter Objects


1. Introduction

contents.html | lib.html | builtin.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 1. Introduction
The ``Python library'' contains several different kinds of components.
It contains data types that would normally be considered part of the
``core'' of a language, such as numbers and lists. For these types,
the Python language core defines the form of literals and places some
constraints on their semantics, but does not fully define the
semantics. (On the other hand, the language core does define
syntactic properties like the spelling and priorities of operators.)
The library also contains built-in functions and exceptions --
objects that can be used by all Python code without the need of an
import statement. Some of these are defined by the core
language, but many are not essential for the core semantics and are
only described here.
The bulk of the library, however, consists of a collection of modules.
There are many ways to dissect this collection. Some modules are
written in C and built in to the Python interpreter; others are
written in Python and imported in source form. Some modules provide
interfaces that are highly specific to Python, like printing a stack
trace; some provide interfaces that are specific to particular
operating systems, such as access to specific hardware; others provide
interfaces that are
specific to a particular application domain, like the World Wide Web.
Some modules are available in all versions and ports of Python; others
are only available when the underlying system supports or requires
them; yet others are available only when a particular configuration
option was chosen at the time when Python was compiled and installed.
This manual is organized ``from the inside out:'' it first describes
the built-in data types, then the built-in functions and exceptions,
and finally the modules, grouped in chapters of related modules. The
ordering of the chapters as well as the ordering of the modules within
each chapter is roughly from most relevant to least important.
This means that if you start reading this manual from the start, and
skip to the next chapter when you get bored, you will get a reasonable
overview of the available modules and application areas that are
supported by the Python library. Of course, you don't have to
read it like a novel -- you can also browse the table of contents (in
front of the manual), or look for a specific function, module or term
in the index (in the back). And finally, if you enjoy learning about
random subjects, you choose a random page number (see module
random (module-random.html)) and read a section or two. Regardless of the
order in which you read the sections of this manual, it helps to start
with chapter 2 (builtin.html#builtin), ``Built-in Types, Exceptions and
Functions,'' as the remainder of the manual assumes familiarity with
this material.
Let the show begin!


18. Python Language Services

module-Bastion.html | lib.html | module-parser.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 18. Python Language Services
Python provides a number of modules to assist in working with the
Python language. These module support tokenizing, parsing, syntax
analysis, bytecode disassembly, and various other facilities.
These modules include:


5.3.2 Re-using old test code

organizing-tests.html | module-unittest.html | unittest-contents.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.3.2 Re-using old test code
Some users will find that they have existing test code that they would
like to run from PyUnit, without converting every old test function to
a TestCase subclass.
For this reason, PyUnit provides a FunctionTestCase class.
This subclass of TestCase can be used to wrap an existing test
function. Set-up and tear-down functions can also optionally be
wrapped.
Given the following test function:
```text

def testSomething():
something = makeSomething()
assert something.name is not None
# ...
```
one can create an equivalent test case instance as follows:
```text

testcase = unittest.FunctionTestCase(testSomething)
```
If there are additional set-up and tear-down methods that should be
called as part of the test case's operation, they can also be provided:
```text

testcase = unittest.FunctionTestCase(testSomething,
setUp=makeSomethingDB,
tearDown=deleteSomethingDB)
```
Note:
PyUnit supports the use of AssertionError
as an indicator of test failure, but does not recommend it. Future
versions may treat AssertionError differently.


Python Library Reference


13.12.3 Locator Objects

incremental-parser-objects.html | module-xml.sax.xmlreader.html | input-source-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 13.12.3 Locator Objects
Instances of Locator provide these methods:


7.5.1 Lock Objects

module-threading.html | module-threading.html | rlock-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 7.5.1 Lock Objects
A primitive lock is a synchronization primitive that is not owned
by a particular thread when locked. In Python, it is currently
the lowest level synchronization primitive available, implemented
directly by the thread (module-thread.html) extension module.
A primitive lock is in one of two states, ``locked'' or ``unlocked''.
It is created in the unlocked state. It has two basic methods,
acquire() and release(). When the state is
unlocked, acquire() changes the state to locked and returns
immediately. When the state is locked, acquire() blocks
until a call to release() in another thread changes it to
unlocked, then the acquire() call resets it to locked and
returns. The release() method should only be called in the
locked state; it changes the state to unlocked and returns
immediately. When more than one thread is blocked in
acquire() waiting for the state to turn to unlocked, only one
thread proceeds when a release() call resets the state to
unlocked; which one of the waiting threads proceeds is not defined,
and may vary across implementations.
All methods are executed atomically.


12.4.1 Mailbox Objects

module-mailbox.html | module-mailbox.html | module-mhlib.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.4.1 Mailbox Objects
All implementations of mailbox objects are iterable objects, and
have one externally visible method. This method is used by iterators
created from mailbox objects and may also be used directly.


13. Structured Markup Processing Tools

module-robotparser.html | lib.html | module-HTMLParser.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 13. Structured Markup Processing Tools
Python supports a variety of modules to work with various forms of
structured data markup. This includes modules to work with the
Standard Generalized Markup Language (SGML) and the Hypertext Markup
Language (HTML), and several interfaces for working with the
Extensible Markup Language (XML).


4.2.5 Match Objects

re-objects.html | module-re.html | node102.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 4.2.5 Match Objects
MatchObject instances support the following methods and
attributes:


4.2.2 Matching vs. Searching

re-syntax.html | module-re.html | node99.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 4.2.2 Matching vs. Searching
Python offers two different primitive operations based on regular
expressions: match and search. If you are accustomed to Perl's
semantics, the search operation is what you're looking for. See the
search() function and corresponding method of compiled
regular expression objects.
Note that match may differ from search using a regular expression
beginning with "^": "^" matches only at the
start of the string, or in MULTILINE mode also immediately
following a newline. The ``match'' operation succeeds only if the
pattern matches at the start of the string regardless of mode, or at
the starting position given by the optional pos argument
regardless of whether a newline precedes it.
```text

re.compile("a").match("ba", 1) # succeeds
re.compile("^a").search("ba", 1) # fails; 'a' not at start
re.compile("^a").search("\na", 1) # fails; 'a' not at start
re.compile("^a", re.M).search("\na", 1) # succeeds
re.compile("^a", re.M).search("ba", 1) # fails; no preceding \n
```


12.11.1 Message Objects

module-rfc822.html | module-rfc822.html | addresslist-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.11.1 Message Objects
A Message instance has the following methods:
Message instances also support a limited mapping interface.
In particular: `m [name]` is like
`m .getheader(name)` but raises KeyError if
there is no matching header; and `len( m )`,
`m .get(name [ , deafult ] )`,
`m .has_key(name)`, `m .keys()`,
`m .values()` `m .items()`, and
`m .setdefault(name [ , default ] )` act as expected,
with the one difference that get() and setdefault()
use an empty string as the default value. Message instances
also support the mapping writable interface `m [name] =
value` and `del m [name]`. Message objects do not
support the clear(), copy(), popitem(), or
update() methods of the mapping interface. (Support for
get() and setdefault() was only added in Python
2.2.)
Finally, Message instances have some public instance variables:


12.5.2 Folder Objects

mh-objects.html | module-mhlib.html | mh-message-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.5.2 Folder Objects
Folder instances represent open folders and have the following
methods:


12.5.3 Message Objects

mh-folder-objects.html | module-mhlib.html | module-mimetools.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.5.3 Message Objects
The Message class adds one method to those of
mimetools.Message:


12.5.1 MH Objects

module-mhlib.html | module-mhlib.html | mh-folder-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.5.1 MH Objects
MH instances have the following methods:


module-mimetools.html | module-mimetools.html | module-mimetypes.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.6.1 Additional Methods of Message Objects
The Message class defines the following methods in
addition to the rfc822.Message methods:


12.7.1 MimeTypes Objects

module-mimetypes.html | module-mimetypes.html | module-MimeWriter.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.7.1 MimeTypes Objects
MimeTypes instances provide an interface which is very like
that of the mimetypes (module-mimetypes.html) module.


12.8.1 MimeWriter Objects

module-MimeWriter.html | module-MimeWriter.html | module-mimify.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.8.1 MimeWriter Objects
MimeWriter instances have the following methods:


13.7.3 minidom and the DOM standard

dom-example.html | module-xml.dom.minidom.html | module-xml.dom.pulldom.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 13.7.3 minidom and the DOM standard
The xml.dom.minidom (module-xml.dom.minidom.html) module is essentially a DOM
1.0-compatible DOM with some DOM 2 features (primarily namespace
features).
Usage of the DOM interface in Python is straight-forward. The
following mapping rules apply:
- Interfaces are accessed through instance objects. Applications
should not instantiate the classes themselves; they should use
the creator functions available on the Document object.
Derived interfaces support all operations (and attributes) from
the base interfaces, plus any new operations.
- Operations are used as methods. Since the DOM uses only
in parameters, the arguments are passed in normal
order (from left to right). There are no optional
arguments. void operations return `None`.
- IDL attributes map to instance attributes. For compatibility
with the OMG IDL language mapping for Python, an attribute
`foo` can also be accessed through accessor methods
_get_foo() and _set_foo(). readonly
attributes must not be changed; this is not enforced at
runtime.
- The types `short int`, `unsigned int`, `unsigned
long long`, and `boolean` all map to Python integer
objects.
- The type `DOMString` maps to Python strings.
xml.dom.minidom (module-xml.dom.minidom.html) supports either byte or Unicode
strings, but will normally produce Unicode strings. Values
of type `DOMString` may also be `None` where allowed
to have the IDL `null` value by the DOM specification from
the W3C.
- const declarations map to variables in their
respective scope
(e.g. `xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE`);
they must not be changed.
- `DOMException` is currently not supported in
xml.dom.minidom (module-xml.dom.minidom.html). Instead,
xml.dom.minidom (module-xml.dom.minidom.html) uses standard Python exceptions such
as TypeError and AttributeError.
- NodeList objects are implemented using Python's built-in
list type. Starting with Python 2.2, these objects provide the
interface defined in the DOM specification, but with earlier
versions of Python they do not support the official API. They
are, however, much more ``Pythonic'' than the interface defined
in the W3C recommendations.
The following interfaces have no implementation in
xml.dom.minidom (module-xml.dom.minidom.html):
- DOMTimeStamp
- DocumentType (added in Python 2.1)
- DOMImplementation (added in Python 2.1)
- CharacterData
- CDATASection
- Notation
- Entity
- EntityReference
- DocumentFragment


5. Miscellaneous Services

module-unicodedata.html | lib.html | module-pydoc.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5. Miscellaneous Services
The modules described in this chapter provide miscellaneous services
that are available in all Python versions. Here's an overview:


14. Multimedia Services

xml-namespace.html | lib.html | module-audioop.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 14. Multimedia Services
The modules described in this chapter implement various algorithms or
interfaces that are mainly useful for multimedia applications. They
are available at the discretion of the installation. Here's an overview:


Module Index

node622.html | lib.html | genindex.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## Module Index
This index only lists modules documented in this manual.
The Global Module
Index (../modindex.html) lists all modules that are documented in this set
of manuals.
Some module names are followed by an annotation indicating what
platform they are available on.


22.2 _winreg - Windows registry access

msvcrt-other.html | node604.html | handle-object.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 22.2 _winreg -
Windows registry access
Availability: Windows.
New in version 2.0.
These functions expose the Windows registry API to Python. Instead of
using an integer as the registry handle, a handle object is used to
ensure that the handles are closed correctly, even if the programmer
neglects to explicitly close them.
This module exposes a very low-level interface to the Windows
registry; it is expected that in the future a new `winreg`
module will be created offering a higher-level interface to the
registry API.
This module offers the following functions:


module-imageop.html | mmedia.html | module-sunau.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 14.3 aifc --
Read and write AIFF and AIFC files
This module provides support for reading and writing AIFF and AIFF-C
files. AIFF is Audio Interchange File Format, a format for storing
digital audio samples in a file. AIFF-C is a newer version of the
format that includes the ability to compress the audio data.
Caveat: Some operations may only work under IRIX; these will
raise ImportError when attempting to import the
cl module, which is only available on IRIX.
Audio files have a number of parameters that describe the audio data.
The sampling rate or frame rate is the number of times per second the
sound is sampled. The number of channels indicate if the audio is
mono, stereo, or quadro. Each frame consists of one sample per
channel. The sample size is the size in bytes of each sample. Thus a
frame consists of nchannels*samplesize bytes, and a
second's worth of audio consists of
nchannels*samplesize*framerate bytes.
For example, CD quality audio has a sample size of two bytes (16
bits), uses two channels (stereo) and has a frame rate of 44,100
frames/second. This gives a frame size of 4 bytes (2*2), and a
second's worth occupies 2*2*44100 bytes (176,400 bytes).
Module aifc defines the following function:
Objects returned by open() when a file is opened for
reading have the following methods:
Objects returned by open() when a file is opened for
writing have all the above methods, except for readframes() and
setpos(). In addition the following methods exist. The
get*() methods can only be called after the corresponding
set*() methods have been called. Before the first
writeframes() or writeframesraw(), all parameters
except for the number of frames must be filled in.


al-port-objects.html | sgi.html | module-cd.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 20.2 AL --
Constants used with the al module
Availability: IRIX.
This module defines symbolic constants needed to use the built-in
module al (module-al.html) (see above); they are equivalent to those defined
in the C header file `<audio.h>` except that the name prefix
"AL_" is omitted. Read the module source for a complete list of
the defined names. Suggested use:


20.1 al -- Audio functions on the SGI

sgi.html | sgi.html | al-config-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 20.1 al --
Audio functions on the SGI
Availability: IRIX.
This module provides access to the audio facilities of the SGI Indy
and Indigo workstations. See section 3A of the IRIX man pages for
details. You'll need to read those man pages to understand what these
functions do! Some of the functions are not available in IRIX
releases before 4.0.5. Again, see the manual to check whether a
specific function is available on your platform.
All functions and methods defined in this module are equivalent to
the C functions with "AL" prefixed to their name.
Symbolic constants from the C header file `<audio.h>` are
defined in the standard module
AL (module-al-constants.html), see below.
Warning:
The current version of the audio library may dump core
when bad argument values are passed rather than returning an error
status. Unfortunately, since the precise circumstances under which
this may happen are undocumented and hard to check, the Python
interface can provide no protection against this kind of problems.
(One example is specifying an excessive queue size -- there is no
documented upper limit.)
The module defines the following functions:


module-mmap.html | someos.html | module-dumbdbm.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.8 anydbm --
Generic access to DBM-style databases
anydbm is a generic interface to variants of the DBM
database -- dbhash (module-dbhash.html)(requires
bsddb (module-bsddb.html)),
gdbm (module-gdbm.html), or
dbm (module-dbm.html). If none of these modules is
installed, the slow-but-simple implementation in module
dumbdbm (module-dumbdbm.html)will be used.
The object returned by open() supports most of the same
functionality as dictionaries; keys and their corresponding values can
be stored, retrieved, and deleted, and the has_key() and
keys() methods are available. Keys and values must always be
strings.
See Also:


bisect-example.html | misc.html | module-ConfigParser.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5.9 array --
Efficient arrays of numeric values
This module defines a new object type which can efficiently represent
an array of basic values: characters, integers, floating point
numbers. Arraysare sequence types and behave very much
like lists, except that the type of objects stored in them is
constrained. The type is specified at object creation time by using a
type code, which is a single character. The following type
codes are defined:
The actual representation of values is determined by the machine
architecture (strictly speaking, by the C implementation). The actual
size can be accessed through the itemsize attribute. The values
stored for `'L'` and `'I'` items will be represented as
Python long integers when retrieved, because Python's plain integer
type cannot represent the full range of C's unsigned (long) integers.
The module defines the following function and type object:
Array objects support the following data items and methods:
When an array object is printed or converted to a string, it is
represented as `array( typecode , initializer )`. The
initializer is omitted if the array is empty, otherwise it is a
string if the typecode is `'c'`, otherwise it is a list of
numbers. The string is guaranteed to be able to be converted back to
an array with the same type and value using reverse quotes
(````), so long as the array() function has been
imported using `from array import array`. Examples:
```text

array('l')
array('c', 'hello world')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])
```


simple-xmlrpc-servers.html | internet.html | asyncore-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.22 asyncore --
Asynchronous socket handler
This module provides the basic infrastructure for writing asynchronous
socket service clients and servers.
There are only two ways to have a program on a single processor do
``more than one thing at a time.'' Multi-threaded programming is the
simplest and most popular way to do it, but there is another very
different technique, that lets you have nearly all the advantages of
multi-threading, without actually using multiple threads. It's really
only practical if your program is largely I/O bound. If your program
is processor bound, then pre-emptive scheduled threads are probably what
you really need. Network servers are rarely processor bound, however.
If your operating system supports the select() system call
in its I/O library (and nearly all do), then you can use it to juggle
multiple communication channels at once; doing other work while your
I/O is taking place in the ``background.'' Although this strategy can
seem strange and complex, especially at first, it is in many ways
easier to understand and control than multi-threaded programming.
The module documented here solves many of the difficult problems for
you, making the task of building sophisticated high-performance
network servers and clients a snap.
This set of user-level events is larger than the basics. The
full set of methods that can be overridden in your subclass are:
In addition, there are the basic methods needed to construct and
manipulate ``channels,'' which are what we will call the socket
connections in this context. Note that most of these are nearly
identical to their socket partners.


3.5 atexit -- Exit handlers

node41.html | python.html | atexit-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.5 atexit --
Exit handlers
New in version 2.0.
The atexit module defines a single function to register
cleanup functions. Functions thus registered are automatically
executed upon normal interpreter termination.
Note: the functions registered via this module are not called when the program is killed by a
signal, when a Python fatal internal error is detected, or when
os._exit() is called.
This is an alternate interface to the functionality provided by the
`sys.exitfunc` variable.
Note: This module is unlikely to work correctly when used with other code
that sets `sys.exitfunc`. In particular, other core Python modules are
free to use atexit without the programmer's knowledge. Authors who
use `sys.exitfunc` should convert their code to use
atexit instead. The simplest way to convert code that sets
`sys.exitfunc` is to import atexit and register the function
that had been bound to `sys.exitfunc`.
See Also:


mmedia.html | mmedia.html | module-imageop.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 14.1 audioop --
Manipulate raw audio data
The audioop module contains some useful operations on sound
fragments. It operates on sound fragments consisting of signed
integer samples 8, 16 or 32 bits wide, stored in Python strings. This
is the same format as used by the al (module-al.html) and sunaudiodev (module-sunaudiodev.html)
modules. All scalar items are integers, unless specified otherwise.
This module provides support for u-LAW and Intel/DVI ADPCM encodings.
A few of the more complicated operations only take 16-bit samples,
otherwise the sample size (in bytes) is always a parameter of the
operation.
The module defines the following variables and functions:
Note that operations such as mul() or max() make
no distinction between mono and stereo fragments, i.e. all samples
are treated equal. If this is a problem the stereo fragment should be
split into two mono fragments first and recombined later. Here is an
example of how to do that:
```text

def mul_stereo(sample, width, lfactor, rfactor):
lsample = audioop.tomono(sample, width, 1, 0)
rsample = audioop.tomono(sample, width, 0, 1)
lsample = audioop.mul(sample, width, lfactor)
rsample = audioop.mul(sample, width, rfactor)
lsample = audioop.tostereo(lsample, width, 1, 0)
rsample = audioop.tostereo(rsample, width, 0, 1)
return audioop.add(lsample, rsample, width)
```
If you use the ADPCM coder to build network packets and you want your
protocol to be stateless (i.e. to be able to tolerate packet loss)
you should not only transmit the data but also the state. Note that
you should send the initial state (the one you passed to
lin2adpcm()) along to the decoder, not the final state (as
returned by the coder). If you want to use struct.struct()
to store the state in binary you can code the first element (the
predicted value) in 16 bits and the second (the delta index) in 8.
The ADPCM coders have never been tried against other ADPCM coders,
only against themselves. It could well be that I misinterpreted the
standards in which case they will not be interoperable with the
respective standards.
The find*() routines might look a bit funny at first sight.
They are primarily meant to do echo cancellation. A reasonably
fast way to do this is to pick the most energetic piece of the output
sample, locate that in the input sample and subtract the whole output
sample from the input sample:


addresslist-objects.html | netdata.html | module-binascii.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 12.12 base64 --
Encode and decode MIME base64 data
This module performs base64 encoding and decoding of arbitrary binary
strings into text strings that can be safely sent by email or included
as part of an HTTP POST request. The
encoding scheme is defined in RFC 1521 (http://www.faqs.org/rfcs/rfc1521.html) (MIME
(Multipurpose Internet Mail Extensions) Part One: Mechanisms for
Specifying and Describing the Format of Internet Message Bodies,
section 5.2, ``Base64 Content-Transfer-Encoding'') and is used for
MIME email and various other Internet-related applications; it is not
the same as the output produced by the uuencode program.
For example, the string `'www.python.org'` is encoded as the
string `'d3d3LnB5dGhvbi5vcmc=\n'`.


module-SocketServer.html | internet.html | module-SimpleHTTPServer.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.16 BaseHTTPServer --
Basic HTTP server
This module defines two classes for implementing HTTP servers
(Web servers). Usually, this module isn't used directly, but is used
as a basis for building functioning Web servers. See the
SimpleHTTPServerand
CGIHTTPServer (module-CGIHTTPServer.html)modules.
The first class, HTTPServer, is a
SocketServer.TCPServer subclass. It creates and listens at the
HTTP socket, dispatching the requests to a handler. Code to create and
run the server looks like this:
```text

def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
```
BaseHTTPRequestHandler has the following instance variables:
BaseHTTPRequestHandler has the following class variables:
A BaseHTTPRequestHandler instance has the following methods:


node547.html | restricted.html | language.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 17.2 Bastion --
Restricting access to objects
According to the dictionary, a bastion is ``a fortified area or
position'', or ``something that is considered a stronghold.'' It's a
suitable name for this module, which provides a way to forbid access
to certain attributes of an object. It must always be used with the
rexec (module-rexec.html) module, in order to allow restricted-mode programs
access to certain safe attributes of an object, while denying access
to other, unsafe attributes.


module-base64.html | netdata.html | module-binhex.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 12.13 binascii --
Convert between binary and ASCII
The binascii module contains a number of methods to convert
between binary and various ASCII-encoded binary
representations. Normally, you will not use these functions directly
but use wrapper modules like uu (module-uu.html)or
binhex (module-binhex.html)instead, this module solely
exists because bit-manipulation of large amounts of data is slow in
Python.
The binascii module defines the following functions:


module-binascii.html | netdata.html | binhex-notes.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 12.14 binhex --
Encode and decode binhex4 files
This module encodes and decodes files in binhex4 format, a format
allowing representation of Macintosh files in ASCII. On the Macintosh,
both forks of a file and the finder information are encoded (or
decoded), on other platforms only the data fork is handled.
The binhex module defines the following functions:
See Also:


5.8 bisect -- Array bisection algorithm

module-whrandom.html | misc.html | bisect-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5.8 bisect --
Array bisection algorithm
This module provides support for maintaining a list in sorted order
without having to sort the list after each insertion. For long lists
of items with expensive comparison operations, this can be an
improvement over the more common approach. The module is called
bisect because it uses a basic bisection algorithm to do its
work. The source code may be most useful as a working example of the
algorithm (the boundary conditions are already right!).
The following functions are provided:


module-whichdb.html | someos.html | bsddb-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.12 bsddb --
Interface to Berkeley DB library
Availability: Unix, Windows.
The bsddb module provides an interface to the Berkeley DB
library. Users can create hash, btree or record based library files
using the appropriate open call. Bsddb objects behave generally like
dictionaries. Keys and values must be strings, however, so to use
other objects as keys or to store other kinds of objects the user must
serialize them somehow, typically using marshal.dumps or pickle.dumps.
There are two incompatible versions of the underlying library.
Version 1.85 is widely available, but has some known bugs. Version 2
is not quite as widely used, but does offer some improvements. The
bsddb module uses the 1.85 interface. Starting with Python
2.0, the configure script can usually determine the
version of the library which is available and build it correctly. If
you have difficulty getting configure to do the right thing,
run it with the --help option to get information about
additional options that can help. On Windows, you will need to define
the `HAVE_DB_185_H` macro if you are building Python from source
and using version 2 of the DB library.
The bsddb module defines the following functions that create
objects that access the appropriate type of Berkeley DB file. The
first two arguments of each function are the same. For ease of
portability, only the first two arguments should be used in most
instances.
See Also:


3.29 __builtin__ -- Built-in functions

module-user.html | python.html | module-main.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.29 __builtin__ --
Built-in functions


module-xreadlines.html | misc.html | module-cmd.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5.13 calendar --
General calendar-related functions
This module allows you to output calendars like the Unix
cal program, and provides additional useful functions
related to the calendar. By default, these calendars have Monday as
the first day of the week, and Sunday as the last (the European
convention). Use setfirstweekday() to set the first day of the
week to Sunday (6) or to any other weekday. Parameters that specify
dates are given as integers.


20.3 cd -- CD-ROM access on SGI systems

module-al-constants.html | sgi.html | player-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 20.3 cd --
CD-ROM access on SGI systems
Availability: IRIX.
This module provides an interface to the Silicon Graphics CD library.
It is available only on Silicon Graphics systems.
The way the library works is as follows. A program opens the CD-ROM
device with open() and creates a parser to parse the data
from the CD with createparser(). The object returned by
open() can be used to read data from the CD, but also to get
status information for the CD-ROM device, and to get information about
the CD, such as the table of contents. Data from the CD is passed to
the parser, which parses the frames, and calls any callback
functions that have previously been added.
An audio CD is divided into tracks or programs (the terms
are used interchangeably). Tracks can be subdivided into
indices. An audio CD contains a table of contents which
gives the starts of the tracks on the CD. Index 0 is usually the
pause before the start of a track. The start of the track as given by
the table of contents is normally the start of index 1.
Positions on a CD can be represented in two ways. Either a frame
number or a tuple of three values, minutes, seconds and frames. Most
functions use the latter representation. Positions can be both
relative to the beginning of the CD, and to the beginning of the
track.
Module cd defines the following functions and constants:
The module defines the following variables:
The following variables are states as returned by
getstatus():


browser-controllers.html | internet.html | cgi-intro.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.2 cgi --
Common Gateway Interface support.
Support module for Common Gateway Interface (CGI) scripts.
This module defines a number of utilities for use by CGI scripts
written in Python.


module-SimpleHTTPServer.html | internet.html | module-Cookie.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.18 CGIHTTPServer --
CGI-capable HTTP request handler
The CGIHTTPServer module defines a request-handler class,
interface compatible with
BaseHTTPServer.BaseHTTPRequestHandler and inherits behavior
from SimpleHTTPServer.SimpleHTTPRequestHandler but can also
run CGI scripts.
Note:
This module can run CGI scripts on Unix and Windows systems;
on Mac OS it will only be able to run Python scripts within the same
process as itself.
The CGIHTTPServer module defines the following class:
The CGIHTTPRequestHandler defines the following data member:
The CGIHTTPRequestHandler defines the following methods:
Note that CGI scripts will be run with UID of user nobody, for security
reasons. Problems with the CGI script will be translated to error 403.
For example usage, see the implementation of the test()
function.


node303.html | internet.html | module-urllib.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.3 cgitb --
Traceback manager for CGI scripts
New in version 2.2.
The cgitb module provides a special exception handler for CGI
scripts. After this module is activated, if an uncaught exception occurs,
a detailed, formatted report will be sent to the Web browser. The report
includes a traceback showing excerpts of the source code for each level,
as well as the values of the arguments and local variables to currently
running functions, to help you debug the problem. Optionally, you can
save this information to a file instead of sending it to the browser.
To enable this feature, simply add one line to the top of your CGI script:
```text

import cgitb; cgitb.enable()
```
The options to the enable() function control whether the
report is displayed in the browser and whether the report is logged
to a file for later analysis.


14.6 chunk -- Read IFF chunked data

Wave-write-objects.html | mmedia.html | module-colorsys.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 14.6 chunk --
Read IFF chunked data
This module provides an interface for reading files that use EA IFF 85
chunks.14.1 (#foot44678) This format is used
in at least the AudioInterchange File Format
(AIFF/AIFF-C) and the RealMedia File
Format(RMFF). The WAVE audio file format is closely
related and can also be read using this module.
A chunk has the following structure:
The ID is a 4-byte string which identifies the type of chunk.
The size field (a 32-bit value, encoded using big-endian byte order)
gives the size of the chunk data, not including the 8-byte header.
Usually an IFF-type file consists of one or more chunks. The proposed
usage of the Chunk class defined here is to instantiate an
instance at the start of each chunk and read from the instance until
it reaches the end, after which a new instance can be instantiated.
At the end of the file, creating a new instance will fail with a
EOFError exception.
A Chunk object supports the following methods:
The remaining methods will raise IOError if called after
the close() method has been called.


module-math.html | misc.html | module-random.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5.5 cmath --
Mathematical functions for complex numbers
This module is always available. It provides access to mathematical
functions for complex numbers. The functions are:
The module also defines two mathematical constants:
Note that the selection of functions is similar, but not identical, to
that in module math (module-math.html). The reason for having
two modules is that some users aren't interested in complex numbers,
and perhaps don't even know what they are. They would rather have
`math.sqrt(-1)` raise an exception than return a complex number.
Also note that the functions defined in cmath always return a
complex number, even if the answer can be expressed as a real number
(in which case the complex number has an imaginary part of zero).
A note on branch cuts: They are curves along which the given function
fails to be continuous. They are a necessary feature of many complex
functions. It is assumed that if you need to compute with complex
functions, you will understand about branch cuts. Consult almost any
(not too elementary) book on complex variables for enlightenment. For
information of the proper choice of branch cuts for numerical
purposes, a good reference should be the following:


module-calendar.html | misc.html | Cmd-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5.14 cmd --
Support for line-oriented command interpreters
The Cmd class provides a simple framework for writing
line-oriented command interpreters. These are often useful for
test harnesses, administrative tools, and prototypes that will
later be wrapped in a more sophisticated interface.


3.22 code -- Interpreter base classes

examples-imp.html | python.html | interpreter-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.22 code --
Interpreter base classes
The `code` module provides facilities to implement
read-eval-print loops in Python. Two classes and convenience
functions are included which can be used to build applications which
provide an interactive interpreter prompt.


module-cStringIO.html | strings.html | node113.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 4.8 codecs --
Codec registry and base classes
This module defines base classes for standard Python codecs (encoders
and decoders) and provides access to the internal Python codec
registry which manages the codec lookup process.
It defines the following functions:
To simply access to the various codecs, the module provides these
additional functions which use lookup() for the codec
lookup:
To simplify working with encoded files or stream, the module
also defines these utility functions:
The module also provides the following constants which are useful
for reading and writing to platform dependent files:
See Also:


3.23 codeop -- Compile Python code

console-objects.html | python.html | module-pprint.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.23 codeop --
Compile Python code
The codeop module provides utilities upon which the Python
read-eval-print loop can be emulated, as is done in the
code (module-code.html) module. As a result, you probably don't want to use
the module directly; if you want to include such a loop in your
program you probably want to use the code (module-code.html) module instead.
There are two parts to this job:
1. Being able to tell if a line of input completes a Python
statement: in short, telling whether to print
``> > >` or ``...`' next.
2. Remembering which future statements the user has entered, so
subsequent input can be compiled with these in effect.
The codeop module provides a way of doing each of these
things, and a way of doing them both.
To do just the former:
A note on version compatibility: the Compile and
CommandCompiler are new in Python 2.2. If you want to enable
the future-tracking features of 2.2 but also retain compatibility with
2.1 and earlier versions of Python you can either write
```text

try:
from codeop import CommandCompiler
compile_command = CommandCompiler()
del CommandCompiler
except ImportError:
from codeop import compile_command
```
which is a low-impact change, but introduces possibly unwanted global
state into your program, or you can write:
```text

try:
from codeop import CommandCompiler
except ImportError:
def CommandCompiler():
from codeop import compile_command
return compile_comamnd
```


module-chunk.html | mmedia.html | module-rgbimg.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 14.7 colorsys --
Conversions between color systems
The colorsys module defines bidirectional conversions of
color values between colors expressed in the RGB (Red Green Blue)
color space used in computer monitors and three other coordinate
systems: YIQ, HLS (Hue Lightness Saturation) and HSV (Hue Saturation
Value). Coordinates in all of these color spaces are floating point
values. In the YIQ space, the Y coordinate is between 0 and 1, but
the I and Q coordinates can be positive or negative. In all other
spaces, the coordinates are all between 0 and 1.
More information about color spaces can be found at
http://www.inforamp.net/%7epoynton/ColorFAQ.html.
The colorsys module defines the following functions:
Example:


module-syslog.html | unix.html | module-pdb.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 8.18 commands --
Utilities for running commands
Availability: Unix.
The commands module contains wrapper functions for
os.popen() which take a system command as a string and
return any output generated by the command and, optionally, the exit
status.
The commands module defines the following functions:
Example:
```text

>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
```


module-pycompile.html | language.html | module-dis.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 18.9 compileall --
Byte-compile Python libraries
This module provides some utility functions to support installing
Python libraries. These functions compile Python source files in a
directory tree, allowing users without permission to write to the
libraries to take advantage of cached byte-code files.
The source file for this module may also be used as a script to
compile Python sources in directories named on the command line or in
`sys.path`.


19.3.1 AST Nodes

node574.html | node574.html | node576.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 19.3.1 AST Nodes
The compiler.ast module is generated from a text file that
describes each node type and its elements. Each node type is
represented as a class that inherits from the abstract base class
compiler.ast.Node and defines a set of named attributes for
child nodes.
All Node objects offer the following methods:
Two examples illustrate the general structure of Node
classes. The while statement is defined by the following
grammar production:
```text

while_stmt: "while" expression ":" suite
["else" ":" suite]
```
The While node has three attributes: test,
body, and else_. (If the natural name for an
attribute is also a Python reserved word, it can't be used as an
attribute name. An underscore is appended to the word to make it a
legal identifier, hence else_ instead of else.)
The if statement is more complicated because it can include
several tests.
```text

if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
```
The If node only defines two attributes: tests and
else_. The tests attribute is a sequence of test
expression, consequent body pairs. There is one pair for each
if/elif clause. The first element of the pair is
the test expression. The second elements is a Stmt node that
contains the code to execute if the test is true.
The getChildren() method of If returns a flat list of
child nodes. If there are three if/elif clauses
and no else clause, then getChildren() will return
a list of six elements: the first test expression, the first
Stmt, the second text expression, etc.
The following table lists each of the Node subclasses defined
in compiler.ast and each of the public attributes available
on their instances. The values of most of the attributes are
themselves Node instances or sequences of instances. When the
value is something other than an instance, the type is noted in the
comment. The attributes are listed in the order in which they are
returned by getChildren() and getChildNodes().


19.1 The basic interface

compiler.html | compiler.html | node573.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 19.1 The basic interface
The top-level of the package defines four functions. If you import
compiler, you will get these functions and a collection of
modules contained in the package.
The compiler package contains the following modules:
ast (module-compiler.ast.html), consts, future,
misc, pyassem, pycodegen, symbols,
transformer, and visitor (module-compiler.visitor.html).


19.4 Using Visitors to Walk ASTs

node577.html | compiler.html | node579.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 19.4 Using Visitors to Walk ASTs
The visitor pattern is ... The compiler (module-compiler.html) package uses a
variant on the visitor pattern that takes advantage of Python's
introspection features to elminiate the need for much of the visitor's
infrastructure.
The classes being visited do not need to be programmed to accept
visitors. The visitor need only define visit methods for classes it
is specifically interested in; a default visit method can handle the
rest.
XXX The magic visit() method for visitors.
ASTVisitor objects have the following methods:
XXX describe extra arguments


module-array.html | misc.html | ConfigParser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5.10 ConfigParser --
Configuration file parser
This module defines the class ConfigParser.
The ConfigParser class implements a basic configuration file
parser language which provides a structure similar to what you would
find on Microsoft Windows INI files. You can use this to write Python
programs which can be customized by end users easily.
The configuration file consists of sections, lead by a
"[section]" header and followed by "name: value" entries,
with continuations in the style of RFC 822 (http://www.faqs.org/rfcs/rfc822.html); "name=value" is
also accepted. Note that leading whitespace is removed from values.
The optional values can contain format strings which refer to other
values in the same section, or values in a special
`DEFAULT` section. Additional defaults can be provided upon
initialization and retrieval. Lines beginning with "#" or
";" are ignored and may be used to provide comments.
For example:
```text

foodir: %(dir)s/whatever
dir=frob
```
would resolve the "%(dir)s" to the value of
"dir" ("frob" in this case). All reference expansions are
done on demand.
Default values can be specified by passing them into the
ConfigParser constructor as a dictionary. Additional defaults
may be passed into the get() method which will override all
others.
See Also:


11.19 Cookie -- HTTP state management

module-CGIHTTPServer.html | internet.html | cookie-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.19 Cookie --
HTTP state management
The Cookie module defines classes for abstracting the concept of
cookies, an HTTP state management mechanism. It supports both simple
string-only cookies, and provides an abstraction for having any serializable
data-type as cookie value.
The module formerly strictly applied the parsing rules described in in
the RFC 2109 (http://www.faqs.org/rfcs/rfc2109.html) and RFC 2068 (http://www.faqs.org/rfcs/rfc2068.html) specifications. It has since been discovered
that MSIE 3.0x doesn't follow the character rules outlined in those
specs. As a result, the parsing rules used are a bit less strict.
A further security note is warranted. For backwards compatibility,
the Cookie module exports a class named Cookie which
is just an alias for SmartCookie. This is probably a mistake
and will likely be removed in a future version. You should not use
the Cookie class in your applications, for the same reason why
you should not use the SerialCookie class.
See Also:


module-shelve.html | python.html | module-marshal.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.18 copy --
Shallow and deep copy operations
This module provides generic (shallow and deep) copying operations.
Interface summary:
```text

import copy

x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
```
For module specific errors, copy.error is raised.
The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or
class instances):
- A shallow copy constructs a new compound object and then (to the
extent possible) inserts references into it to the objects found
in the original.
- A deep copy constructs a new compound object and then,
recursively, inserts copies into it of the objects found in the
original.
Two problems often exist with deep copy operations that don't exist
with shallow copy operations:
- Recursive objects (compound objects that, directly or indirectly,
contain a reference to themselves) may cause a recursive loop.
- Because deep copy copies everything it may copy too much,
e.g., administrative data structures that should be shared even
between copies.
The deepcopy() function avoids these problems by:
- keeping a ``memo'' dictionary of objects already copied during the current
copying pass; and
- letting user-defined classes override the copying operation or the
set of components copied.
This version does not copy types like module, class, function, method,
stack trace, stack frame, file, socket, window, array, or any similar
types.
Classes can use the same interfaces to control copying that they use
to control pickling: they can define methods called
__getinitargs__(), __getstate__() and
__setstate__(). See the description of module
pickle (module-pickle.html)for information on these
methods. The copy module does not use the
copy_reg (module-copyreg.html) registration module.
In order for a class to define its own copy implementation, it can
define special methods __copy__() and
__deepcopy__(). The former is called to implement the
shallow copy operation; no additional arguments are passed. The
latter is called to implement the deep copy operation; it is passed
one argument, the memo dictionary. If the __deepcopy__()
implementation needs to make a deep copy of a component, it should
call the deepcopy() function with the component as first
argument and the memo dictionary as second argument.


module-cPickle.html | python.html | module-shelve.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.16 copy_reg --
Register pickle support functions
The copy_reg module provides support for the
pickle (module-pickle.html)and
cPickle (module-cPickle.html)modules. The
copy (module-copy.html)module is likely to use this in the
future as well. It provides configuration information about object
constructors which are not classes. Such constructors may be factory
functions or class instances.


3.15 cPickle -- A faster pickle

pickle-example.html | python.html | module-copyreg.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.15 cPickle -- A faster pickle
The cPickle module supports serialization and
de-serialization of Python objects, providing an interface and
functionality nearly identical to the
pickle (module-pickle.html)module. There are several
differences, the most important being performance and subclassability.
First, cPickle can be up to 1000 times faster than
pickle because the former is implemented in C. Second, in
the cPickle module the callables Pickler() and
Unpickler() are functions, not classes. This means that
you cannot use them to derive custom pickling and unpickling
subclasses. Most applications have no need for this functionality and
should benefit from the greatly improved performance of the
cPickle module.
The pickle data stream produced by pickle and
cPickle are identical, so it is possible to use
pickle and cPickle interchangeably with existing
pickles3.13 (#foot6907).
There are additional minor differences in API between cPickle
and pickle, however for most applications, they are
interchangable. More documentation is provided in the
pickle module documentation, which
includes a list of the documented differences.


module-grp.html | unix.html | module-dl.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 8.4 crypt --
Function to check Unix passwords
Availability: Unix.
This module implements an interface to the
crypt(3)routine, which is a one-way hash
function based upon a modified DESalgorithm; see
the Unix man page for further details. Possible uses include
allowing Python scripts to accept typed passwords from the user, or
attempting to crack Unix passwords with a dictionary.
A simple example illustrating typical use:


module-StringIO.html | strings.html | module-codecs.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 4.7 cStringIO --
Faster version of StringIO
The module cStringIO provides an interface similar to that of
the StringIO (module-StringIO.html) module. Heavy use of StringIO.StringIO
objects can be made more efficient by using the function
StringIO() from this module instead.
Since this module provides a factory function which returns objects of
built-in types, there's no way to build your own version using
subclassing. Use the original StringIO (module-StringIO.html) module in that case.
Unlike the memory files implemented by the StringIO (module-StringIO.html)
module, those provided by this module are not able to accept Unicode
strings that cannot be encoded as plain ASCII strings.
The following data objects are provided as well:


module-curses.wrapper.html | allos.html | module-curses.panel.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.16 curses.ascii --
Utilities for ASCII characters
New in version 1.6.
The curses.ascii module supplies name constants for
ASCII characters and functions to test membership in various
ASCII character classes. The constants supplied are names for
control characters as follows:
Note that many of these have little practical significance in modern
usage. The mnemonics derive from teleprinter conventions that predate
digital computers.
The module supplies the following functions, patterned on those in the
standard C library:
These functions accept either integers or strings; when the argument
is a string, it is first converted using the built-in function
ord().
Note that all these functions check ordinal bit values derived from the
first character of the string you pass in; they do not actually know
anything about the host machine's character encoding. For functions
that know about the character encoding (and handle
internationalization properly) see the string (module-string.html) module.
The following two functions take either a single-character string or
integer byte value; they return a value of the same type.
The following function takes either a single-character string or
integer value; it returns a string.


module-getpass.html | allos.html | curses-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.13 curses --
Terminal handling for character-cell displays
Changed in version 1.6:
Added support for the `ncurses` library and
converted to a package.
The curses module provides an interface to the curses
library, the de-facto standard for portable advanced terminal
handling.
While curses is most widely used in the Unix environment, versions
are available for DOS, OS/2, and possibly other systems as well. This
extension module is designed to match the API of ncurses, an
open-source curses library hosted on Linux and the BSD variants of
Unix.
See Also:
The Demo/curses/ directory in the Python source
distribution contains some example programs using the
curses bindings provided by this module.


module-curses.ascii.html | allos.html | cursespanel-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.17 curses.panel --
A panel stack extension for curses.
Panels are windows with the added feature of depth, so they can be
stacked on top of each other, and only the visible portions of
each window will be displayed. Panels can be added, moved up
or down in the stack, and removed.


node181.html | allos.html | curses-textpad-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.14 curses.textpad --
Text input widget for curses programs
New in version 1.6.
The curses.textpad module provides a Textbox class
that handles elementary text editing in a curses window, supporting a
set of keybindings resembling those of Emacs (thus, also of Netscape
Navigator, BBedit 6.x, FrameMaker, and many other programs). The
module also provides a rectangle-drawing function useful for framing
text boxes or for other purposes.
The module curses.textpad defines the following function:


curses-textpad-objects.html | allos.html | module-curses.ascii.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.15 curses.wrapper --
Terminal handler for curses programs
New in version 1.6.
This module supplies one function, wrapper(), which runs
another function which should be the rest of your curses-using
application. If the application raises an exception,
wrapper() will restore the terminal to a sane state before
passing it further up the stack and generating a traceback.


module-dumbdbm.html | someos.html | dbhash-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.10 dbhash --
DBM-style interface to the BSD database library
Availability: Unix, Windows.
The dbhash module provides a function to open databases using
the BSD `db` library. This module mirrors the interface of the
other Python database modules that provide access to DBM-style
databases. The bsddb (module-bsddb.html)module is required
to use dbhash.
This module provides an exception and a function:
See Also:


dl-objects.html | unix.html | module-gdbm.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 8.6 dbm --
Simple ``database'' interface
Availability: Unix.
The dbm module provides an interface to the Unix
(`n`)`dbm` library. Dbm objects behave like mappings
(dictionaries), except that keys and values are always strings.
Printing a dbm object doesn't print the keys and values, and the
items() and values() methods are not supported.
This module can be used with the ``classic'' ndbm interface, the BSD
DB compatibility interface, or the GNU GDBM compatibility interface.
On Unix, the configure script will attempt to locate the
appropriate header file to simplify building this module.
The module defines the following:


module-gl.html | sgi.html | module-gl-constants.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 20.9 DEVICE --
Constants used with the gl module
Availability: IRIX.
This modules defines the constants used by the Silicon Graphics
Graphics Library that C programmers find in the header file
`<gl/device.h>`.
Read the module source file for details.


module-struct.html | strings.html | sequence-matcher.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 4.4 difflib --
Helpers for computing deltas
New in version 2.1.
See Also:


module-os.path.html | allos.html | module-stat.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.3 dircache --
Cached directory listings
The dircache module defines a function for reading directory listing
using a cache, and cache invalidation using the mtime of the directory.
Additionally, it defines a function to annotate directories by appending
a slash.
The dircache module defines the following functions:


module-compileall.html | language.html | bytecodes.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 18.10 dis --
Disassembler for Python byte code
The dis module supports the analysis of Python byte code by
disassembling it. Since there is no Python assembler, this module
defines the Python assembly language. The Python byte code which
this module takes as an input is defined in the file
Include/opcode.h and used by the compiler and the interpreter.
Example: Given the function myfunc:
```text

def myfunc(alist):
return len(alist)
```
the following command can be used to get the disassembly of
myfunc():
```text

>>> dis.dis(myfunc)
0 SET_LINENO 1

3 SET_LINENO 2
6 LOAD_GLOBAL 0 (len)
9 LOAD_FAST 0 (alist)
12 CALL_FUNCTION 1
15 RETURN_VALUE
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
```
The dis module defines the following functions and constants:


bytecodes.html | language.html | compiler.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 18.11 distutils --
Building and installing Python modules
The distutils package provides support for building and
installing additional modules into a Python installation. The new
modules may be either 100%-pure Python, or may be extension modules
written in C, or may be collections of Python packages which include
modules coded in both Python and C.
This package is discussed in two separate documents which are included
in the Python documentation package. To learn about distributing new
modules using the distutils facilities, read
Distributing Python Modules (../dist/dist.html). To learn
about installing Python modules, whether or not the author made use of
the distutils package, read
Installing Python Modules (../inst/inst.html).
See Also:


module-crypt.html | unix.html | dl-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 8.5 dl --
Call C functions in shared objects
Availability: Unix.
The dl module defines an interface to the
dlopen() function, which is the most common interface on
Unix platforms for handling dynamically linked libraries. It allows
the program to call arbitrary functions in such a library.
Note:
This module will not work unless
`sizeof(int) == sizeof(long) == sizeof(char *)`
If this is not the case, SystemError will be raised on
import.
The dl module defines the following function:
The dl module defines the following constants:
The dl module defines the following exception:
Example:
```text

>>> import dl, time
>>> a=dl.open('/lib/libc.so.6')
>>> a.call('time'), time.time()
(929723914, 929723914.498)
```
This example was tried on a Debian GNU/Linux system, and is a good
example of the fact that using this module is usually a bad alternative.


module-pydoc.html | misc.html | node123.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5.2 doctest --
Test docstrings represent reality
The doctest module searches a module's docstrings for text that looks
like an interactive Python session, then executes all such sessions to verify
they still work exactly as shown. Here's a complete but small example:
```text

"""
This is module example.

Example supplies one function, factorial. For example,

>>> factorial(5)
120
"""

def factorial(n):
"""Return the factorial of n, an exact integer >= 0.

If the result is small enough to fit in an int, return an int.
Else return a long.

>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000L
>>> factorial(30L)
265252859812191058636308480000000L
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0

Factorials of floats are OK, but the float must be an exact integer:
>>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000L

It must also not be ridiculously large:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
```
```text

import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # e.g., 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
try:
result *= factor
except OverflowError:
result *= long(factor)
factor += 1
return result

def _test():
import doctest, example
return doctest.testmod(example)

if __name__ == "__main__":
_test()
```
If you run example.py directly from the command line, doctest works
its magic:
```text

$ python example.py
$
```
There's no output! That's normal, and it means all the examples worked.
Pass -v to the script, and doctest prints a detailed log
of what it's trying, and prints a summary at the end:
```text

$ python example.py -v
Running example.__doc__
Trying: factorial(5)
Expecting: 120
ok
0 of 1 examples failed in example.__doc__
Running example.factorial.__doc__
Trying: [factorial(n) for n in range(6)]
Expecting: [1, 1, 2, 6, 24, 120]
ok
Trying: [factorial(long(n)) for n in range(6)]
Expecting: [1, 1, 2, 6, 24, 120]
ok
Trying: factorial(30)
Expecting: 265252859812191058636308480000000L
ok
```
And so on, eventually ending with:
```text

Trying: factorial(1e100)
Expecting:
Traceback (most recent call last):
...
OverflowError: n too large
ok
0 of 8 examples failed in example.factorial.__doc__
2 items passed all tests:
1 tests in example
8 tests in example.factorial
9 tests in 2 items.
9 passed and 0 failed.
Test passed.
$
```
That's all you need to know to start making productive use of doctest! Jump
in. The docstrings in doctest.py contain detailed information about all
aspects of doctest, and we'll just cover the more important points here.


module-anydbm.html | someos.html | module-dbhash.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.9 dumbdbm --
Portable DBM implementation
A simple and slow database implemented entirely in Python. This
should only be used when no other DBM-style database is available.


12.2.5 Encoders

node383.html | module-email.html | module-email.Errors.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.2.5 Encoders
When creating Message objects from scratch, you often need to
encode the payloads for transport through compliant mail servers.
This is especially true for image/* and text/*
type messages containing binary data.
The email package provides some convenient encodings in its
Encoders module. These encoders are actually used by the
MIMEImage and MIMEText class constructors to provide default
encodings. All encoder functions take exactly one argument, the
message object to encode. They usually extract the payload, encode
it, and reset the payload to this newly encoded value. They should also
set the Content-Transfer-Encoding: header as appropriate.
Here are the encoding functions provided:


12.2.6 Exception classes

module-email.Encoders.html | module-email.html | module-email.Utils.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.2.6 Exception classes
The following exception classes are defined in the
email.Errors module:


12.2.3 Generating MIME documents

node381.html | module-email.html | node383.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.2.3 Generating MIME documents
One of the most common tasks is to generate the flat text of the email
message represented by a message object tree. You will need to do
this if you want to send your message via the smtplib (module-smtplib.html)
module or the nntplib (module-nntplib.html) module, or print the message on the
console. Taking a message object tree and producing a flat text
document is the job of the Generator class.
Again, as with the email.Parser (module-email.Parser.html) module, you aren't limited
to the functionality of the bundled generator; you could write one
from scratch yourself. However the bundled generator knows how to
generate most email in a standards-compliant way, should handle MIME
and non-MIME email messages just fine, and is designed so that the
transformation from flat text, to an object tree via the
Parser class,
and back to flat text, is idempotent (the input is identical to the
output).
Here are the public methods of the Generator class:
The other public Generator methods are:
As a convenience, see the methods Message.as_string() and
`str(aMessage)`, a.k.a. Message.__str__(), which
simplify the generation of a formatted string representation of a
message object. For more detail, see email.Message (module-email.Message.html).


writer-impls.html | netdata.html | module-email.Message.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 12.2 email --
An email and MIME handling package
New in version 2.2.
The email package is a library for managing email messages,
including MIME and other RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html)-based message documents. It
subsumes most of the functionality in several older standard modules
such as rfc822 (module-rfc822.html), mimetools (module-mimetools.html),
multifile (module-multifile.html), and other non-standard packages such as
mimecntl. It is specifically not designed to do any
sending of email messages to SMTP (RFC 2821 (http://www.faqs.org/rfcs/rfc2821.html)) servers; that is the
function of the smtplib (module-smtplib.html) module12.1 (#foot35502).
The primary distinguishing feature of the email package is
that it splits the parsing and generating of email messages from the
internal object model representation of email. Applications
using the email package deal primarily with objects; you can
add sub-objects to messages, remove sub-objects from messages,
completely re-arrange the contents, etc. There is a separate parser
and a separate generator which handles the transformation from flat
text to the object model, and then back to flat text again. There
are also handy subclasses for some common MIME object types, and a few
miscellaneous utilities that help with such common tasks as extracting
and parsing message field values, creating RFC-compliant dates, etc.
The following sections describe the functionality of the
email package. The ordering follows a progression that
should be common in applications: an email message is read as flat
text from a file or other source, the text is parsed to produce an
object model representation of the email message, this model is
manipulated, and finally the model is rendered back into
flat text.
It is perfectly feasible to create the object model out of whole cloth
-- i.e. completely from scratch. From there, a similar progression
can be taken as above.
Also included are detailed specifications of all the classes and
modules that the email package provides, the exception
classes you might encounter while using the email package,
some auxiliary utilities, and a few examples. For users of the older
mimelib package, from which the email package is
descended, a section on differences and porting is provided.
See Also:
---
#### Footnotes


12.2.8 Iterators

module-email.Utils.html | module-email.html | node388.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.2.8 Iterators
Iterating over a message object tree is fairly easy with the
Message.walk() method. The email.Iterators module
provides some useful higher level iterations over message object
trees.


12.2.1 Representing an email message

module-email.html | module-email.html | module-email.Parser.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.2.1 Representing an email message
The central class in the email package is the
Message class; it is the base class for the email
object model. Message provides the core functionality for
setting and querying header fields, and for accessing message bodies.
Conceptually, a Message object consists of headers and
payloads. Headers are RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) style field names and
values where the field name and value are separated by a colon. The
colon is not part of either the field name or the field value.
Headers are stored and returned in case-preserving form but are
matched case-insensitively. There may also be a single
Unix-From header, also known as the envelope header or the
`From_` header. The payload is either a string in the case of
simple message objects, a list of Message objects for
multipart MIME documents, or a single Message instance for
message/rfc822 type objects.
Message objects provide a mapping style interface for
accessing the message headers, and an explicit interface for accessing
both the headers and the payload. It provides convenience methods for
generating a flat text representation of the message object tree, for
accessing commonly used header parameters, and for recursively walking
over the object tree.
Here are the methods of the Message class:
The following methods implement a mapping-like interface for accessing
the message object's RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) headers. Note that there are some
semantic differences between these methods and a normal mapping
(i.e. dictionary) interface. For example, in a dictionary there are
no duplicate keys, but here there may be duplicate message headers. Also,
in dictionaries there is no guaranteed order to the keys returned by
keys(), but in a Message object, there is an explicit
order. These semantic differences are intentional and are biased
toward maximal convenience.
Note that in all cases, any optional Unix-From header the message
may have is not included in the mapping interface.
Here are some additional useful methods:
Message objects can also optionally contain two instance
attributes, which can be used when generating the plain text of a MIME
message.


12.2.2 Parsing email messages

module-email.Message.html | module-email.html | node380.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.2.2 Parsing email messages
Message object trees can be created in one of two ways: they can be
created from whole cloth by instantiating Message objects and
stringing them together via add_payload() and
set_payload() calls, or they can be created by parsing a flat text
representation of the email message.
The email package provides a standard parser that understands
most email document structures, including MIME documents. You can
pass the parser a string or a file object, and the parser will return
to you the root Message instance of the object tree. For
simple, non-MIME messages the payload of this root object will likely
be a string containing the text of the message. For MIME
messages, the root object will return true from its
is_multipart() method, and the subparts can be accessed via
the get_payload() and walk() methods.
Note that the parser can be extended in limited ways, and of course
you can implement your own parser completely from scratch. There is
no magical connection between the email package's bundled
parser and the Message class, so your custom parser can create
message object trees in any way it find necessary.
The primary parser class is Parser which parses both the
headers and the payload of the message. In the case of
multipart messages, it will recursively parse the body of
the container message. The email.Parser module also provides
a second class, called HeaderParser which can be used if
you're only interested in the headers of the message.
HeaderParser can be much faster in this situations, since it
does not attempt to parse the message body, instead setting the
payload to the raw body as a string. HeaderParser has the
same API as the Parser class.


12.2.7 Miscellaneous utilities

module-email.Errors.html | module-email.html | module-email.Iterators.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.2.7 Miscellaneous utilities
There are several useful utilities provided with the email
package.


module-tempfile.html | allos.html | module-glob.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.20 errno --
Standard errno system symbols
This module makes available standard `errno` system symbols.
The value of each symbol is the corresponding integer value.
The names and descriptions are borrowed from linux/include/errno.h,
which should be pretty all-inclusive.
To translate a numeric error code to an error message, use
os.strerror().
Of the following list, symbols that are not used on the current
platform are not defined by the module. The specific list of defined
symbols is available as `errno.errorcode.keys()`. Symbols
available can include:


2.3 Built-in Exceptions

specialattrs.html | builtin.html | python.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 2.3 Built-in Exceptions
Exceptions can be class objects or string objects. Though most
exceptions have been string objects in past versions of Python, in
Python 1.5 and newer versions, all standard exceptions have been
converted to class objects, and users are encouraged to do the same.
The exceptions are defined in the module exceptions. This
module never needs to be imported explicitly: the exceptions are
provided in the built-in namespace as well as the exceptions
module.
Two distinct string objects with the same value are considered different
exceptions. This is done to force programmers to use exception names
rather than their string value when specifying exception handlers.
The string value of all built-in exceptions is their name, but this is
not a requirement for user-defined exceptions or exceptions defined by
library modules.
For class exceptions, in a trystatement with
an exceptclause that mentions a particular
class, that clause also handles any exception classes derived from
that class (but not exception classes from which it is
derived). Two exception classes that are not related via subclassing
are never equivalent, even if they have the same name.
The built-in exceptions listed below can be generated by the
interpreter or built-in functions. Except where mentioned, they have
an ``associated value'' indicating the detailed cause of the error.
This may be a string or a tuple containing several items of
information (e.g., an error code and a string explaining the code).
The associated value is the second argument to the
raisestatement. For string exceptions, the
associated value itself will be stored in the variable named as the
second argument of the except clause (if any). For class
exceptions, that variable receives the exception instance. If the
exception class is derived from the standard root class
Exception, the associated value is present as the
exception instance's args attribute, and possibly on other
attributes as well.
User code can raise built-in exceptions. This can be used to test an
exception handler or to report an error condition ``just like'' the
situation in which the interpreter raises the same exception; but
beware that there is nothing to prevent user code from raising an
inappropriate error.
The built-in exception classes can be sub-classed to define new
exceptions; programmers are encouraged to at least derive new
exceptions from the Exception base class. More
information on defining exceptions is available in the
Python Tutorial (../tut/tut.html) under the heading
``User-defined Exceptions.''
The following exceptions are only used as base classes for other
exceptions.
The following exceptions are the exceptions that are actually raised.
The following exceptions are used as warning categories; see the
warnings module for more information.


module-pty.html | unix.html | module-pipes.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 8.12 fcntl --
The fcntl() and ioctl() system calls
Availability: Unix.
This module performs file control and I/O control on file descriptors.
It is an interface to the fcntl() and ioctl()
Unix routines.
All functions in this module take a file descriptor fd as their
first argument. This can be an integer file descriptor, such as
returned by `sys.stdin.fileno()`, or a file object, such as
`sys.stdin` itself, which provides a fileno() which
returns a genuine file descriptor.
The module defines the following functions:
Examples (all on a SVR4 compliant system):
```text

import struct, fcntl

file = open(...)
rv = fcntl(file, fcntl.F_SETFL, os.O_NDELAY)

lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
rv = fcntl.fcntl(file, fcntl.F_SETLKW, lockdata)
```


module-statvfs.html | allos.html | dircmp-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.7 filecmp --
File and Directory Comparisons
The filecmp module defines functions to compare files and
directories, with various optional time/correctness trade-offs.
The filecmp module defines the following functions:
Example:
```text

>>> import filecmp
>>> filecmp.cmp('libundoc.tex', 'libundoc.tex')
1
>>> filecmp.cmp('libundoc.tex', 'lib.tex')
0
```