module-fnmatch.html | allos.html | shutil-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.23 shutil --
High-level file operations
The shutil module offers a number of high-level operations on
files and collections of files. In particular, functions are provided
which support file copying and removal.
Caveat: On MacOS, the resource fork and other metadata are
not used. For file copies, this means that resources will be lost and
file type and creator codes will not be correct.


someos.html | someos.html | node214.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.1 signal --
Set handlers for asynchronous events
This module provides mechanisms to use signal handlers in Python.
Some general rules for working with signals and their handlers:
- A handler for a particular signal, once set, remains installed until
it is explicitly reset (Python emulates the BSD style interface
regardless of the underlying implementation), with the exception of
the handler for SIGCHLD, which follows the underlying
implementation.
- There is no way to ``block'' signals temporarily from critical
sections (since this is not supported by all Unix flavors).
- Although Python signal handlers are called asynchronously as far as
the Python user is concerned, they can only occur between the
``atomic'' instructions of the Python interpreter. This means that
signals arriving during long calculations implemented purely in C
(such as regular expression matches on large bodies of text) may be
delayed for an arbitrary amount of time.
- When a signal arrives during an I/O operation, it is possible that the
I/O operation raises an exception after the signal handler returns.
This is dependent on the underlying Unix system's semantics regarding
interrupted system calls.
- Because the C signal handler always returns, it makes little sense to
catch synchronous errors like SIGFPE or SIGSEGV.
- Python installs a small number of signal handlers by default:
SIGPIPE is ignored (so write errors on pipes and sockets can be
reported as ordinary Python exceptions) and SIGINT is translated
into a KeyboardInterrupt exception. All of these can be
overridden.
- Some care must be taken if both signals and threads are used in the
same program. The fundamental thing to remember in using signals and
threads simultaneously is: always perform signal() operations
in the main thread of execution. Any thread can perform an
alarm(), getsignal(), or pause();
only the main thread can set a new signal handler, and the main thread
will be the only one to receive signals (this is enforced by the
Python signal module, even if the underlying thread
implementation supports sending signals to individual threads). This
means that signals can't be used as a means of inter-thread
communication. Use locks instead.
The variables defined in the signal module are:
The signal module defines the following functions:


module-BaseHTTPServer.html | internet.html | module-CGIHTTPServer.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.17 SimpleHTTPServer --
Simple HTTP request handler
The SimpleHTTPServer module defines a request-handler class,
interface compatible with BaseHTTPServer.BaseHTTPRequestHandler
which serves files only from a base directory.
The SimpleHTTPServer module defines the following class:
The SimpleHTTPRequestHandler defines the following member
variables:
The SimpleHTTPRequestHandler defines the following methods:


xmlrpc-client-example.html | internet.html | simple-xmlrpc-servers.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.21 SimpleXMLRPCServer --
Basic XML-RPC server
The SimpleXMLRPCServer module provides a basic server
framework for XML-RPC servers written in Python. The server object is
based on the SocketServer (module-SocketServer.html).TCPServer class,
and the request handler is based on the
BaseHTTPServer (module-BaseHTTPServer.html).BaseHTTPRequestHandler class.


module-new.html | python.html | module-user.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.27 site --
Site-specific configuration hook
This module is automatically imported during initialization.
In earlier versions of Python (up to and including 1.5a3), scripts or
modules that needed to use site-specific modules would place
"import site" somewhere near the top of their code. This is no
longer necessary.
This will append site-specific paths to the module search path.
It starts by constructing up to four directories from a head and a
tail part. For the head part, it uses `sys.prefix` and
`sys.exec_prefix`; empty heads are skipped. For
the tail part, it uses the empty string (on Macintosh or Windows) or
it uses first lib/python2.2/site-packages and then
lib/site-python (on Unix). For each of the distinct
head-tail combinations, it sees if it refers to an existing directory,
and if so, adds to `sys.path`, and also inspects the path for
configuration files.
A path configuration file is a file whose name has the form
package.pth; its contents are additional items (one
per line) to be added to `sys.path`. Non-existing items are
never added to `sys.path`, but no check is made that the item
refers to a directory (rather than a file). No item is added to
`sys.path` more than once. Blank lines and lines beginning with
`#` are skipped. Lines starting with `import` are executed.
For example, suppose `sys.prefix` and `sys.exec_prefix` are
set to /usr/local. The Python 2.2 library is then
installed in /usr/local/lib/python2.2 (where only the
first three characters of `sys.version` are used to form the
installation path name). Suppose this has a subdirectory
/usr/local/lib/python2.2/site-packages with three
subsubdirectories, foo, bar and spam, and two
path configuration files, foo.pth and bar.pth. Assume
foo.pth contains the following:
```text

# foo package configuration

foo
bar
bletch
```
and bar.pth contains:
```text

# bar package configuration

bar
```
Then the following directories are added to `sys.path`, in this
order:
```text

/usr/local/lib/python1.5/site-packages/bar
/usr/local/lib/python1.5/site-packages/foo
```
Note that bletch is omitted because it doesn't exist; the
bar directory precedes the foo directory because
bar.pth comes alphabetically before foo.pth; and
spam is omitted because it is not mentioned in either path
configuration file.
After these path manipulations, an attempt is made to import a module
named sitecustomize, which can
perform arbitrary site-specific customizations. If this import fails
with an ImportError exception, it is silently ignored.


11.12 smtplib -- SMTP protocol client

