module-urlparse.html | internet.html | module-BaseHTTPServer.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.14 urlparse (module-urlparse.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.16 BaseHTTPServer (module-BaseHTTPServer.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.
When inheriting from ThreadingMixIn for threaded connection
behavior, you should explicitly declare how you want your threads
to behave on an abrupt shutdown. The ThreadingMixIn class
defines an attribute daemon_threads, which indicates whether
or not the server should wait for thread termination. You should
set the flag explicitly if you would like threads to behave
autonomously; the default is False, meaning that Python
will not exit until all threads created by ThreadingMixIn have
exited.
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
Previous:
6.3 dircache (module-dircache.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.5 statcache (module-statcache.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
Previous:
6.4 stat (module-stat.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.6 statvfs (module-statvfs.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
Previous:
6.5 statcache (module-statcache.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.7 filecmp (module-filecmp.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
Previous:
4. String Services (strings.html)
Up:
4. String Services (strings.html)
Next:
4.2 re (module-re.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
Previous:
4.5 fpformat (module-fpformat.html)
Up:
4. String Services (strings.html)
Next:
4.7 cStringIO (module-cStringIO.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:


module-unicodedata.html | strings.html | misc.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.10 unicodedata (module-unicodedata.html)
Up:
4. String Services (strings.html)
Next:
5. Miscellaneous Services (misc.html)
---
# 4.11 stringprep --
Internet String Preparation
When identifying things (such as host names) in the internet, it is
often necessary to compare such identifications for
``equality''. Exactly how this comparison is executed may depend on
the application domain, e.g. whether it should be case-insensitive or
not. It may be also necessary to restrict the possible
identifications, to allow only identifications consisting of
``printable'' characters.
RFC 3454 (http://www.faqs.org/rfcs/rfc3454.html) defines a procedure for ``preparing'' Unicode strings in
internet protocols. Before passing strings onto the wire, they are
processed with the preparation procedure, after which they have a
certain normalized form. The RFC defines a set of tables, which can be
combined into profiles. Each profile must define which tables it uses,
and what other optional parts of the `stringprep` procedure are
part of the profile. One example of a `stringprep` profile is
`nameprep`, which is used for internationalized domain names.
The module stringprep only exposes the tables from RFC
3454. As these tables would be very large to represent them as
dictionaries or lists, the module uses the Unicode character database
internally. The module source code itself was generated using the
`mkstringprep.py` utility.
As a result, these tables are exposed as functions, not as data
structures. There are two kinds of tables in the RFC: sets and
mappings. For a set, stringprep provides the ``characteristic
function'', i.e. a function that returns true if the parameter is part
of the set. For mappings, it provides the mapping function: given the
key, it returns the associated value. Below is a list of all functions
available in the module.


node108.html | strings.html | module-difflib.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.2.6 Examples (node108.html)
Up:
4. String Services (strings.html)
Next:
4.4 difflib (module-difflib.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
Previous:
14.3 aifc (module-aifc.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.4.1 AU_read Objects (au-read-objects.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 | node735.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
21.1.1 Audio Device Objects (audio-device-objects.html)
Up:
21. SunOS Specific Services (sunos.html)
Next:
22. MS Windows Specific (node735.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
Previous:
21. SunOS Specific Services (sunos.html)
Up:
21. SunOS Specific Services (sunos.html)
Next:
21.1.1 Audio Device Objects (audio-device-objects.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:


node689.html | language.html | module-token.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
18.1.6.2 Information Discovery (node689.html)
Up:
18. Python Language Services (language.html)
Next:
18.3 token (module-token.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
Previous:
3. Python Runtime Services (python.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.2 gc (module-gc.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
Previous:
8.16 nis (module-nis.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.18 commands (module-commands.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
Previous:
18.5 tokenize (module-tokenize.html)
Up:
18. Python Language Services (language.html)
Next:
18.7 pyclbr (module-pyclbr.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.


zipinfo-objects.html | someos.html | tarfile-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.18.3 ZipInfo Objects (zipinfo-objects.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.19.1 TarFile Objects (tarfile-objects.html)
---
# 7.19 tarfile -- Read and write tar archive files
New in version 2.3.
The tarfile module makes it possible to read and create tar archives.
Some facts and figures:
- reads and writes gzip and bzip2 compressed archives.
- creates POSIX 1003.1-1990 compliant or GNU tar compatible archives.
- reads GNU tar extensions longname, longlink and
sparse.
- stores pathnames of unlimited length using GNU tar extensions.
- handles directories, regular files, hardlinks, symbolic links, fifos,
character devices and block devices and is able to acquire and
restore file information like timestamp, access permissions and owner.
- can handle tape devices.
See Also:


11.13 telnetlib -- Telnet client

SMTP-example.html | internet.html | telnet-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.12.2 SMTP Example (SMTP-example.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.13.1 Telnet Objects (telnet-objects.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 (see below), 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.
The symbolic constants for the telnet commands are: IAC, DONT, DO,
WONT, WILL, SE (Subnegotiation End), NOP (No Operation), DM (Data
Mark), BRK (Break), IP (Interrupt process), AO (Abort output), AYT
(Are You There), EC (Erase Character), EL (Erase Line), GA (Go Ahead),
SB (Subnegotiation Begin).
See Also:


optparse-extending-examples.html | allos.html | module-errno.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.20.5.4 Examples (optparse-extending-examples.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.22 errno (module-errno.html)
---
# 6.21 tempfile --
Generate temporary files and directories
This module generates temporary files and directories. It works on
all supported platforms.
In version 2.3 of Python, this module was overhauled for enhanced
security. It now provides three new functions,
NamedTemporaryFile(), mkstemp(), and
mkdtemp(), which should eliminate all remaining need to use
the insecure mktemp() function. Temporary file names created
by this module no longer contain the process ID; instead a string of
six random characters is used.
Also, all the user-callable functions now take additional arguments
which allow direct control over the location and name of temporary
files. It is no longer necessary to use the global tempdir and
template variables. To maintain backward compatibility, the
argument order is somewhat odd; it is recommended to use keyword
arguments for clarity.
The module defines the following user-callable functions:
The module uses two global variables that tell it how to construct a
temporary name. They are initialized at the first call to any of the
functions above. The caller may change them, but this is discouraged;
use the appropriate function arguments, instead.


8.8 termios -- POSIX style tty control

module-gdbm.html | unix.html | node364.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.7 gdbm (module-gdbm.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.8.1 Example (node364.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:


node364.html | unix.html | module-tty.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.8.1 Example (node364.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.10 tty (module-tty.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.


unittest-error-info.html | misc.html | module-test.testsupport.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.3.9 Getting Extended Error (unittest-error-info.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.4.1 [test.testsupport]test.test_support (module-test.testsupport.html)
---
# 5.4 test --
Regression tests package for Python
The test package contains all regression tests for Python as well as
the modules test_support and regrtest.py.
test_support is used to enhance your tests while regrtest.py
drives the testing suite.
Each module in the test package whose name starts with
`'test_'` is a testing suite for a specific module or feature.
All new tests should be written using the unittest module; using
unittest is not required but makes the tests more flexible and
maintenance of the tests easier.
Some older tests are written to use doctest and a ``traditional''
testing style; these styles of tests will not be covered.
See Also:


module-test.html | module-test.html | writing-tests.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.4 test (module-test.html)
Up:
5.4 test (module-test.html)
Next:
5.4.2 Writing Unit Tests (writing-tests.html)
---
## 5.4.1 [test.testsupport]test.test_support --
-- Utility functions for tests
The test.test_support module contains functions for assisting
with writing regression tests.
The test.test_support module defines the following exceptions:
The test_support module defines the following constants:
The test_support module defines the following functions:


module-cStringIO.html | strings.html | module-codecs.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.7 cStringIO (module-cStringIO.html)
Up:
4. String Services (strings.html)
Next:
4.9 codecs (module-codecs.html)
---
# 4.8 textwrap --
Text wrapping and filling
New in version 2.3.
The textwrap module provides two convenience functions,
wrap() and fill(), as well as
TextWrapper, the class that does all the work, and a utility function
dedent(). If you're just wrapping or filling one or two
text strings, the convenience functions should be good enough; otherwise,
you should use an instance of TextWrapper for efficiency.
Both wrap() and fill() work by creating a
TextWrapper instance and calling a single method on it. That
instance is not reused, so for applications that wrap/fill many text
strings, it will be more efficient for you to create your own
TextWrapper object.
An additional utility function, dedent(), is provided to
remove indentation from strings that have unwanted whitespace to the
left of the text.
The TextWrapper instance attributes (and keyword arguments to
the constructor) are as follows:
TextWrapper also provides two public methods, analogous to the
module-level convenience functions:


poll-objects.html | someos.html | module-threading.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.3.1 Polling Objects (poll-objects.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.5 threading (module-threading.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, Linux, SGI
IRIX, Solaris 2.x, as well as on systems that have a POSIX thread
(a.k.a. ``pthread'') implementation. For systems lacking the thread
module, the dummy_thread (module-dummythread.html) module is available.
It duplicates this module's interface and can be
used as a drop-in replacement.
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
Previous:
7.4 thread (module-thread.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.5.1 Lock Objects (lock-objects.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.
The dummy_threading (module-dummythreading.html) module is provided for
situations where threading cannot be used because
thread (module-thread.html) is missing.
This module 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.


node208.html | allos.html | module-sched.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.9.7 strftime() Behavior (node208.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.11 sched (module-sched.html)
---
# 6.10 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. Most
of the functions defined in this module call platform C library
functions with the same name. It may sometimes be helpful to consult
the platform documentation, because the semantics of these functions
varies among 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 struct_time
(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 value as returned by gmtime(),
localtime(), and strptime(), and accepted by
asctime(), mktime() and strftime(),
is a sequence of 9 integers. The return values of gmtime(),
localtime(), and strptime() also offer attribute
names for individual fields.
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 the
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 struct_time, or having elements of the wrong type, a
TypeError is raised.
Changed in version 2.2:
The time value sequence was changed from a tuple to a
struct_time, with the addition of attribute names
for the fields.
The module defines the following functions and data items:


hotshot-example.html | profile.html | node396.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
10.9.3 Example Usage (hotshot-example.html)
Up:
10. The Python Profiler (profile.html)
Next:
10.10.1 Command Line Interface (node396.html)
---
# 10.10 timeit --
Measure execution time of small code snippets
New in version 2.3.
This module provides a simple way to time small bits of Python code.
It has both command line as well as callable interfaces. It avoids a
number of common traps for measuring execution times. See also Tim
Peters' introduction to the ``Algorithms'' chapter in the
Python Cookbook, published by O'Reilly.
The module defines the following public class:


16.2 Tix -- Extension widgets for Tk

node646.html | tkinter.html | node648.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
16.1.6.9 Images (node646.html)
Up:
16. Graphical User Interfaces (tkinter.html)
Next:
16.2.1 Using Tix (node648.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 | node630.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
16. Graphical User Interfaces (tkinter.html)
Up:
16. Graphical User Interfaces (tkinter.html)
Next:
16.1.1 Tkinter Modules (node630.html)
---
# 16.1 Tkinter --
Python interface to Tcl/Tk
The Tkinter module (``Tk interface'') is the standard Python
interface to the Tk GUI toolkit. Both Tk and Tkinter are
available on most Unix platforms, as well as on Windows and
Macintosh systems. (Tk itself is not part of Python; it is maintained
at ActiveState.)
See Also:


module-symbol.html | language.html | module-keyword.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
18.2 symbol (module-symbol.html)
Up:
18. Python Language Services (language.html)
Next:
18.4 keyword (module-keyword.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
Previous:
18.4 keyword (module-keyword.html)
Up:
18. Python Language Services (language.html)
Next:
18.6 tabnanny (module-tabnanny.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
Previous:
3.11.4 The interpreter stack (inspect-stack.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.12.1 Traceback Example (traceback-example.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, such as 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` (deprecated) 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
Previous:
8.9 TERMIOS (module-TERMIOSuppercase.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.11 pty (module-pty.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
Previous:
16.3 ScrolledText (module-ScrolledText.html)
Up:
16. Graphical User Interfaces (tkinter.html)
Next:
16.4.1 Pen and RawPen (pen-rawpen-objects.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:


3.6 types -- Names for built-in types

atexit-example.html | python.html | module-UserDict.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.5.1 atexit Example (atexit-example.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.7 UserDict (module-UserDict.html)
---
# 3.6 types --
Names for built-in types
This module defines names for some object types that are used by
the standard Python interpreter, but not for the types defined by various
extension modules. Also, it does not include some of the types that
arise during processing such the `listiterator` type.
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(mylist, item):
if type(item) is IntType:
del mylist[item]
else:
mylist.remove(item)
```
Starting in Python 2.2, built-in factory functions such as
int() and str() are also names for the
corresponding types. This is now the preferred way to access
the type instead of using the types module. Accordingly,
the example above should be written as follows:
```text

def delete(mylist, item):
if isinstance(item, int):
del mylist[item]
else:
mylist.remove(item)
```
The module defines the following names:


4.10 unicodedata -- Unicode Database

module-encodings.idna.html | strings.html | module-stringprep.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.9.3 encodings.idna (module-encodings.idna.html)
Up:
4. String Services (strings.html)
Next:
4.11 stringprep (module-stringprep.html)
---
# 4.10 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.2.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.2.0 (see
http://www.unicode.org/Public/UNIDATA/UnicodeData.html). It
defines the following functions:
In addition, the module exposes the following constant:


5.3 unittest -- Unit testing framework

node140.html | misc.html | minimal-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.2.8 Soapbox (node140.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.3.1 Minimal example (minimal-example.html)
---
# 5.3 unittest --
Unit testing framework
New in version 2.1.
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 latter 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
Previous:
11.3 cgitb (module-cgitb.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.4.1 URLopener Objects (urlopener-objs.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:
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
HTTP protocol provides type information in the
reply header, which can be inspected by looking at the
Content-Type: header. For the
Gopher protocol, 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).


node415.html | internet.html | request-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.4.2 Examples (node415.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.5.1 Request Objects (request-objects.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
Previous:
11.13.2 Telnet Example (telnet-example.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.15 SocketServer (module-SocketServer.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
Previous:
3.28 site (module-site.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.30 __builtin__ (module-builtin.html)
---
# 3.29 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
Previous:
3.6 types (module-types.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.8 UserList (module-UserList.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 dict 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 module also defines a mixin defining all dictionary methods for
classes that already have a minimum mapping interface. This greatly
simplifies writing classes that need to be substitutable for
dictionaries (such as the shelve module).
The UserDict module defines the UserDict class
and DictMixin:
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
Previous:
3.7 UserDict (module-UserDict.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.9 UserString (module-UserString.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
Previous:
3.8 UserList (module-UserList.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.10 operator (module-operator.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
Previous:
12.15 quopri (module-quopri.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.17 xdrlib (module-xdrlib.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.
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
Previous:
3.19 marshal (module-marshal.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.20.1 Warning Categories (warning-categories.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
Previous:
14.4.2 AU_write Objects (au-write-objects.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.5.1 Wave_read Objects (Wave-read-objects.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
Previous:
3.2 gc (module-gc.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.3.1 Weak Reference Objects (weakref-objects.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 can
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
Previous:
11. Internet Protocols and (internet.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.1.1 Browser Controller Objects (browser-controllers.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
Previous:
7.11.1 Database Objects (dbhash-objects.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.13 bsddb (module-bsddb.html)
---
# 7.12 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
Previous:
5.7 random (module-random.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.9 bisect (module-bisect.html)
---
# 5.8 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 | node735.html | undoc.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
22.2.1 Registry Handle Objects (handle-object.html)
Up:
22. MS Windows Specific (node735.html)
Next:
A. Undocumented Modules (undoc.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
Previous:
12.16 uu (module-uu.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.17.1 Packer Objects (xdr-packer-objects.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 | node564.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.5.5 Expat error constants (expat-errors.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.6.1 Module Contents (node564.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. The mapping of
the Level 3 specification, currently only available in draft form, is
being developed by the Python XML Special Interest
Group (http://www.python.org/sigs/xml-sig/) as part of the
PyXML package (http://pyxml.sourceforge.net/). Refer to the
documentation bundled with that package for information on the current
state of DOM Level 3 support.
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 no way to access an XML
reader/parser/Document builder in an implementation-independent way.
There is also no well-defined way to access these methods without an
existing Document object. In Python, each DOM implementation
will provide a function getDOMImplementation(). DOM Level 3
adds a Load/Store specification, which defines an interface to the
reader, but this is not yet available in the Python standard library.
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
Previous:
13.6.3.2 Accessor Methods (dom-accessor-methods.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.7.1 DOM Objects (dom-objects.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.
What the parse() and parseString() functions do
is connect an XML parser with a ``DOM builder'' that can accept parse
events from any SAX parser and convert them into a DOM tree. The name
of the functions are perhaps misleading, but are easy to grasp when
learning the interfaces. The parsing of the document will be
completed before these functions return; it's simply that these
functions do not provide a parser implementation themselves.
You can also create a Document by calling a method on a ``DOM
Implementation'' object. You can get this object either by calling
the getDOMImplementation() function in the
xml.dom (module-xml.dom.html) package or the xml.dom.minidom module.
Using the implementation from the xml.dom.minidom module will
always return a Document instance from the minidom
implementation, while the version from xml.dom (module-xml.dom.html) may provide
an alternate implementation (this is likely if you have the
PyXML package (http://pyxml.sourceforge.net/) installed). Once
you have a Document, you can add child nodes to it to populate
the DOM:
```text

from xml.dom.minidom import getDOMImplementation

impl = getDOMImplementation()

newdoc = impl.createDocument(None, "some_tag", None)
top_element = newdoc.documentElement
text = newdoc.createTextNode('Some textual content.')
top_element.appendChild(text)
```
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
Previous:
13.7.3 minidom and the (minidom-and-dom.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.8.1 DOMEventStream Objects (domeventstream-objects.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
Previous:
13.4 htmlentitydefs (module-htmlentitydefs.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.5.1 XMLParser Objects (xmlparser-objects.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:
See Also:


sax-exception-objects.html | markup.html | content-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.9.1 SAXException Objects (sax-exception-objects.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.10.1 ContentHandler Objects (content-handler-objects.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
Previous:
13.8.1 DOMEventStream Objects (domeventstream-objects.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.9.1 SAXException Objects (sax-exception-objects.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,
Attributes, AttributesNS, 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
Previous:
13.10.4 ErrorHandler Objects (sax-error-handler.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.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
Previous:
13.11 xml.sax.saxutils (module-xml.sax.saxutils.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.12.1 XMLReader Objects (xmlreader-objects.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-objects.html | markup.html | xml-namespace.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.12.6 The AttributesNS Interface (attributes-ns-objects.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.13.1 XML Namespaces (xml-namespace.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
...
arguments.13.1 (module-xmllib.html#tex2html149): Actually, a number of keyword arguments are
recognized which influence the parser to accept certain non-standard
constructs. The following keyword arguments are currently
recognized. The defaults for all of these is `0` (false) except
for the last one for which the default is `1` (true).
accept_unquoted_attributes (accept certain attribute values
without requiring quotes), accept_missing_endtag_name (accept
end tags that look like `</>`), map_case (map upper case to
lower case in tags and attributes), accept_utf8 (allow UTF-8
characters in input; this is required according to the XML standard,
but Python does not as yet deal properly with these characters, so
this is not the default), translate_attribute_references (don't
attempt to translate character and entity references in attribute values).


cookie-example.html | internet.html | serverproxy-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.19.3 Example (cookie-example.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.20.1 ServerProxy Objects (serverproxy-objects.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
Previous:
5.15 fileinput (module-fileinput.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.17 calendar (module-calendar.html)
---
# 5.16 xreadlines --
Efficient iteration over a file
New in version 2.1.
Deprecated since release 2.3.
Use `for line in file` instead.
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.18 zipfile -- Work with ZIP archives

node339.html | someos.html | zipfile-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.17.3 One-shot (de)compression (node339.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.18.1 ZipFile Objects (zipfile-objects.html)
---
# 7.18 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:


dumbdbm-objects.html | someos.html | module-gzip.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.14.1 Dumbdbm Objects (dumbdbm-objects.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.16 gzip (module-gzip.html)
---
# 7.15 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
Previous:
11.19.1 Cookie Objects (cookie-objects.html)
Up:
11.19 Cookie (module-Cookie.html)
Next:
11.19.3 Example (cookie-example.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
Previous:
22.1.1 File Operations (msvcrt-files.html)
Up:
22.1 msvcrt - Useful (module-msvcrt.html)
Next:
22.1.3 Other Functions (msvcrt-other.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
Previous:
22.1 msvcrt - Useful (module-msvcrt.html)
Up:
22.1 msvcrt - Useful (module-msvcrt.html)
Next:
22.1.2 Console I/O (msvcrt-console.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
Previous:
22.1.2 Console I/O (msvcrt-console.html)
Up:
22.1 msvcrt - Useful (module-msvcrt.html)
Next:
22.2 _winreg - Windows (module--winreg.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
Previous:
12.10.1 MultiFile Objects (MultiFile-objects.html)
Up:
12.10 multifile (module-multifile.html)
Next:
12.11 rfc822 (module-rfc822.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
Previous:
12.10 multifile (module-multifile.html)
Up:
12.10 multifile (module-multifile.html)
Next:
12.10.2 MultiFile Example (multifile-example.html)
---
## 12.10.1 MultiFile Objects
A MultiFile instance has the following methods:
Finally, MultiFile instances have two public instance variables:


6.12.1 Mutex Objects

module-mutex.html | module-mutex.html | module-getpass.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.12 mutex (module-mutex.html)
Up:
6.12 mutex (module-mutex.html)
Next:
6.13 getpass (module-getpass.html)
---
## 6.12.1 Mutex Objects
mutex objects have following methods:


12. Internet Data Handling

asynchat-example.html | lib.html | module-formatter.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.24.2 asynchat Example (asynchat-example.html)
Up:
Python Library Reference (lib.html)
Next:
12.1 formatter (module-formatter.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
Previous:
12.18 netrc (module-netrc.html)
Up:
12.18 netrc (module-netrc.html)
Next:
12.19 robotparser (module-robotparser.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
Previous:
11.11 nntplib (module-nntplib.html)
Up:
11.11 nntplib (module-nntplib.html)
Next:
11.12 smtplib (module-smtplib.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.2.3 Module Contents

matching-searching.html | module-re.html | re-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.2.2 Matching vs Searching (matching-searching.html)
Up:
4.2 re (module-re.html)
Next:
4.2.4 Regular Expression Objects (re-objects.html)
---
## 4.2.3 Module Contents
The module defines the following functions and constants, and an exception:


4.2.6 Examples

match-objects.html | module-re.html | module-struct.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.2.5 Match Objects (match-objects.html)
Up:
4.2 re (module-re.html)
Next:
4.3 struct (module-struct.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
```
Avoiding recursion
If you create regular expressions that require the engine to perform a
lot of recursion, you may encounter a RuntimeError exception with
the message `maximum recursion limit` exceeded. For example,
```text

>>> import re
>>> s = 'Begin ' + 1000*'a very long string ' + 'end'
>>> re.match('Begin (\w| )*? end', s).end()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/local/lib/python2.3/sre.py", line 132, in match
return _compile(pattern, flags).match(string)
RuntimeError: maximum recursion limit exceeded
```
You can often restructure your regular expression to avoid recursion.


4.9.1 Codec Base Classes

module-codecs.html | module-codecs.html | codec-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.9 codecs (module-codecs.html)
Up:
4.9 codecs (module-codecs.html)
Next:
4.9.1.1 Codec Objects (codec-objects.html)
---
## 4.9.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:
The set of allowed values can be extended via register_error.


4.9.2 Standard Encodings

stream-recoder-objects.html | module-codecs.html | module-encodings.idna.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.9.1.5 StreamRecoder Objects (stream-recoder-objects.html)
Up:
4.9 codecs (module-codecs.html)
Next:
4.9.3 encodings.idna (module-encodings.idna.html)
---
## 4.9.2 Standard Encodings
Python comes with a number of codecs builtin, either implemented as C
functions, or with dictionaries as mapping tables. The following table
lists the codecs by name, together with a few common aliases, and the
languages for which the encoding is likely used. Neither the list of
aliases nor the list of languages is meant to be exhaustive. Notice
that spelling alternatives that only differ in case or use a hyphen
instead of an underscore are also valid aliases.
Many of the character sets support the same languages. They vary in
individual characters (e.g. whether the EURO SIGN is supported or
not), and in the assignment of characters to code positions. For the
European languages in particular, the following variants typically
exist:
- an ISO 8859 codeset
- a Microsoft Windows code page, which is typically derived from
a 8859 codeset, but replaces control characters with additional
graphic characters
- an IBM EBCDIC code page
- an IBM PC code page, which is ASCII compatible
A number of codecs are specific to Python, so their codec names have
no meaning outside Python. Some of them don't convert from Unicode
strings to byte strings, but instead use the property of the Python
codecs machinery that any bijective function with one argument can be
considered as an encoding.
For the codecs listed below, the result in the ``encoding'' direction
is always a byte string. The result of the ``decoding'' direction is
listed as operand type in the table.


5.2.1 Normal Usage

module-doctest.html | module-doctest.html | node134.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.2 doctest (module-doctest.html)
Up:
5.2 doctest (module-doctest.html)
Next:
5.2.2 Which Docstrings Are (node134.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()
```
If you want to test the module as the main module, you don't need to
pass M to testmod(); in this case, it will test the current
module.
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 standard
output, 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?

node133.html | module-doctest.html | node135.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.2.1 Normal Usage (node133.html)
Up:
5.2 doctest (module-doctest.html)
Next:
5.2.3 What's the Execution (node135.html)
---
## 5.2.2 Which Docstrings Are Examined?
See the docstrings in doctest.py for all the details. They're
unsurprising: the module docstring, and all function, class and method
docstrings are searched. Optionally, the tester can be directed to
exclude 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 the tester has been
directed to skip over private names in the rest of the module.
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 can be optionally skipped, all names reached from
`M.__test__` are searched.


5.2.3 What's the Execution Context?

node134.html | module-doctest.html | node136.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.2.2 Which Docstrings Are (node134.html)
Up:
5.2 doctest (module-doctest.html)
Next:
5.2.4 What About Exceptions? (node136.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?

node135.html | module-doctest.html | node137.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.2.3 What's the Execution (node135.html)
Up:
5.2 doctest (module-doctest.html)
Next:
5.2.5 Advanced Usage (node137.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

node136.html | module-doctest.html | node138.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.2.4 What About Exceptions? (node136.html)
Up:
5.2 doctest (module-doctest.html)
Next:
5.2.6 How are Docstring (node138.html)
---
## 5.2.5 Advanced Usage
Several module level functions are available for controlling how doctests
are run.