nntp-objects.html | internet.html | SMTP-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.12 smtplib --
SMTP protocol client
The smtplib module defines an SMTP client session object that
can be used to send mail to any Internet machine with an SMTP or ESMTP
listener daemon. For details of SMTP and ESMTP operation, consult
RFC 821 (http://www.faqs.org/rfcs/rfc821.html) (Simple Mail Transfer Protocol) and RFC 1869 (http://www.faqs.org/rfcs/rfc1869.html)
(SMTP Service Extensions).
A nice selection of exceptions is defined as well:
See Also:


module-imghdr.html | mmedia.html | crypto.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 14.10 sndhdr --
Determine type of sound file
The sndhdr provides utility functions which attempt to
determine the type of sound data which is in a file. When these
functions are able to determine what type of sound data is stored in a
file, they return a tuple `( type , sampling_rate , channels , frames , bits_per_sample )`. The value for
type indicates the data type and will be one of the strings
`'aifc'`, `'aiff'`, `'au'`, `'hcom'`,
`'sndr'`, `'sndt'`, `'voc'`, `'wav'`,
`'8svx'`, `'sb'`, `'ub'`, or `'ul'`. The
sampling_rate will be either the actual value or `0` if
unknown or difficult to decode. Similarly, channels will be
either the number of channels or `0` if it cannot be determined
or if the value is difficult to decode. The value for frames
will be either the number of frames or `-1`. The last item in
the tuple, bits_per_sample, will either be the sample size in
bits or `'A'` for A-LAWor `'U'` for
u-LAW.


node214.html | someos.html | socket-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.2 socket --
Low-level networking interface
This module provides access to the BSD socket interface.
It is available on all modern Unix systems, Windows, MacOS, BeOS,
OS/2, and probably additional platforms.
For an introduction to socket programming (in C), see the following
papers: An Introductory 4.3BSD Interprocess Communication
Tutorial, by Stuart Sechrest and An Advanced 4.3BSD
Interprocess Communication Tutorial, by Samuel J. Leffler et al,
both in the Unix Programmer's Manual, Supplementary Documents 1
(sections PS1:7 and PS1:8). The platform-specific reference material
for the various socket-related system calls are also a valuable source
of information on the details of socket semantics. For Unix, refer
to the manual pages; for Windows, see the WinSock (or Winsock 2)
specification.
For IPv6-ready APIs, readers may want to refer to RFC 2553 (http://www.faqs.org/rfcs/rfc2553.html) titled
Basic Socket Interface Extensions for IPv6.
The Python interface is a straightforward transliteration of the
Unix system call and library interface for sockets to Python's
object-oriented style: the socket() function returns a
socket objectwhose methods implement the
various socket system calls. Parameter types are somewhat
higher-level than in the C interface: as with read() and
write() operations on Python files, buffer allocation on
receive operations is automatic, and buffer length is implicit on send
operations.
Socket addresses are represented as follows:
A single string is used for the AF_UNIX address family.
A pair `( host , port )` is used for the
AF_INET address family, where host is a string
representing either a hostname in Internet domain notation like
`'daring.cwi.nl'` or an IPv4 address like `'100.50.200.5'`,
and port is an integral port number.
For AF_INET6 address family, a four-tuple
`( host , port , flowinfo , scopeid )` is
used, where flowinfo and scopeid represents
`sin6_flowinfo` and `sin6_scope_id` member in
struct sockaddr_in6 in C.
For socket module methods, flowinfo and scopeid
can be omitted just for backward compatibility. Note, however,
omission of scopeid can cause problems in manipulating scoped
IPv6 addresses. Other address families are currently not supported.
The address format required by a particular socket object is
automatically selected based on the address family specified when the
socket object was created.
For IPv4 addresses, two special forms are accepted instead of a host
address: the empty string represents INADDR_ANY, and the string
`'<broadcast>'` represents INADDR_BROADCAST.
The behavior is not available for IPv6 for backward compatibility,
therefore, you may want to avoid these if you intend to support IPv6 with
your Python programs.
If you use a hostname in the host portion of IPv4/v6 socket
address, the program may show a nondeterministic behavior, as Python
uses the first address returned from the DNS resolution. The socket
address will be resolved differently into an actual IPv4/v6 address,
depending on the results from DNS resolution and/or the host
configuration. For deterministic behavior use a numeric address in
host portion.
All errors raise exceptions. The normal exceptions for invalid
argument types and out-of-memory conditions can be raised; errors
related to socket or address semantics raise the error
socket.error.
Non-blocking mode is supported through the
setblocking() method.
The module socket exports the following constants and functions:
See Also:


module-urlparse.html | internet.html | module-BaseHTTPServer.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.15 SocketServer --
A framework for network servers
The SocketServer module simplifies the task of writing network
servers.
There are four basic server classes: TCPServer uses the
Internet TCP protocol, which provides for continuous streams of data
between the client and server. UDPServer uses datagrams, which
are discrete packets of information that may arrive out of order or be
lost while in transit. The more infrequently used
UnixStreamServer and UnixDatagramServer classes are
similar, but use Unix domain sockets; they're not available on
non-Unix platforms. For more details on network programming, consult
a book such as W. Richard Steven's UNIX Network Programming
or Ralph Davis's Win32 Network Programming.
These four classes process requests synchronously; each request
must be completed before the next request can be started. This isn't
suitable if each request takes a long time to complete, because it
requires a lot of computation, or because it returns a lot of data
which the client is slow to process. The solution is to create a
separate process or thread to handle each request; the
ForkingMixIn and ThreadingMixIn mix-in classes can be
used to support asynchronous behaviour.
Creating a server requires several steps. First, you must create a
request handler class by subclassing the BaseRequestHandler
class and overriding its handle() method; this method will
process incoming requests. Second, you must instantiate one of the
server classes, passing it the server's address and the request
handler class. Finally, call the handle_request() or
serve_forever() method of the server object to process one or
many requests.
Server classes have the same external methods and attributes, no
matter what network protocol they use:
The server classes support the following class variables:
There are various server methods that can be overridden by subclasses
of base server classes like TCPServer; these methods aren't
useful to external users of the server object.
The request handler class must define a new handle() method,
and can override any of the following methods. A new instance is
created for each request.


6.4 stat -- Interpreting stat() results

module-dircache.html | allos.html | module-statcache.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.4 stat --
Interpreting stat() results
The stat module defines constants and functions for
interpreting the results of os.stat(),
os.fstat() and os.lstat() (if they exist). For
complete details about the stat(), fstat() and
lstat() calls, consult the documentation for your system.
The stat module defines the following functions to test for
specific file types:
Two additional functions are defined for more general manipulation of
the file's mode:
Normally, you would use the os.path.is*() functions for
testing the type of a file; the functions here are useful when you are
doing multiple tests of the same file and wish to avoid the overhead of
the stat() system call for each test. These are also
useful when checking for information about a file that isn't handled
by os.path (module-os.path.html), like the tests for block and character
devices.
All the variables below are simply symbolic indexes into the 10-tuple
returned by os.stat(), os.fstat() or
os.lstat().
The interpretation of ``file size'' changes according to the file
type. For plain files this is the size of the file in bytes. For
FIFOs and sockets under most flavors of Unix (including Linux in
particular), the ``size'' is the number of bytes waiting to be read at
the time of the call to os.stat(), os.fstat(),
or os.lstat(); this can sometimes be useful, especially for
polling one of these special files after a non-blocking open. The
meaning of the size field for other character and block devices varies
more, depending on the implementation of the underlying system call.
Example:


module-stat.html | allos.html | module-statvfs.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.5 statcache --
An optimization of os.stat()
Deprecated since release 2.2.
Use os (module-os.html).stat() directly instead
of using the cache; the cache introduces a very high level of
fragility in applications using it and complicates application code
with the addition of cache management support.
The statcache module provides a simple optimization to
os.stat(): remembering the values of previous invocations.
The statcache module defines the following functions:
The rest of the functions are used to clear the cache, or parts of
it.
Example:


module-statcache.html | allos.html | module-filecmp.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.6 statvfs --
Constants used with os.statvfs()
The statvfs module defines constants so interpreting the result
if os.statvfs(), which returns a tuple, can be made without
remembering ``magic numbers.'' Each of the constants defined in this
module is the index of the entry in the tuple returned by
os.statvfs() that contains the specified information.


4.1 string -- Common string operations

strings.html | strings.html | module-re.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 4.1 string --
Common string operations
This module defines some constants useful for checking character
classes and some useful string functions. See the module
re (module-re.html)for string functions based on regular
expressions.
The constants defined in this module are:
Many of the functions provided by this module are also defined as
methods of string and Unicode objects; see ``String Methods'' (section
2.2.6 (string-methods.html#string-methods)) for more information on those.
The functions defined in this module are:


module-fpformat.html | strings.html | module-cStringIO.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 4.6 StringIO --
Read and write strings as files
This module implements a file-like class, StringIO,
that reads and writes a string buffer (also known as memory
files). See the description of file objects for operations (section
2.2.8 (bltin-file-objects.html#bltin-file-objects)).
The following methods of StringIO objects require special
mention:


node102.html | strings.html | module-difflib.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 4.3 struct --
Interpret strings as packed binary data
This module performs conversions between Python values and C
structs represented as Python strings. It uses format strings
(explained below) as compact descriptions of the lay-out of the C
structs and the intended conversion to/from Python values. This can
be used in handling binary data stored in files or from network
connections, among other sources.
The module defines the following exception and functions:
Format characters have the following meaning; the conversion between
C and Python values should be obvious given their types:
Notes:
(1): The "q" and "Q" conversion codes are available in
native mode only if the platform C compiler supports C long long,
or, on Windows, __int64. They are always available in standard
modes.
New in version 2.2.
A format character may be preceded by an integral repeat count. For
example, the format string `'4h'` means exactly the same as
`'hhhh'`.
Whitespace characters between formats are ignored; a count and its
format must not contain whitespace though.
For the "s" format character, the count is interpreted as the
size of the string, not a repeat count like for the other format
characters; for example, `'10s'` means a single 10-byte string, while
`'10c'` means 10 characters. For packing, the string is
truncated or padded with null bytes as appropriate to make it fit.
For unpacking, the resulting string always has exactly the specified
number of bytes. As a special case, `'0s'` means a single, empty
string (while `'0c'` means 0 characters).
The "p" format character encodes a "Pascal string", meaning
a short variable-length string stored in a fixed number of bytes.
The count is the total number of bytes stored. The first byte stored is
the length of the string, or 255, whichever is smaller. The bytes
of the string follow. If the string passed in to pack() is too
long (longer than the count minus 1), only the leading count-1 bytes of the
string are stored. If the string is shorter than count-1, it is padded
with null bytes so that exactly count bytes in all are used. Note that
for unpack(), the "p" format character consumes count
bytes, but that the string returned can never contain more than 255
characters.
For the "I", "L", "q" and "Q"
format characters, the return value is a Python long integer.
For the "P" format character, the return value is a Python
integer or long integer, depending on the size needed to hold a
pointer when it has been cast to an integer type. A NULL pointer will
always be returned as the Python integer `0`. When packing pointer-sized
values, Python integer or long integer objects may be used. For
example, the Alpha and Merced processors use 64-bit pointer values,
meaning a Python long integer will be used to hold the pointer; other
platforms use 32-bit pointers and will use a Python integer.
By default, C numbers are represented in the machine's native format
and byte order, and properly aligned by skipping pad bytes if
necessary (according to the rules used by the C compiler).
Alternatively, the first character of the format string can be used to
indicate the byte order, size and alignment of the packed data,
according to the following table:
If the first character is not one of these, "@" is assumed.
Native byte order is big-endian or little-endian, depending on the
host system. For example, Motorola and Sun processors are big-endian;
Intel and DEC processors are little-endian.
Native size and alignment are determined using the C compiler's
sizeof expression. This is always combined with native byte
order.
Standard size and alignment are as follows: no alignment is required
for any type (so you have to use pad bytes);
short is 2 bytes;
int and long are 4 bytes;
long long (__int64 on Windows) is 8 bytes;
float and double are 32-bit and 64-bit
IEEE floating point numbers, respectively.
Note the difference between "@" and "=": both use
native byte order, but the size and alignment of the latter is
standardized.
The form "!" is available for those poor souls who claim they
can't remember whether network byte order is big-endian or
little-endian.
There is no way to indicate non-native byte order (force
byte-swapping); use the appropriate choice of "<" or
">".
The "P" format character is only available for the native
byte ordering (selected as the default or with the "@" byte
order character). The byte order character "=" chooses to
use little- or big-endian ordering based on the host system. The
struct module does not interpret this as native ordering, so the
"P" format is not available.
Examples (all using native byte order, size and alignment, on a
big-endian machine):
```text

>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')
8
```
Hint: to align the end of a structure to the alignment requirement of
a particular type, end the format with the code for that type with a
repeat count of zero. For example, the format `'llh0l'`
specifies two pad bytes at the end, assuming longs are aligned on
4-byte boundaries. This only works when native size and alignment are
in effect; standard size and alignment does not enforce any alignment.


module-aifc.html | mmedia.html | au-read-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 14.4 sunau --
Read and write Sun AU files
The sunau module provides a convenient interface to the Sun
AU sound format. Note that this module is interface-compatible with
the modules aifc (module-aifc.html) and wave (module-wave.html).
An audio file consists of a header followed by the data. The fields
of the header are:
Apart from the info field, all header fields are 4 bytes in size.
They are all 32-bit unsigned integers encoded in big-endian byte
order.
The sunau module defines the following functions:
The sunau module defines the following exception:
The sunau module defines the following data items:


audio-device-objects.html | sunos.html | node604.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 21.2 SUNAUDIODEV --
Constants used with sunaudiodev
Availability: SunOS.
This is a companion module to
sunaudiodev (module-sunaudiodev.html)which defines
useful symbolic constants like MIN_GAIN,
MAX_GAIN, SPEAKER, etc. The names of the
constants are the same names as used in the C include file
`<sun/audioio.h>`, with the leading string "AUDIO_"stripped.


sunos.html | sunos.html | audio-device-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 21.1 sunaudiodev --
Access to Sun audio hardware
Availability: SunOS.
This module allows you to access the Sun audio interface. The Sun
audio hardware is capable of recording and playing back audio data
in u-LAWformat with a sample rate of 8K per second. A
full description can be found in the audio(7I) manual page.
The module
SUNAUDIODEV (module-sunaudiodev-constants.html)
defines constants which may be used with this module.
This module defines the following variables and functions:


node558.html | language.html | module-token.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 18.2 symbol --
Constants used with Python parse trees
This module provides constants which represent the numeric values of
internal nodes of the parse tree. Unlike most Python constants, these
use lower-case names. Refer to the file Grammar/Grammar in the
Python distribution for the definitions of the names in the context of
the language grammar. The specific numeric values which the names map
to may change between Python versions.
This module also provides one additional data object:


python.html | python.html | module-gc.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.1 sys --
System-specific parameters and functions
This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
It is always available.


module-nis.html | unix.html | module-commands.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 8.17 syslog --
Unix syslog library routines
Availability: Unix.
This module provides an interface to the Unix `syslog` library
routines. Refer to the Unix manual pages for a detailed description
of the `syslog` facility.
The module defines the following functions:
The module defines the following constants:


module-tokenize.html | language.html | module-pyclbr.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 18.6 tabnanny --
Detection of ambiguous indentation
For the time being this module is intended to be called as a script.
However it is possible to import it into an IDE and use the function
check() described below.
Warning:
The API provided by this module is likely to change
in future releases; such changes may not be backward compatible.


11.13 telnetlib -- Telnet client

SMTP-example.html | internet.html | telnet-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.13 telnetlib --
Telnet client
The telnetlib module provides a Telnet class that
implements the Telnet protocol. See RFC 854 (http://www.faqs.org/rfcs/rfc854.html) for details about the
protocol. In addition, it provides symbolic constants for the protocol
characters (IAC/DONT/DO/WONT/WILL), and for the telnet options. The
symbolic names of the telnet options follow the definitions in
`arpa/telnet.h`, with the leading `TELOPT_` removed. For
symbolic names of options which are traditionally not included in
`arpa/telnet.h`, see the module source itself.
See Also:


module-getopt.html | allos.html | module-errno.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.19 tempfile --
Generate temporary file names
This module generates temporary file names. It is not Unix specific,
but it may require some help on non-Unix systems.
The module defines the following user-callable functions:
The module uses two global variables that tell it how to construct a
temporary name. The caller may assign values to them; by default they
are initialized at the first call to mktemp().


8.8 termios -- POSIX style tty control

module-gdbm.html | unix.html | node263.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 8.8 termios --
POSIX style tty control
Availability: Unix.
This module provides an interface to the POSIX calls for tty I/O
control. For a complete description of these calls, see the POSIX or
Unix manual pages. It is only available for those Unix versions
that support POSIX termios style tty I/O control (and then
only if configured at installation time).
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.
This module also defines all the constants needed to work with the
functions provided here; these have the same name as their
counterparts in C. Please refer to your system documentation for more
information on using these terminal control interfaces.
The module defines the following functions:
See Also:


node263.html | unix.html | module-tty.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 8.9 TERMIOS --
Constants used with the termios module
Availability: Unix.
Deprecated since release 2.1.
Import needed constants from termios (module-termios.html)
instead.


poll-objects.html | someos.html | module-threading.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.4 thread --
Multiple threads of control
This module provides low-level primitives for working with multiple
threads (a.k.a. light-weight processes or tasks) -- multiple
threads of control sharing their global data space. For
synchronization, simple locks (a.k.a. mutexes or binary
semaphores) are provided.
The module is optional. It is supported on Windows NT and '95, SGI
IRIX, Solaris 2.x, as well as on systems that have a POSIX thread
(a.k.a. ``pthread'') implementation.
It defines the following constant and functions:
Lock objects have the following methods:
Caveats:


module-thread.html | someos.html | lock-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.5 threading --
Higher-level threading interface
This module constructs higher-level threading interfaces on top of the
lower level thread (module-thread.html) module.
This module is safe for use with "from threading import *". It
defines the following functions and objects:
Detailed interfaces for the objects are documented below.
The design of this module is loosely based on Java's threading model.
However, where Java makes locks and condition variables basic behavior
of every object, they are separate objects in Python. Python's Thread
class supports a subset of the behavior of Java's Thread class;
currently, there are no priorities, no thread groups, and threads
cannot be destroyed, stopped, suspended, resumed, or interrupted. The
static methods of Java's Thread class, when implemented, are mapped to
module-level functions.
All of the methods described below are executed atomically.


6.9 time -- Time access and conversions

popen3-objects.html | allos.html | module-sched.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 6.9 time --
Time access and conversions
This module provides various time-related functions.
It is always available, but not all functions are available
on all platforms.
An explanation of some terminology and conventions is in order.
- The epochis the point where the time starts. On
January 1st of that year, at 0 hours, the ``time since the epoch'' is
zero. For Unix, the epoch is 1970. To find out what the epoch is,
look at `gmtime(0)`.
- The functions in this module do not handle dates and times before the
epoch or far in the future. The cut-off point in the future is
determined by the C library; for Unix, it is typically in
2038.
- Year 2000 (Y2K) issues: Python
depends on the platform's C library, which generally doesn't have year
2000 issues, since all dates and times are represented internally as
seconds since the epoch. Functions accepting a time tuple (see below)
generally require a 4-digit year. For backward compatibility, 2-digit
years are supported if the module variable `accept2dyear` is a
non-zero integer; this variable is initialized to `1` unless the
environment variable PYTHONY2K is set to a non-empty string,
in which case it is initialized to `0`. Thus, you can set
PYTHONY2K to a non-empty string in the environment to require 4-digit
years for all year input. When 2-digit years are accepted, they are
converted according to the POSIX or X/Open standard: values 69-99
are mapped to 1969-1999, and values 0-68 are mapped to 2000-2068.
Values 100-1899 are always illegal. Note that this is new as of
Python 1.5.2(a2); earlier versions, up to Python 1.5.1 and 1.5.2a1,
would add 1900 to year values below 1900.
- UTCis Coordinated Universal Time(formerly known as Greenwich Mean
Time,or GMT). The acronym UTC is not a
mistake but a compromise between English and French.
- DST is Daylight Saving Time,an adjustment
of the timezone by (usually) one hour during part of the year. DST
rules are magic (determined by local law) and can change from year to
year. The C library has a table containing the local rules (often it
is read from a system file for flexibility) and is the only source of
True Wisdom in this respect.
- The precision of the various real-time functions may be less than
suggested by the units in which their value or argument is expressed.
E.g. on most Unix systems, the clock ``ticks'' only 50 or 100 times a
second, and on the Mac, times are only accurate to whole seconds.
- On the other hand, the precision of time() and
sleep() is better than their Unix equivalents: times are
expressed as floating point numbers, time() returns the
most accurate time available (using Unix gettimeofday()
where available), and sleep() will accept a time with a
nonzero fraction (Unix select() is used to implement
this, where available).
- The time tuple as returned by gmtime(),
localtime(), and strptime(), and accepted by
asctime(), mktime() and strftime(),
is a tuple of 9 integers:
Note that unlike the C structure, the month value is a
range of 1-12, not 0-11. A year value will be handled as described
under ``Year 2000 (Y2K) issues'' above. A `-1` argument as
daylight savings flag, passed to mktime() will usually
result in the correct daylight savings state to be filled in.
When a tuple with an incorrect length is passed to a function
expecting a time tuple, or having elements of the wrong type, a
TypeError is raised.
The module defines the following functions and data items:


16.2 Tix -- Extension widgets for Tk

node515.html | tkinter.html | node517.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 16.2 Tix --
Extension widgets for Tk
The Tix (Tk Interface Extension) module provides an
additional rich set of widgets. Although the standard Tk library has
many useful widgets, they are far from complete. The Tix
library provides most of the commonly needed widgets that are missing
from standard Tk: HList, ComboBox, Control
(a.k.a. SpinBox) and an assortment of scrollable widgets. Tix
also includes many more widgets that are generally useful in a wide
range of applications: NoteBook, FileEntry,
PanedWindow, etc; there are more than 40 of them.
With all these new widgets, you can introduce new interaction
techniques into applications, creating more useful and more intuitive
user interfaces. You can design your application by choosing the most
appropriate widgets to match the special needs of your application and
users.
See Also:


tkinter.html | tkinter.html | node500.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 16.1 Tkinter --
Python interface to Tcl/Tk
The Tkinter module (``Tk interface'') is the standard Python
interface to the Tk GUI toolkit, now maintained at ActiveState. Both
Tk and Tkinter are available on most Unix platforms, as well
as on Windows and Macintosh systems.
See Also:


module-symbol.html | language.html | module-keyword.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 18.3 token --
Constants used with Python parse trees
This module provides constants which represent the numeric values of
leaf nodes of the parse tree (terminal tokens). Refer to the file
Grammar/Grammar in the Python distribution for the definitions
of the names in the context of the language grammar. The specific
numeric values which the names map to may change between Python
versions.
This module also provides one data object and some functions. The
functions mirror definitions in the Python C header files.


module-keyword.html | language.html | module-tabnanny.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 18.5 tokenize --
Tokenizer for Python source
The tokenize module provides a lexical scanner for Python
source code, implemented in Python. The scanner in this module
returns comments as tokens as well, making it useful for implementing
``pretty-printers,'' including colorizers for on-screen displays.
The primary entry point is a generator:
An older entry point is retained for backward compatibility:
All constants from the token (module-token.html) module are also exported from
tokenize, as are two additional token type values that might be
passed to the tokeneater function by tokenize():


inspect-stack.html | python.html | traceback-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.12 traceback --
Print or retrieve a stack traceback
This module provides a standard interface to extract, format and print
stack traces of Python programs. It exactly mimics the behavior of
the Python interpreter when it prints a stack trace. This is useful
when you want to print stack traces under program control, e.g. in a
``wrapper'' around the interpreter.
The module uses traceback objects -- this is the object type
that is stored in the variables `sys.exc_traceback` and
`sys.last_traceback` and returned as the third item from
sys.exc_info().
The module defines the following functions:


8.10 tty -- Terminal control functions

module-TERMIOSuppercase.html | unix.html | module-pty.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 8.10 tty --
Terminal control functions
Availability: Unix.
The tty module defines functions for putting the tty into
cbreak and raw modes.
Because it requires the termios (module-termios.html) module, it will work
only on Unix.
The tty module defines the following functions:


16.4 turtle -- Turtle graphics for Tk

module-ScrolledText.html | tkinter.html | pen-rawpen-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 16.4 turtle --
Turtle graphics for Tk
Availability: Tk.
The turtle module provides turtle graphics primitives, in both an
object-oriented and procedure-oriented ways. Because it uses Tkinter
for the underlying graphics, it needs a version of python installed with
Tk support.
The procedural interface uses a pen and a canvas which are automagically
created when any of the functions are called.
The turtle module defines the following functions:
This module also does `from math import *`, so see the
documentation for the math (module-math.html) module for additional constants
and functions useful for turtle graphics.
For examples, see the code of the demo() function.
This module defines the following classes:


atexit-example.html | python.html | module-UserDict.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.6 types --
Names for all built-in types
This module defines names for all object types that are used by the
standard Python interpreter, but not for the types defined by various
extension modules. It is safe to use "from types import *" --
the module does not export any names besides the ones listed here.
New names exported by future versions of this module will all end in
"Type".
Typical use is for functions that do different things depending on
their argument types, like the following:
```text

from types import *
def delete(list, item):
if type(item) is IntType:
del list[item]
else:
list.remove(item)
```
The module defines the following names:


4.9 unicodedata -- Unicode Database

stream-recoder-objects.html | strings.html | misc.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 4.9 unicodedata --
Unicode Database
This module provides access to the Unicode Character Database which
defines character properties for all Unicode characters. The data in
this database is based on the UnicodeData.txt file version
3.0.0 which is publically available from ftp://ftp.unicode.org/.
The module uses the same names and symbols as defined by the
UnicodeData File Format 3.0.0 (see
http://www.unicode.org/Public/UNIDATA/UnicodeData.html). It
defines the following functions:


5.3 unittest -- Unit testing framework

node130.html | misc.html | organizing-tests.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5.3 unittest --
Unit testing framework
The Python unit testing framework, often referred to as ``PyUnit,'' is
a Python language version of JUnit, by Kent Beck and Erich Gamma.
JUnit is, in turn, a Java version of Kent's Smalltalk testing
framework. Each is the de facto standard unit testing framework for
its respective language.
PyUnit supports test automation, sharing of setup and shutdown code
for tests, aggregation of tests into collections, and independence of
the tests from the reporting framework. The unittest module
provides classes that make it easy to support these qualities for a
set of tests.
To achieve this, PyUnit supports some important concepts:
The test case and test fixture concepts are supported through the
TestCase and FunctionTestCase classes; the former
should be used when creating new tests, and the later can be used when
integrating existing test code with a PyUnit-driven framework. When
building test fixtures using TestCase, the setUp()
and tearDown() methods can be overridden to provide
initialization and cleanup for the fixture. With
FunctionTestCase, existing functions can be passed to the
constructor for these purposes. When the test is run, the
fixture initialization is run first; if it succeeds, the cleanup
method is run after the test has been executed, regardless of the
outcome of the test. Each instance of the TestCase will only
be used to run a single test method, so a new fixture is created for
each test.
Test suites are implemented by the TestSuite class. This
class allows individual tests and test suites to be aggregated; when
the suite is executed, all tests added directly to the suite and in
``child'' test suites are run.
A test runner is an object that provides a single method,
run(), which accepts a TestCase or TestSuite
object as a parameter, and returns a result object. The class
TestResult is provided for use as the result object. PyUnit
provide the TextTestRunner as an example test runner which
reports test results on the standard error stream by default.
Alternate runners can be implemented for other environments (such as
graphical environments) without any need to derive from a specific
class.
See Also:


module-cgitb.html | internet.html | urlopener-objs.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.4 urllib --
Open arbitrary resources by URL
This module provides a high-level interface for fetching data across
the World Wide Web. In particular, the urlopen() function
is similar to the built-in function open(), but accepts
Universal Resource Locators (URLs) instead of filenames. Some
restrictions apply -- it can only open URLs for reading, and no seek
operations are available.
It defines the following public functions:
The public functions urlopen() and
urlretrieve() create an instance of the
FancyURLopener class and use it to perform their requested
actions. To override this functionality, programmers can create a
subclass of URLopener or FancyURLopener, then assign
that an instance of that class to the
`urllib._urlopener` variable before calling the desired function.
For example, applications may want to specify a different
User-Agent: header than URLopener defines. This
can be accomplished with the following code:
```text

class AppURLopener(urllib.FancyURLopener):
def __init__(self, *args):
self.version = "App/1.7"
urllib.FancyURLopener.__init__(self, *args)

urllib._urlopener = AppURLopener()
```
Restrictions:
- Currently, only the following protocols are supported: HTTP, (versions
0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files.
- The caching feature of urlretrieve() has been disabled
until I find the time to hack proper processing of Expiration time
headers.
- There should be a function to query whether a particular URL is in
the cache.
- For backward compatibility, if a URL appears to point to a local file
but the file can't be opened, the URL is re-interpreted using the FTP
protocol. This can sometimes cause confusing error messages.
- The urlopen() and urlretrieve() functions can
cause arbitrarily long delays while waiting for a network connection
to be set up. This means that it is difficult to build an interactive
Web client using these functions without using threads.
- The data returned by urlopen() or urlretrieve()
is the raw data returned by the server. This may be binary data
(e.g. an image), plain text or (for example) HTML. The
HTTPprotocol provides type information in the
reply header, which can be inspected by looking at the
Content-Type: header. For the
Gopherprotocol, type information is encoded
in the URL; there is currently no easy way to extract it. If the
returned data is HTML, you can use the module
htmllib (module-htmllib.html)to parse it.
- This module does not support the use of proxies which require
authentication. This may be implemented in the future.
- Although the urllib module contains (undocumented) routines
to parse and unparse URL strings, the recommended interface for URL
manipulation is in module urlparse (module-urlparse.html).


node307.html | internet.html | request-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.5 urllib2 --
extensible library for opening URLs
The urllib2 module defines functions and classes which help
in opening URLs (mostly HTTP) in a complex world -- basic and digest
authentication, redirections and more.
The urllib2 module defines the following functions:
The following exceptions are raised as appropriate:
The following classes are provided:


telnet-example.html | internet.html | module-SocketServer.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.14 urlparse --
Parse URLs into components
This module defines a standard interface to break Uniform Resource
Locator (URL) strings up in components (addressing scheme, network
location, path etc.), to combine the components back into a URL
string, and to convert a ``relative URL'' to an absolute URL given a
``base URL.''
The module has been designed to match the Internet RFC on Relative
Uniform Resource Locators (and discovered a bug in an earlier
draft!).
It defines the following functions:


module-site.html | python.html | module-builtin.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.28 user --
User-specific configuration hook
As a policy, Python doesn't run user-specified code on startup of
Python programs. (Only interactive sessions execute the script
specified in the PYTHONSTARTUP environment variable if it
exists).
However, some programs or sites may find it convenient to allow users
to have a standard customization file, which gets run when a program
requests it. This module implements such a mechanism. A program
that wishes to use the mechanism must execute the statement
```text

import user
```
The user module looks for a file .pythonrc.py in the user's
home directory and if it can be opened, executes it (using
execfile()) in its own (the
module user's) global namespace. Errors during this phase
are not caught; that's up to the program that imports the
user module, if it wishes. The home directory is assumed to
be named by the HOME environment variable; if this is not set,
the current directory is used.
The user's .pythonrc.py could conceivably test for
`sys.version` if it wishes to do different things depending on
the Python version.
A warning to users: be very conservative in what you place in your
.pythonrc.py file. Since you don't know which programs will
use it, changing the behavior of standard modules or functions is
generally not a good idea.
A suggestion for programmers who wish to use this mechanism: a simple
way to let users specify options for your package is to have them
define variables in their .pythonrc.py file that you test in
your module. For example, a module spam that has a verbosity
level can look for a variable `user.spam_verbose`, as follows:
```text

import user
try:
verbose = user.spam_verbose # user's verbosity preference
except AttributeError:
verbose = 0 # default verbosity
```
Programs with extensive customization needs are better off reading a
program-specific customization file.
Programs with security or privacy concerns should not import
this module; a user can easily break into a program by placing
arbitrary code in the .pythonrc.py file.
Modules for general use should not import this module; it may
interfere with the operation of the importing program.


module-types.html | python.html | module-UserList.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.7 UserDict --
Class wrapper for dictionary objects
Note:
This module is available for backward compatibility only. If
you are writing code that does not need to work with versions of
Python earlier than Python 2.2, please consider subclassing directly
from the built-in dictionary type.
This module defines a class that acts as a wrapper around
dictionary objects. It is a useful base class for
your own dictionary-like classes, which can inherit from
them and override existing methods or add new ones. In this way one
can add new behaviors to dictionaries.
The UserDict module defines the UserDict class:
In addition to supporting the methods and operations of mappings (see
section 2.2.7 (typesmapping.html#typesmapping)), UserDict instances provide the
following attribute:


module-UserDict.html | python.html | module-UserString.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.8 UserList --
Class wrapper for list objects
Note:
This module is available for backward compatibility only. If
you are writing code that does not need to work with versions of
Python earlier than Python 2.2, please consider subclassing directly
from the built-in list type.
This module defines a class that acts as a wrapper around
list objects. It is a useful base class for
your own list-like classes, which can inherit from
them and override existing methods or add new ones. In this way one
can add new behaviors to lists.
The UserList module defines the UserList class:
In addition to supporting the methods and operations of mutable
sequences (see section 2.2.6 (typesseq.html#typesseq)), UserList instances
provide the following attribute:
Subclassing requirements:
Subclasses of UserList are expect to offer a constructor which
can be called with either no arguments or one argument. List
operations which return a new sequence attempt to create an instance
of the actual implementation class. To do so, it assumes that the
constructor can be called with a single parameter, which is a sequence
object used as a data source.
If a derived class does not wish to comply with this requirement, all
of the special methods supported by this class will need to be
overridden; please consult the sources for information about the
methods which need to be provided in that case.
Changed in version 2.0:
Python versions 1.5.2 and 1.6 also required that the
constructor be callable with no parameters, and offer
a mutable data attribute. Earlier versions
of Python did not attempt to create instances of the
derived class.


module-UserList.html | python.html | module-operator.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.9 UserString --
Class wrapper for string objects
Note:
This UserString class from this module is available for
backward compatibility only. If you are writing code that does not
need to work with versions of Python earlier than Python 2.2, please
consider subclassing directly from the built-in str type
instead of using UserString (there is no built-in equivalent
to MutableString).
This module defines a class that acts as a wrapper around string
objects. It is a useful base class for your own string-like classes,
which can inherit from them and override existing methods or add new
ones. In this way one can add new behaviors to strings.
It should be noted that these classes are highly inefficient compared
to real string or Unicode objects; this is especially the case for
MutableString.
The UserString module defines the following classes:
In addition to supporting the methods and operations of string and
Unicode objects (see section 2.2.6 (string-methods.html#string-methods), ``String
Methods''), UserString instances provide the following
attribute:


module-quopri.html | netdata.html | module-xdrlib.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 12.16 uu --
Encode and decode uuencode files
This module encodes and decodes files in uuencode format, allowing
arbitrary binary data to be transferred over ASCII-only connections.
Wherever a file argument is expected, the methods accept a file-like
object. For backwards compatibility, a string containing a pathname
is also accepted, and the corresponding file will be opened for
reading and writing; the pathname `'-'` is understood to mean the
standard input or output. However, this interface is deprecated; it's
better for the caller to open the file itself, and be sure that, when
required, the mode is `'rb'` or `'wb'` on Windows or DOS.
This code was contributed by Lance Ellinghouse, and modified by Jack
Jansen.
The uu module defines the following functions:


3.20 warnings -- Warning control

module-marshal.html | python.html | warning-categories.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.20 warnings --
Warning control
New in version 2.1.
Warning messages are typically issued in situations where it is useful
to alert the user of some condition in a program, where that condition
(normally) doesn't warrant raising an exception and terminating the
program. For example, one might want to issue a warning when a
program uses an obsolete module.
Python programmers issue warnings by calling the warn()
function defined in this module. (C programmers use
PyErr_Warn(); see the
Python/C API Reference
Manual (../api/exceptionHandling.html) for details).
Warning messages are normally written to `sys.stderr`, but their
disposition can be changed flexibly, from ignoring all warnings to
turning them into exceptions. The disposition of warnings can vary
based on the warning category (see below), the text of the warning
message, and the source location where it is issued. Repetitions of a
particular warning for the same source location are typically
suppressed.
There are two stages in warning control: first, each time a warning is
issued, a determination is made whether a message should be issued or
not; next, if a message is to be issued, it is formatted and printed
using a user-settable hook.
The determination whether to issue a warning message is controlled by
the warning filter, which is a sequence of matching rules and actions.
Rules can be added to the filter by calling
filterwarnings() and reset to its default state by calling
resetwarnings().
The printing of warning messages is done by calling
showwarning(), which may be overidden; the default
implementation of this function formats the message by calling
formatwarning(), which is also available for use by custom
implementations.


14.5 wave -- Read and write WAV files

au-write-objects.html | mmedia.html | Wave-read-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 14.5 wave --
Read and write WAV files
The wave module provides a convenient interface to the WAV sound
format. It does not support compression/decompression, but it does support
mono/stereo.
The wave module defines the following function and exception:


3.3 weakref -- Weak references

module-gc.html | python.html | weakref-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 3.3 weakref --
Weak references
New in version 2.1.
The weakref module allows the Python programmer to create
weak references to objects.
In the discussion which follows, the term referent means the
object which is referred to by a weak reference.
XXX -- need to say more here!
Not all objects can be weakly referenced; those objects which do
include class instances, functions written in Python (but not in C),
and methods (both bound and unbound). Extension types can easily
be made to support weak references; see section 3.3.3 (weakref-extension.html#weakref-extension),
``Weak References in Extension Types,'' for more information.
See Also:


internet.html | internet.html | browser-controllers.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.1 webbrowser --
Convenient Web-browser controller
The webbrowser module provides a very high-level interface to
allow displaying Web-based documents to users. The controller objects
are easy to use and are platform-independent. Under most
circumstances, simply calling the open() function from this
module will do the right thing.
Under Unix, graphical browsers are preferred under X11, but text-mode
browsers will be used if graphical browsers are not available or an X11
display isn't available. If text-mode browsers are used, the calling
process will block until the user exits the browser.
Under Unix, if the environment variable BROWSER exists, it
is interpreted to override the platform default list of browsers, as a
colon-separated list of browsers to try in order. When the value of
a list part contains the string `%s`, then it is interpreted as
a literal browser command line to be used with the argument URL
substituted for the `%s`; if the part does not contain
`%s`, it is simply interpreted as the name of the browser to
launch.
For non-Unix platforms, or when X11 browsers are available on
Unix, the controlling process will not wait for the user to finish
with the browser, but allow the browser to maintain its own window on
the display.
The following exception is defined:
The following functions are defined:
A number of browser types are predefined. This table gives the type
names that may be passed to the get() function and the
corresponding instantiations for the controller classes, all defined
in this module.
Notes:
(1): ``Konqueror'' is the file manager for the KDE desktop environment for
UNIX, and only makes sense to use if KDE is running. Some way of
reliably detecting KDE would be nice; the KDEDIR variable is
not sufficient. Note also that the name ``kfm'' is used even when
using the konqueror command with KDE 2 -- the
implementation selects the best strategy for running Konqueror.
(2): Only on Windows platforms; requires the common
extension modules win32api and win32con.
(3): Only on MacOS platforms; requires the standard MacPython ic
module, described in the Macintosh
Library Modules (../mac/module-ic.html) manual.


dbhash-objects.html | someos.html | module-bsddb.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.11 whichdb --
Guess which DBM module created a database
The single function in this module attempts to guess which of the
several simple database modules available-dbm (module-dbm.html),
gdbm (module-gdbm.html), or dbhash (module-dbhash.html)-should be used to open a
given file.


module-random.html | misc.html | module-bisect.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5.7 whrandom --
Pseudo-random number generator
Deprecated since release 2.1.
Use random (module-random.html) instead.
Note:
This module was an implementation detail of the
random (module-random.html) module in releases of Python prior to 2.1. It is
no longer used. Please do not use this module directly; use
random (module-random.html) instead.
This module implements a Wichmann-Hill pseudo-random number generator
class that is also named whrandom. Instances of the
whrandom class conform to the Random Number Generator
interface described in section #rng-objects. They also offer the
following method, specific to the Wichmann-Hill algorithm:
When imported, the whrandom module also creates an instance of
the whrandom class, and makes the methods of that instance
available at the module level. Therefore one can write either
`N = whrandom.random()` or:
```text

generator = whrandom.whrandom()
N = generator.random()
```
Note that using separate instances of the generator leads to
independent sequences of pseudo-random numbers.


handle-object.html | node604.html | undoc.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 22.3 winsound --
Sound-playing interface for Windows
Availability: Windows.
New in version 1.5.2.
The winsound module provides access to the basic
sound-playing machinery provided by Windows platforms. It includes
two functions and several constants.


module-uu.html | netdata.html | xdr-packer-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 12.17 xdrlib --
Encode and decode XDR data
The xdrlib module supports the External Data Representation
Standard as described in RFC 1014 (http://www.faqs.org/rfcs/rfc1014.html), written by Sun Microsystems,
Inc. June 1987. It supports most of the data types described in the
RFC.
The xdrlib module defines two classes, one for packing
variables into XDR representation, and another for unpacking from XDR
representation. There are also two exception classes.
See Also:


expat-errors.html | markup.html | node437.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 13.6 xml.dom --
The Document Object Model API
New in version 2.0.
The Document Object Model, or ``DOM,'' is a cross-language API from
the World Wide Web Consortium (W3C) for accessing and modifying XML
documents. A DOM implementation presents an XML document as a tree
structure, or allows client code to build such a structure from
scratch. It then gives access to the structure through a set of
objects which provided well-known interfaces.
The DOM is extremely useful for random-access applications. SAX only
allows you a view of one bit of the document at a time. If you are
looking at one SAX element, you have no access to another. If you are
looking at a text node, you have no access to a containing element.
When you write a SAX application, you need to keep track of your
program's position in the document somewhere in your own code. SAX
does not do it for you. Also, if you need to look ahead in the XML
document, you are just out of luck.
Some applications are simply impossible in an event driven model with
no access to a tree. Of course you could build some sort of tree
yourself in SAX events, but the DOM allows you to avoid writing that
code. The DOM is a standard tree representation for XML data.
The Document Object Model is being defined by the W3C in stages, or
``levels'' in their terminology. The Python mapping of the API is
substantially based on the DOM Level 2 recommendation. Some aspects
of the API will only become available in Python 2.1, or may only be
available in particular DOM implementations.
DOM applications typically start by parsing some XML into a DOM. How
this is accomplished is not covered at all by DOM Level 1, and Level 2
provides only limited improvements. There is a
DOMImplementation object class which provides access to
Document creation methods, but these methods were only added
in DOM Level 2 and were not implemented in time for Python 2.0. There
is also no well-defined way to access these methods without an
existing Document object. For Python 2.0, consult the
documentation for each particular DOM implementation to determine the
bootstrap procedure needed to create and initialize Document
and DocumentType instances.
Once you have a DOM document object, you can access the parts of your
XML document through its properties and methods. These properties are
defined in the DOM specification; this portion of the reference manual
describes the interpretation of the specification in Python.
The specification provided by the W3C defines the DOM API for Java,
ECMAScript, and OMG IDL. The Python mapping defined here is based in
large part on the IDL version of the specification, but strict
compliance is not required (though implementations are free to support
the strict mapping from IDL). See section 13.6.3 (dom-conformance.html#dom-conformance),
``Conformance,'' for a detailed discussion of mapping requirements.
See Also:


dom-accessor-methods.html | markup.html | dom-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 13.7 xml.dom.minidom --
Lightweight DOM implementation
New in version 2.0.
xml.dom.minidom is a light-weight implementation of the
Document Object Model interface. It is intended to be
simpler than the full DOM and also significantly smaller.
DOM applications typically start by parsing some XML into a DOM. With
xml.dom.minidom, this is done through the parse functions:
```text

from xml.dom.minidom import parse, parseString

dom1 = parse('c:\\temp\\mydata.xml') # parse an XML file by name

datasource = open('c:\\temp\\mydata.xml')
dom2 = parse(datasource) # parse an open file

dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')
```
The parse function can take either a filename or an open file object.
If you have XML in a string, you can use the
parseString() function instead:
Both functions return a Document object representing the
content of the document.
You can also create a Document node merely by instantiating a
document object. Then you could add child nodes to it to populate
the DOM:
```text

from xml.dom.minidom import Document

newdoc = Document()
newel = newdoc.createElement("some_tag")
newdoc.appendChild(newel)
```
Once you have a DOM document object, you can access the parts of your
XML document through its properties and methods. These properties are
defined in the DOM specification. The main property of the document
object is the documentElement property. It gives you the
main element in the XML document: the one that holds all others. Here
is an example program:
```text

dom3 = parseString("<myxml>Some data</myxml>")
assert dom3.documentElement.tagName == "myxml"
```
When you are finished with a DOM, you should clean it up. This is
necessary because some versions of Python do not support garbage
collection of objects that refer to each other in a cycle. Until this
restriction is removed from all versions of Python, it is safest to
write your code as if cycles would not be cleaned up.
The way to clean up a DOM is to call its unlink() method:
```text

dom1.unlink()
dom2.unlink()
dom3.unlink()
```
unlink() is a xml.dom.minidom-specific extension to
the DOM API. After calling unlink() on a node, the node and
its descendents are essentially useless.
See Also:


minidom-and-dom.html | markup.html | domeventstream-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 13.8 xml.dom.pulldom --
Support for building partial DOM trees
New in version 2.0.
xml.dom.pulldom allows building only selected portions of a
Document Object Model representation of a document from SAX events.


module-htmlentitydefs.html | markup.html | xmlparser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 13.5 xml.parsers.expat --
Fast XML parsing using Expat
New in version 2.0.
The xml.parsers.expat module is a Python interface to the
Expatnon-validating XML parser.
The module provides a single extension type, xmlparser, that
represents the current state of an XML parser. After an
xmlparser object has been created, various attributes of the object
can be set to handler functions. When an XML document is then fed to
the parser, the handler functions are called for the character data
and markup in the XML document.
This module uses the pyexpatmodule to
provide access to the Expat parser. Direct use of the
pyexpat module is deprecated.
This module provides one exception and one type object:
The xml.parsers.expat module contains two functions:


sax-exception-objects.html | markup.html | content-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 13.10 xml.sax.handler --
Base classes for SAX handlers
New in version 2.0.
The SAX API defines four kinds of handlers: content handlers, DTD
handlers, error handlers, and entity resolvers. Applications normally
only need to implement those interfaces whose events they are
interested in; they can implement the interfaces in a single object or
in multiple objects. Handler implementations should inherit from the
base classes provided in the module xml.sax, so that all
methods get default implementations.
In addition to these classes, xml.sax.handler provides
symbolic constants for the feature and property names.


domeventstream-objects.html | markup.html | sax-exception-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 13.9 xml.sax --
Support for SAX2 parsers
New in version 2.0.
The xml.sax package provides a number of modules which
implement the Simple API for XML (SAX) interface for Python. The
package itself provides the SAX exceptions and the convenience
functions which will be most used by users of the SAX API.
The convenience functions are:
A typical SAX application uses three kinds of objects: readers,
handlers and input sources. ``Reader'' in this context is another
term for parser, i.e. some piece of code that reads the bytes or
characters from the input source, and produces a sequence of events.
The events then get distributed to the handler objects, i.e. the
reader invokes a method on the handler. A SAX application must
therefore obtain a reader object, create or open the input sources,
create the handlers, and connect these objects all together. As the
final step of preparation, the reader is called to parse the input.
During parsing, methods on the handler objects are called based on
structural and syntactic events from the input data.
For these objects, only the interfaces are relevant; they are normally
not instantiated by the application itself. Since Python does not have
an explicit notion of interface, they are formally introduced as
classes, but applications may use implementations which do not inherit
from the provided classes. The InputSource, Locator,
AttributesImpl, AttributesNSImpl, and
XMLReader interfaces are defined in the module
xml.sax.xmlreader (module-xml.sax.xmlreader.html). The handler interfaces are defined in
xml.sax.handler (module-xml.sax.handler.html). For convenience, InputSource
(which is often instantiated directly) and the handler classes are
also available from xml.sax. These interfaces are described
below.
In addition to these classes, xml.sax provides the following
exception classes.
See Also:


13.11 xml.sax.saxutils -- SAX Utilities

sax-error-handler.html | markup.html | module-xml.sax.xmlreader.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 13.11 xml.sax.saxutils --
SAX Utilities
New in version 2.0.
The module xml.sax.saxutils contains a number of classes and
functions that are commonly useful when creating SAX applications,
either in direct use, or as base classes.


module-xml.sax.saxutils.html | markup.html | xmlreader-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 13.12 xml.sax.xmlreader --
Interface for XML parsers
New in version 2.0.
SAX parsers implement the XMLReader interface. They are
implemented in a Python module, which must provide a function
create_parser(). This function is invoked by
xml.sax.make_parser() with no arguments to create a new
parser object.


attributes-ns-impl-objects.html | markup.html | xml-namespace.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 13.13 xmllib --
A parser for XML documents
Deprecated since release 2.0.
Use xml.sax (module-xml.sax.html) instead. The newer XML
package includes full support for XML 1.0.
Changed in version 1.5.2:
Added namespace support.
This module defines a class XMLParser which serves as the basis
for parsing text files formatted in XML (Extensible Markup Language).
This class provides the following interface methods and instance variables:
See Also:
---
#### Footnotes


cookie-example.html | internet.html | server-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 11.20 xmlrpclib -- XML-RPC client access
New in version 2.2.
XML-RPC is a Remote Procedure Call method that uses XML passed via
HTTP as a transport. With it, a client can call methods with
parameters on a remote server (the server is named by a URI) and get back
structured data. This module supports writing XML-RPC client code; it
handles all the details of translating between conformable Python
objects and XML on the wire.
See Also:


module-fileinput.html | misc.html | module-calendar.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 5.12 xreadlines --
Efficient iteration over a file
New in version 2.1.
This module defines a new object type which can efficiently iterate
over the lines of a file. An xreadlines object is a sequence type
which implements simple in-order indexing beginning at `0`, as
required by for statement or the
filter() function.
Thus, the code
```text

import xreadlines, sys

for line in xreadlines.xreadlines(sys.stdin):
pass
```
has approximately the same speed and memory consumption as
```text

while 1:
lines = sys.stdin.readlines(8*1024)
if not lines: break
for line in lines:
pass
```
except the clarity of the for statement is retained in the
former case.
An xreadlines object s supports the following sequence
operation:
If successive values of i are not sequential starting from
`0`, this code will raise RuntimeError.


7.15 zipfile -- Work with ZIP archives

module-gzip.html | someos.html | zipfile-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.15 zipfile --
Work with ZIP archives
New in version 1.6.
The ZIP file format is a common archive and compression standard.
This module provides tools to create, read, write, append, and list a
ZIP file. Any advanced use of this module will require an
understanding of the format, as defined in
PKZIP Application
Note (http://www.pkware.com/appnote.html).
This module does not currently handle ZIP files which have appended
comments, or multi-disk ZIP files.
The available attributes of this module are:
See Also:


bsddb-objects.html | someos.html | module-gzip.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 7.13 zlib --
Compression compatible with gzip
For applications that require data compression, the functions in this
module allow compression and decompression, using the zlib library.
The zlib library has its own home page at
http://www.gzip.org/zlib/. Version 1.1.3 is the
most recent version as of September 2000; use a later version if one
is available. There are known incompatibilities between the Python
module and earlier versions of the zlib library.
The available exception and functions in this module are:
Compression objects support the following methods:
Decompression objects support the following methods, and two attributes:


11.19.2 Morsel Objects

cookie-objects.html | module-Cookie.html | cookie-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.19.2 Morsel Objects


22.1.2 Console I/O

msvcrt-files.html | module-msvcrt.html | msvcrt-other.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 22.1.2 Console I/O


22.1.1 File Operations

module-msvcrt.html | module-msvcrt.html | msvcrt-console.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 22.1.1 File Operations


22.1.3 Other Functions

msvcrt-console.html | module-msvcrt.html | module--winreg.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 22.1.3 Other Functions


12.10.2 MultiFile Example

MultiFile-objects.html | module-multifile.html | module-rfc822.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.10.2 MultiFile Example


12.10.1 MultiFile Objects

module-multifile.html | module-multifile.html | multifile-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.10.1 MultiFile Objects
A MultiFile instance has the following methods:
Finally, MultiFile instances have two public instance variables:


6.11.1 Mutex Objects

module-mutex.html | module-mutex.html | module-getpass.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 6.11.1 Mutex Objects
mutex objects have following methods:


12. Internet Data Handling

asyncore-example.html | lib.html | module-formatter.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
# 12. Internet Data Handling
This chapter describes modules which support handling data formats
commonly used on the Internet.


12.18.1 netrc Objects

module-netrc.html | module-netrc.html | module-robotparser.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 12.18.1 netrc Objects
A netrc instance has the following methods:
Instances of netrc have public instance variables:


11.11.1 NNTP Objects

module-nntplib.html | module-nntplib.html | module-smtplib.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 11.11.1 NNTP Objects
NNTP instances have the following methods. The response that is
returned as the first item in the return tuple of almost all methods
is the server's response: a string beginning with a three-digit code.
If the server's response indicates an error, the method raises one of
the above exceptions.


4.8.1 Codec Base Classes

module-codecs.html | module-codecs.html | codec-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 4.8.1 Codec Base Classes
The codecs defines a set of base classes which define the
interface and can also be used to easily write you own codecs for use
in Python.
Each codec has to define four interfaces to make it usable as codec in
Python: stateless encoder, stateless decoder, stream reader and stream
writer. The stream reader and writers typically reuse the stateless
encoder/decoder to implement the file protocols.
The Codec class defines the interface for stateless
encoders/decoders.
To simplify and standardize error handling, the encode() and
decode() methods may implement different error handling
schemes by providing the errors string argument. The following
string values are defined and implemented by all standard Python
codecs:


4.2.6 Examples

match-objects.html | module-re.html | module-struct.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 4.2.6 Examples
Simulating scanf()
Python does not currently have an equivalent to scanf().
Regular expressions are generally more powerful, though also more
verbose, than scanf() format strings. The table below
offers some more-or-less equivalent mappings between
scanf() format tokens and regular expressions.
To extract the filename and numbers from a string like
```text

/usr/sbin/sendmail - 0 errors, 4 warnings
```
you would use a scanf() format like
```text

%s - %d errors, %d warnings
```
The equivalent regular expression would be
```text

([^\s]+) - (\d+) errors, (\d+) warnings
```


5.1.1 Normal Usage

module-doctest.html | module-doctest.html | node110.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.1.1 Normal Usage
In normal use, end each module M with:
```text

def _test():
import doctest, M # replace M with your module's name
return doctest.testmod(M) # ditto

if __name__ == "__main__":
_test()
```
Then running the module as a script causes the examples in the docstrings
to get executed and verified:
```text

python M.py
```
This won't display anything unless an example fails, in which case the
failing example(s) and the cause(s) of the failure(s) are printed to stdout,
and the final line of output is `'Test failed.'`.
Run it with the -v switch instead:
```text

python M.py -v
```
and a detailed report of all examples tried is printed to `stdout`,
along with assorted summaries at the end.
You can force verbose mode by passing `verbose=1` to testmod, or
prohibit it by passing `verbose=0`. In either of those cases,
`sys.argv` is not examined by testmod.
In any case, testmod returns a 2-tuple of ints `( f , t )`, where f is the number of docstring examples that
failed and t is the total number of docstring examples
attempted.


5.1.2 Which Docstrings Are Examined?

node109.html | module-doctest.html | node111.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.1.2 Which Docstrings Are Examined?
See docstring.py for all the details. They're unsurprising: the
module docstring, and all function, class and method docstrings are
searched, with the exception of docstrings attached to objects with private
names.
In addition, if `M.__test__` exists and "is true", it must be a
dict, and each entry maps a (string) name to a function object, class
object, or string. Function and class object docstrings found from
`M.__test__` are searched even if the name is private, and
strings are searched directly as if they were docstrings. In output,
a key `K` in `M.__test__` appears with name
```text

<name of M>.__test__.K
```
Any classes found are recursively searched similarly, to test docstrings in
their contained methods and nested classes. While private names reached
from M's globals are skipped, all names reached from
`M.__test__` are searched.


5.1.3 What's the Execution Context?

node110.html | module-doctest.html | node112.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.1.3 What's the Execution Context?
By default, each time testmod finds a docstring to test, it uses a
copy of M's globals, so that running tests on a module
doesn't change the module's real globals, and so that one test in
M can't leave behind crumbs that accidentally allow another test
to work. This means examples can freely use any names defined at top-level
in M, and names defined earlier in the docstring being run. It
also means that sloppy imports (see below) can cause examples in external
docstrings to use globals inappropriate for them.
You can force use of your own dict as the execution context by passing
`globs=your_dict` to testmod() instead. Presumably this
would be a copy of `M.__dict__` merged with the globals from other
imported modules.


5.1.4 What About Exceptions?

node111.html | module-doctest.html | node113.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.1.4 What About Exceptions?
No problem, as long as the only output generated by the example is the
traceback itself. For example:
```text

>>> [1, 2, 3].remove(42)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: list.remove(x): x not in list
>>>
```
Note that only the exception type and value are compared (specifically,
only the last line in the traceback). The various ``File'' lines in
between can be left out (unless they add significantly to the documentation
value of the example).


4.8.1 Codec Base Classes


node113.html | module-doctest.html | node115.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.1.6 How are Docstring Examples Recognized?
In most cases a copy-and-paste of an interactive console session works fine
-- just make sure the leading whitespace is rigidly consistent (you can mix
tabs and spaces if you're too lazy to do it right, but doctest is not in
the business of guessing what you think a tab means).
```text

>>> # comments are ignored
>>> x = 12
>>> x
12
>>> if x == 13:
... print "yes"
... else:
... print "no"
... print "NO"
... print "NO!!!"
...
no
NO
NO!!!
>>>
```
Any expected output must immediately follow the final
`'> > > '` or `'... '` line containing the code, and
the expected output (if any) extends to the next `'> > > '`
or all-whitespace line.
The fine print:
- Expected output cannot contain an all-whitespace line, since such a
line is taken to signal the end of expected output.
- Output to stdout is captured, but not output to stderr (exception
tracebacks are captured via a different means).
- If you continue a line via backslashing in an interactive session, or
for any other reason use a backslash, you need to double the backslash in
the docstring version. This is simply because you're in a string, and so
the backslash must be escaped for it to survive intact. Like:
```text

>>> if "yes" == \\
... "y" + \\
... "es":
... print 'yes'
yes
```
- The starting column doesn't matter:
```text

>>> assert "Easy!"
>>> import math
>>> math.floor(1.9)
1.0
```
and as many leading whitespace characters are stripped from the
expected output as appeared in the initial `'> > > '` line
that triggered it.


5.1.7 Warnings

node114.html | module-doctest.html | node116.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.1.7 Warnings
1. Sloppy imports can cause trouble; e.g., if you do
```text

from XYZ import XYZclass
```
then XYZclass is a name in `M.__dict__` too, and doctest
has no way to know that XYZclass wasn't defined in
M. So it may try to execute the examples in
XYZclass's docstring, and those in turn may require a
different set of globals to work correctly. I prefer to do
```import *`''-friendly imports, a la

```text
from XYZ import XYZclass as _XYZclass
```

and then the leading underscore makes _XYZclass a private name so
testmod skips it by default. Other approaches are described in
doctest.py.
2. doctest is serious about requiring exact matches in expected
output. If even a single character doesn't match, the test fails. This
will probably surprise you a few times, as you learn exactly what Python
does and doesn't guarantee about output. For example, when printing a
dict, Python doesn't guarantee that the key-value pairs will be printed
in any particular order, so a test like

```text
>>> foo()
{"Hermione": "hippogryph", "Harry": "broomstick"}
>>>
```

is vulnerable! One workaround is to do

```text
>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
1
>>>
```

instead. Another is to do

```text
>>> d = foo().items()
>>> d.sort()
>>> d
[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
```

There are others, but you get the idea.

Another bad idea is to print things that embed an object address, like

```text
>>> id(1.0) # certain to fail some of the time
7948648
>>>
```

Floating-point numbers are also subject to small output variations across
platforms, because Python defers to the platform C library for float
formatting, and C libraries vary widely in quality here.

```text
>>> 1./7 # risky
0.14285714285714285
>>> print 1./7 # safer
0.142857142857
>>> print round(1./7, 6) # much safer
0.142857
```

Numbers of the form `I/2.**J` are safe across all platforms, and I
often contrive doctest examples to produce numbers of that form:

```text
>>> 3./4 # utterly safe
0.75
```

Simple fractions are also easier for people to understand, and that makes
for better documentation.


5.1.8 Soapbox

node115.html | module-doctest.html | module-unittest.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.1.8 Soapbox
The first word in doctest is "doc", and that's why the author wrote
doctest: to keep documentation up to date. It so happens that doctest
makes a pleasant unit testing environment, but that's not its primary
purpose.
Choose docstring examples with care. There's an art to this that needs to
be learned -- it may not be natural at first. Examples should add genuine
value to the documentation. A good example can often be worth many words.
If possible, show just a few normal cases, show endcases, show interesting
subtle cases, and show an example of each kind of exception that can be
raised. You're probably testing for endcases and subtle cases anyway in an
interactive shell: doctest wants to make it as easy as possible to capture
those sessions, and will verify they continue to work as designed forever
after.
If done with care, the examples will be invaluable for your users, and will
pay back the time it takes to collect them many times over as the years go
by and "things change". I'm still amazed at how often one of my doctest
examples stops working after a "harmless" change.


5.2.1 Normal Usage

module-doctest.html | module-doctest.html | node124.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.2.1 Normal Usage
In normal use, end each module M with:
```text

def _test():
import doctest, M # replace M with your module's name
return doctest.testmod(M) # ditto

if __name__ == "__main__":
_test()
```
Then running the module as a script causes the examples in the docstrings
to get executed and verified:
```text

python M.py
```
This won't display anything unless an example fails, in which case the
failing example(s) and the cause(s) of the failure(s) are printed to stdout,
and the final line of output is `'Test failed.'`.
Run it with the -v switch instead:
```text

python M.py -v
```
and a detailed report of all examples tried is printed to `stdout`,
along with assorted summaries at the end.
You can force verbose mode by passing `verbose=1` to testmod, or
prohibit it by passing `verbose=0`. In either of those cases,
`sys.argv` is not examined by testmod.
In any case, testmod returns a 2-tuple of ints `( f , t )`, where f is the number of docstring examples that
failed and t is the total number of docstring examples
attempted.


5.2.2 Which Docstrings Are Examined?

node123.html | module-doctest.html | node125.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.2.2 Which Docstrings Are Examined?
See docstring.py for all the details. They're unsurprising: the
module docstring, and all function, class and method docstrings are
searched, with the exception of docstrings attached to objects with private
names. Objects imported into the module are not searched.
In addition, if `M.__test__` exists and "is true", it must be a
dict, and each entry maps a (string) name to a function object, class
object, or string. Function and class object docstrings found from
`M.__test__` are searched even if the name is private, and
strings are searched directly as if they were docstrings. In output,
a key `K` in `M.__test__` appears with name
```text

<name of M>.__test__.K
```
Any classes found are recursively searched similarly, to test docstrings in
their contained methods and nested classes. While private names reached
from M's globals are skipped, all names reached from
`M.__test__` are searched.


5.2.3 What's the Execution Context?

node124.html | module-doctest.html | node126.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.2.3 What's the Execution Context?
By default, each time testmod finds a docstring to test, it uses a
copy of M's globals, so that running tests on a module
doesn't change the module's real globals, and so that one test in
M can't leave behind crumbs that accidentally allow another test
to work. This means examples can freely use any names defined at top-level
in M, and names defined earlier in the docstring being run.
You can force use of your own dict as the execution context by passing
`globs=your_dict` to testmod() instead. Presumably this
would be a copy of `M.__dict__` merged with the globals from other
imported modules.


5.2.4 What About Exceptions?

node125.html | module-doctest.html | node127.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.2.4 What About Exceptions?
No problem, as long as the only output generated by the example is the
traceback itself. For example:
```text

>>> [1, 2, 3].remove(42)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: list.remove(x): x not in list
>>>
```
Note that only the exception type and value are compared (specifically,
only the last line in the traceback). The various ``File'' lines in
between can be left out (unless they add significantly to the documentation
value of the example).


5.2.5 Advanced Usage

node126.html | module-doctest.html | node128.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.2.5 Advanced Usage
testmod() actually creates a local instance of class
Tester, runs appropriate methods of that class, and merges
the results into global Tester instance `master`.
You can create your own instances of Tester, and so build your
own policies, or even run methods of `master` directly. See
`Tester.__doc__` for details.


node127.html | module-doctest.html | node129.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.2.6 How are Docstring Examples Recognized?
In most cases a copy-and-paste of an interactive console session works fine
-- just make sure the leading whitespace is rigidly consistent (you can mix
tabs and spaces if you're too lazy to do it right, but doctest is not in
the business of guessing what you think a tab means).
```text

>>> # comments are ignored
>>> x = 12
>>> x
12
>>> if x == 13:
... print "yes"
... else:
... print "no"
... print "NO"
... print "NO!!!"
...
no
NO
NO!!!
>>>
```
Any expected output must immediately follow the final
`'> > > '` or `'... '` line containing the code, and
the expected output (if any) extends to the next `'> > > '`
or all-whitespace line.
The fine print:
- Expected output cannot contain an all-whitespace line, since such a
line is taken to signal the end of expected output.
- Output to stdout is captured, but not output to stderr (exception
tracebacks are captured via a different means).
- If you continue a line via backslashing in an interactive session, or
for any other reason use a backslash, you need to double the backslash in
the docstring version. This is simply because you're in a string, and so
the backslash must be escaped for it to survive intact. Like:
```text

>>> if "yes" == \\
... "y" + \\
... "es":
... print 'yes'
yes
```
- The starting column doesn't matter:
```text

>>> assert "Easy!"
>>> import math
>>> math.floor(1.9)
1.0
```
and as many leading whitespace characters are stripped from the
expected output as appeared in the initial `'> > > '` line
that triggered it.


5.2.7 Warnings

node128.html | module-doctest.html | node130.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.2.7 Warnings
1. doctest is serious about requiring exact matches in expected
output. If even a single character doesn't match, the test fails. This
will probably surprise you a few times, as you learn exactly what Python
does and doesn't guarantee about output. For example, when printing a
dict, Python doesn't guarantee that the key-value pairs will be printed
in any particular order, so a test like
```text

>>> foo()
{"Hermione": "hippogryph", "Harry": "broomstick"}
>>>
```
is vulnerable! One workaround is to do
```text

>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
1
>>>
```
instead. Another is to do
```text

>>> d = foo().items()
>>> d.sort()
>>> d
[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
```
There are others, but you get the idea.
Another bad idea is to print things that embed an object address, like
```text

>>> id(1.0) # certain to fail some of the time
7948648
>>>
```
Floating-point numbers are also subject to small output variations across
platforms, because Python defers to the platform C library for float
formatting, and C libraries vary widely in quality here.
```text

>>> 1./7 # risky
0.14285714285714285
>>> print 1./7 # safer
0.142857142857
>>> print round(1./7, 6) # much safer
0.142857
```
Numbers of the form `I/2.**J` are safe across all platforms, and I
often contrive doctest examples to produce numbers of that form:
```text

>>> 3./4 # utterly safe
0.75
```
Simple fractions are also easier for people to understand, and that makes
for better documentation.
2. Be careful if you have code that must only execute once.
If you have module-level code that must only execute once, a more foolproof
definition of _test() is
```text

def _test():
import doctest, sys
doctest.testmod(sys.modules["__main__"])
```


5.2.8 Soapbox

node129.html | module-doctest.html | module-unittest.html | Python Library Reference | contents.html | modindex.html | genindex.html
---
## 5.2.8 Soapbox
The first word in doctest is "doc", and that's why the author wrote
doctest: to keep documentation up to date. It so happens that doctest
makes a pleasant unit testing environment, but that's not its primary
purpose.
Choose docstring examples with care. There's an art to this that needs to
be learned -- it may not be natural at first. Examples should add genuine
value to the documentation. A good example can often be worth many words.
If possible, show just a few normal cases, show endcases, show interesting
subtle cases, and show an example of each kind of exception that can be
raised. You're probably testing for endcases and subtle cases anyway in an
interactive shell: doctest wants to make it as easy as possible to capture
those sessions, and will verify they continue to work as designed forever
after.
If done with care, the examples will be invaluable for your users, and will
pay back the time it takes to collect them many times over as the years go
by and "things change". I'm still amazed at how often one of my doctest
examples stops working after a "harmless" change.