module-linecache.html | python.html | pickle-example.html | Python Library Reference | contents.html | genindex.html
---
# 3.9 pickle --
Python object serialization
The pickle module implements a basic but powerful algorithm
for ``pickling'' (a.k.a. serializing, marshalling or flattening)
nearly arbitrary Python objects. This is the act of converting
objects to a stream of bytes (and back: ``unpickling''). This is a
more primitive notion than persistency -- although pickle
reads and writes file objects, it does not handle the issue of naming
persistent objects, nor the (even more complicated) area of concurrent
access to persistent objects. The pickle module can
transform a complex object into a byte stream and it can transform the
byte stream into an object with the same internal structure. The most
obvious thing to do with these byte streams is to write them onto a
file, but it is also conceivable to send them across a network or
store them in a database. The module
shelve (module-shelve.html) provides a simple interface
to pickle and unpickle objects on DBM-style database files.
Note: The pickle module is rather slow. A
reimplementation of the same algorithm in C, which is up to 1000 times
faster, is available as the
cPickle (module-cPickle.html) module. This has the same
interface except that Pickler and Unpickler are
factory functions, not classes (so they cannot be used as base classes
for inheritance).
Although the pickle module can use the built-in module
marshal (module-marshal.html) internally, it differs from
marshal (module-marshal.html) in the way it handles certain kinds of data:
- Recursive objects (objects containing references to themselves):
pickle keeps track of the objects it has already
serialized, so later references to the same object won't be
serialized again. (The marshal (module-marshal.html) module breaks for
this.)
- Object sharing (references to the same object in different
places): This is similar to self-referencing objects;
pickle stores the object once, and ensures that all
other references point to the master copy. Shared objects
remain shared, which can be very important for mutable objects.
- User-defined classes and their instances: marshal (module-marshal.html)
does not support these at all, but pickle can save
and restore class instances transparently. The class definition
must be importable and live in the same module as when the
object was stored.
The data format used by pickle is Python-specific. This has
the advantage that there are no restrictions imposed by external
standards such as
XDR (which can't
represent pointer sharing); however it means that non-Python programs
may not be able to reconstruct pickled Python objects.
By default, the pickle data format uses a printable ASCII
representation. This is slightly more voluminous than a binary
representation. The big advantage of using printable ASCII (and of
some other characteristics of pickle's representation) is that
for debugging or recovery purposes it is possible for a human to read
the pickled file with a standard text editor.
A binary format, which is slightly more efficient, can be chosen by
specifying a nonzero (true) value for the bin argument to the
Pickler constructor or the dump() and dumps()
functions. The binary format is not the default because of backwards
compatibility with the Python 1.4 pickle module. In a future version,
the default may change to binary.
The pickle module doesn't handle code objects, which the
marshal (module-marshal.html) module does. I suppose
pickle could, and maybe it should, but there's probably no
great need for it right now (as long as marshal (module-marshal.html) continues
to be used for reading and writing code objects), and at least this
avoids the possibility of smuggling Trojan horses into a program.
For the benefit of persistency modules written using pickle, it
supports the notion of a reference to an object outside the pickled
data stream. Such objects are referenced by a name, which is an
arbitrary string of printable ASCII characters. The resolution of
such names is not defined by the pickle module -- the
persistent object module will have to implement a method
persistent_load(). To write references to persistent objects,
the persistent module must define a method persistent_id() which
returns either `None` or the persistent ID of the object.
There are some restrictions on the pickling of class instances.
First of all, the class must be defined at the top level in a module.
Furthermore, all its instance variables must be picklable.
When a pickled class instance is unpickled, its __init__() method
is normally not invoked. Note: This is a deviation
from previous versions of this module; the change was introduced in
Python 1.5b2. The reason for the change is that in many cases it is
desirable to have a constructor that requires arguments; it is a
(minor) nuisance to have to provide a __getinitargs__() method.
If it is desirable that the __init__() method be called on
unpickling, a class can define a method __getinitargs__(),
which should return a tuple containing the arguments to be
passed to the class constructor (__init__()). This method is
called at pickle time; the tuple it returns is incorporated in the
pickle for the instance.
Classes can further influence how their instances are pickled -- if
the class
defines the method __getstate__(), it is called and the return
state is pickled as the contents for the instance, and if the class
defines the method __setstate__(), it is called with the
unpickled state. (Note that these methods can also be used to
implement copying class instances.) If there is no
__getstate__() method, the instance's __dict__ is
pickled. If there is no __setstate__() method, the pickled
object must be a dictionary and its items are assigned to the new
instance's dictionary. (If a class defines both __getstate__()
and __setstate__(), the state object needn't be a dictionary
-- these methods can do what they want.) This protocol is also used
by the shallow and deep copying operations defined in the
copy (module-copy.html) module.
Note that when class instances are pickled, their class's code and
data are not pickled along with them. Only the instance data are
pickled. This is done on purpose, so you can fix bugs in a class or
add methods and still load objects that were created with an earlier
version of the class. If you plan to have long-lived objects that
will see many versions of a class, it may be worthwhile to put a version
number in the objects so that suitable conversions can be made by the
class's __setstate__() method.
When a class itself is pickled, only its name is pickled -- the class
definition is not pickled, but re-imported by the unpickling process.
Therefore, the restriction that the class must be defined at the top
level in a module applies to pickled classes as well.
The interface can be summarized as follows.
To pickle an object `x` onto a file `f`, open for writing:
```text

p = pickle.Pickler(f)
p.dump(x)
```
A shorthand for this is:
```text

pickle.dump(x, f)
```
To unpickle an object `x` from a file `f`, open for reading:
```text

u = pickle.Unpickler(f)
x = u.load()
```
A shorthand is:
```text

x = pickle.load(f)
```
The Pickler class only calls the method `f.write()` with a
string argument. The Unpickler calls the methods `f.read()`(with an integer argument) and `f.readline()` (without argument),
both returning a string. It is explicitly allowed to pass non-file
objects here, as long as they have the right methods.
The constructor for the Pickler class has an optional second
argument, bin. If this is present and true, the binary
pickle format is used; if it is absent or false, the (less efficient,
but backwards compatible) text pickle format is used. The
Unpickler class does not have an argument to distinguish
between binary and text pickle formats; it accepts either format.
The following types can be pickled:
- `None`
- integers, long integers, floating point numbers
- normal and Unicode strings
- tuples, lists and dictionaries containing only picklable objects
- functions defined at the top level of a module (by name
reference, not storage of the implementation)
- built-in functions
- classes that are defined at the top level in a module
- instances of such classes whose __dict__ or
__setstate__() is picklable
Attempts to pickle unpicklable objects will raise the
PicklingError exception; when this happens, an unspecified
number of bytes may have been written to the file.
It is possible to make multiple calls to the dump() method of
the same Pickler instance. These must then be matched to the
same number of calls to the load() method of the
corresponding Unpickler instance. If the same object is
pickled by multiple dump() calls, the load() will all
yield references to the same object. Warning: this is intended
for pickling multiple objects without intervening modifications to the
objects or their parts. If you modify an object and then pickle it
again using the same Pickler instance, the object is not
pickled again -- a reference to it is pickled and the
Unpickler will return the old value, not the modified one.
(There are two problems here: (a) detecting changes, and (b)
marshalling a minimal set of changes. I have no answers. Garbage
Collection may also become a problem here.)
Apart from the Pickler and Unpickler classes, the
module defines the following functions, and an exception:
See Also:


module-fcntl.html | unix.html | template-objects.html | Python Library Reference | contents.html | genindex.html
---
# 8.13 pipes --
Interface to shell pipelines
Availability: Unix.
The pipes module defines a class to abstract the concept of
a pipeline -- a sequence of convertors from one file to
another.
Because the module uses /bin/sh command lines, a POSIX or
compatible shell for os.system() and os.popen()
is required.
The pipes module defines the following class:
Example:
```text

>>> import pipes
>>> t=pipes.Template()
>>> t.append('tr a-z A-Z', '--')
>>> f=t.open('/tmp/1', 'w')
>>> f.write('hello world')
>>> f.close()
>>> open('/tmp/1').read()
'HELLO WORLD'
```


module-syslog.html | unix.html | popen3-objects.html | Python Library Reference | contents.html | genindex.html
---
# 8.18 popen2 --
Subprocesses with accessible I/O streams
Availability: Unix.
This module allows you to spawn processes and connect their
input/output/error pipes and obtain their return codes under Unix.
Similar functionality exists for Windows platforms using the
win32pipe module provided as part of Mark Hammond's Windows
extensions.
The primary interface offered by this module is a pair of factory
functions:
The class defining the objects returned by the factory functions is
also available:


11.6 poplib -- POP3 protocol client

module-gopherlib.html | internet.html | pop3-objects.html | Python Library Reference | contents.html | genindex.html
---
# 11.6 poplib --
POP3 protocol client
This module defines a class, POP3, which encapsulates a
connection to an POP3 server and implements protocol as defined in
RFC 1725 (http://www.ietf.org/rfc/rfc1725.txt). The POP3 class supports both the minmal and
optional command sets.
A single class is provided by the poplib module:
One exception is defined as an attribute of the poplib module:


unix.html | unix.html | posix-large-files.html | Python Library Reference | contents.html | genindex.html
---
# 8.1 posix --
The most common POSIX system calls
Availability: Unix.
This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly
disguised Unix interface).
Do not import this module directly. Instead, import the
module os (module-os.html), which provides a portable version of this
interface. On Unix, the os (module-os.html) module provides a superset of
the posix interface. On non-Unix operating systems the
posix module is not available, but a subset is always
available through the os (module-os.html) interface. Once os (module-os.html) is
imported, there is no performance penalty in using it instead
of posix. In addition, os (module-os.html)
provides some additional functionality, such as automatically calling
putenv() when an entry in `os.environ` is changed.
The descriptions below are very terse; refer to the corresponding
Unix manual (or POSIX documentation) entry for more information.
Arguments called path refer to a pathname given as a string.
Errors are reported as exceptions; the usual exceptions are given for
type errors, while errors reported by the system calls raise
error (a synonym for the standard exception
OSError), described below.


template-objects.html | unix.html | module-resource.html | Python Library Reference | contents.html | genindex.html
---
# 8.14 posixfile --
File-like objects with locking support
Availability: Unix.
Note: This module will become obsolete in a future release.
The locking operation that it provides is done better and more
portably by the fcntl.lockf() call.
This module implements some additional functionality over the built-in
file objects. In particular, it implements file locking, control over
the file flags, and an easy interface to duplicate the file object.
The module defines a new file object, the posixfile object. It
has all the standard file object methods and adds the methods
described below. This module only works for certain flavors of
Unix, since it uses fcntl.fcntl() for file locking.
To instantiate a posixfile object, use the open() function
in the posixfile module. The resulting object looks and
feels roughly the same as a standard file object.
The posixfile module defines the following constants:
The posixfile module defines the following functions:
The posixfile object defines the following additional methods:
All methods raise IOError when the request fails.
Format characters for the lock() method have the following
meaning:
In addition the following modifiers can be added to the format:
Note:
(1): The lock returned is in the format `( mode , len , start , whence , pid )` where mode is a character
representing the type of lock ('r' or 'w'). This modifier prevents a
request from being granted; it is for query purposes only.
Format characters for the flags() method have the following
meanings:
In addition the following modifiers can be added to the format:
Notes:
(1): The "!" and "=" modifiers are mutually exclusive.
(2): This string represents the flags after they may have been altered
by the same call.
Examples:


3.25 pprint -- Data pretty printer.

module-codeop.html | python.html | PrettyPrinter_Objects.html | Python Library Reference | contents.html | genindex.html
---
# 3.25 pprint --
Data pretty printer.
The pprint module provides a capability to ``pretty-print''
arbitrary Python data structures in a form which can be used as input
to the interpreter. If the formatted structures include objects which
are not fundamental Python types, the representation may not be
loadable. This may be the case if objects such as files, sockets,
classes, or instances are included, as well as many other builtin
objects which are not representable as Python constants.
The formatted representation keeps objects on a single line if it can,
and breaks them onto multiple lines if they don't fit within the
allowed width. Construct PrettyPrinter objects explicitly if
you need to adjust the width constraint.
The pprint module defines one class:
The PrettyPrinter class supports several derivative functions:
One more support function is also defined:
```text

>>> pprint.saferepr(stuff)
"[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca
l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python
1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']"
```


10.5 Reference Manual

Deterministic_Profiling.html | profile.html | profile-stats.html | Python Library Reference | contents.html | genindex.html
---
# 10.5 Reference Manual
The primary entry point for the profiler is the global function
profile.run(). It is typically used to create any profile
information. The reports are formatted and printed using methods of
the class pstats.Stats. The following is a description of all
of these standard entry points and functions. For a more in-depth
view of some of the code, consider reading the later section on
Profiler Extensions, which includes discussion of how to derive
``better'' profilers from the classes presented, or reading the source
code for these modules.
Analysis of the profiler data is done using this class from the
pstats module:


8.11 pty -- Pseudo-terminal utilities

module-tty.html | unix.html | module-fcntl.html | Python Library Reference | contents.html | genindex.html
---
# 8.11 pty --
Pseudo-terminal utilities
Availability: IRIX, Linux.
The pty module defines operations for handling the
pseudo-terminal concept: starting another process and being able to
write to and read from its controlling terminal programmatically.
Because pseudo-terminal handling is highly platform dependant, there
is code to do it only for SGI and Linux. (The Linux code is supposed
to work on other platforms, but hasn't been tested yet.)
The pty module defines the following functions:


8.2 pwd -- The password database

posix-contents.html | unix.html | module-grp.html | Python Library Reference | contents.html | genindex.html
---
# 8.2 pwd --
The password database
Availability: Unix.
This module provides access to the Unix user account and password
database. It is available on all Unix versions.
Password database entries are reported as 7-tuples containing the
following items from the password database (see `<pwd.h>`), in order:
The uid and gid items are integers, all others are strings.
KeyError is raised if the entry asked for cannot be found.
Note: In traditional Unix the field `pw_passwd` usually
contains a password encrypted with a DES derived algorithm (see module
crypt (module-crypt.html)). However most modern unices
use a so-called shadow password system. On those unices the
field `pw_passwd` only contains a asterisk (`'*'`) or the
letter "x" where the encrypted password is stored in a file
/etc/shadow which is not world readable.
It defines the following items:


module-tabnanny.html | python.html | pyclbr-class-objects.html | Python Library Reference | contents.html | genindex.html
---
# 3.22 pyclbr --
Python class browser support
The pyclbr can be used to determine some limited information
about the classes and methods defined in a module. The information
provided is sufficient to implement a traditional three-pane class
browser. The information is extracted from the source code rather
than from an imported module, so this module is safe to use with
untrusted source code. This restriction makes it impossible to use
this module with modules not implemented in Python, including many
standard and optional extension modules.


subclassing-reprs.html | python.html | module-compileall.html | Python Library Reference | contents.html | genindex.html
---
# 3.27 py_compile --
Compile Python source files
The py_compile module provides a single function to generate
a byte-code file from a source file.
Though not often needed, this function can be useful when installing
modules for shared use, especially if some of the users may not have
permission to write the byte-code cache files in the directory
containing the source code.


thread-objects.html | someos.html | QueueObjects.html | Python Library Reference | contents.html | genindex.html
---
# 7.6 Queue --
A synchronized queue class.
The Queue module implements a multi-producer, multi-consumer
FIFO queue. It is especially useful in threads programming when
information must be exchanged safely between multiple threads. The
Queue class in this module implements all the required locking
semantics. It depends on the availability of thread support in
Python.
The Queue module defines the following class and exception:


module-base64.html | netdata.html | module-mailbox.html | Python Library Reference | contents.html | genindex.html
---
# 12.17 quopri --
Encode and decode MIME quoted-printable data
This module performs quoted-printable transport encoding and decoding,
as defined in RFC 1521 (http://www.ietf.org/rfc/rfc1521.txt): ``MIME (Multipurpose Internet Mail Extensions)
Part One''. The quoted-printable encoding is designed for data where
there are relatively few nonprintable characters; the base64 encoding
scheme available via the base64 (module-base64.html) module is more compact if there
are many such characters, as when sending a graphics file.


module-cmath.html | misc.html | rng-objects.html | Python Library Reference | contents.html | genindex.html
---
# 5.3 random --
Generate pseudo-random numbers
This module implements pseudo-random number generators for various
distributions: on the real line, there are functions to compute normal
or Gaussian, lognormal, negative exponential, gamma, and beta
distributions. For generating distribution of angles, the circular
uniform and von Mises distributions are available.
The random module supports the Random Number
Generator interface, described in section 5.3.1 (rng-objects.html#rng-objects). This
interface of the module, as well as the distribution-specific
functions described below, all use the pseudo-random generator
provided by the whrandom (module-whrandom.html) module.
The following functions are defined to support specific distributions,
and all return real values. Function parameters are named after the
corresponding variables in the distribution's equation, as used in
common mathematical practice; most of these equations can be found in
any statistics text. These are expected to become part of the Random
Number Generator interface in a future release.
See Also:


module-string.html | strings.html | re-syntax.html | Python Library Reference | contents.html | genindex.html
---
# 4.2 re --
Perl-style regular expression operations.
This module provides regular expression matching operations similar to
those found in Perl. It's 8-bit clean: the strings being processed
may contain both null bytes and characters whose high bit is set. Regular
expression pattern strings may not contain null bytes, but can specify
the null byte using the `\ number` notation.
Characters with the high bit set may be included. The re
module is always available.
Regular expressions use the backslash character ("\") to
indicate special forms or to allow special characters to be used
without invoking their special meaning. This collides with Python's
usage of the same character for the same purpose in string literals;
for example, to match a literal backslash, one might have to write
`'\\\\'` as the pattern string, because the regular expression
must be "\\", and each backslash must be expressed as
"\\" inside a regular Python string literal.
The solution is to use Python's raw string notation for regular
expression patterns; backslashes are not handled in any special way in
a string literal prefixed with "r". So `r"\n"` is a
two-character string containing "\" and "n",
while `"\n"` is a one-character string containing a newline.
Usually patterns will be expressed in Python code using this raw
string notation.


match-objects.html | strings.html | node91.html | Python Library Reference | contents.html | genindex.html
---
# 4.3 regex --
Regular expression search and match operations.
This module provides regular expression matching operations similar to
those found in Emacs.
Obsolescence note:
This module is obsolete as of Python version 1.5; it is still being
maintained because much existing code still uses it. All new code in
need of regular expressions should use the new
`re` module, which supports the more powerful
and regular Perl-style regular expressions. Existing code should be
converted. The standard library module
`reconvert` helps in converting
`regex` style regular expressions to `re`
style regular expressions. (For more conversion help, see Andrew
Kuchling's ``regex-to-re HOWTO'' at
http://www.python.org/doc/howto/regex-to-re/.)
By default the patterns are Emacs-style regular expressions
(with one exception). There is
a way to change the syntax to match that of several well-known
Unix utilities. The exception is that Emacs' "\s"pattern is not supported, since the original implementation references
the Emacs syntax tables.
This module is 8-bit clean: both patterns and strings may contain null
bytes and characters whose high bit is set.
Please note: There is a little-known fact about Python string
literals which means that you don't usually have to worry about
doubling backslashes, even though they are used to escape special
characters in string literals as well as in regular expressions. This
is because Python doesn't remove backslashes from string literals if
they are followed by an unrecognized escape character.
However, if you want to include a literal backslash in a
regular expression represented as a string literal, you have to
quadruple it or enclose it in a singleton character class.
E.g. to extract LATEX "\section{ ...}" headers
from a document, you can use this pattern:
`'[\]section{\(.*\)}'`. Another exception:
the escape sequece "\b" is significant in string literals
(where it means the ASCII bell character) as well as in Emacs regular
expressions (where it stands for a word boundary), so in order to
search for a word boundary, you should use the pattern `'\\b'`.
Similarly, a backslash followed by a digit 0-7 should be doubled to
avoid interpretation as an octal escape.


Contents_of_Module_regex.html | strings.html | module-struct.html | Python Library Reference | contents.html | genindex.html
---
# 4.4 regsub --
String operations using regular expressions
This module defines a number of functions useful for working with
regular expressions (see built-in module regex (module-regex.html)).
Warning: these functions are not thread-safe.
Obsolescence note:
This module is obsolete as of Python version 1.5; it is still being
maintained because much existing code still uses it. All new code in
need of regular expressions should use the new re (module-re.html) module, which
supports the more powerful and regular Perl-style regular expressions.
Existing code should be converted. The standard library module
reconvert helps in converting regex (module-regex.html) style regular
expressions to re (module-re.html) style regular expressions. (For more
conversion help, see Andrew Kuchling's
``regex-to-re HOWTO'' at
http://www.python.org/doc/howto/regex-to-re/.)


PrettyPrinter_Objects.html | python.html | Repr-objects.html | Python Library Reference | contents.html | genindex.html
---
# 3.26 repr --
Alternate repr() implementation.
The repr module provides a means for producing object
representations with limits on the size of the resulting strings.
This is used in the Python debugger and may be useful in other
contexts as well.
This module provides a class, an instance, and a function:


module-posixfile.html | unix.html | node200.html | Python Library Reference | contents.html | genindex.html
---
# 8.15 resource --
Resource usage information
Availability: Unix.
This module provides basic mechanisms for measuring and controlling
system resources utilized by a program.
Symbolic constants are used to specify particular system resources and
to request usage information about either the current process or its
children.
A single exception is defined for errors:


restricted.html | restricted.html | node309.html | Python Library Reference | contents.html | genindex.html
---
# 13.1 rexec --
Restricted execution framework
This module contains the RExec class, which supports
r_eval(), r_execfile(), r_exec(), and
r_import() methods, which are restricted versions of the standard
Python functions eval(), execfile() and
the exec and import statements.
Code executed in this restricted environment will
only have access to modules and functions that are deemed safe; you
can subclass RExec to add or remove capabilities as desired.
Note: The RExec class can prevent code from performing
unsafe operations like reading or writing disk files, or using TCP/IP
sockets. However, it does not protect against code using extremely
large amounts of memory or CPU time.
The RExec class has the following class attributes, which are
used by the __init__() method. Changing them on an existing
instance won't have any effect; instead, create a subclass of
RExec and assign them new values in the class definition.
Instances of the new class will then use those new values. All these
attributes are tuples of strings.
RExec instances support the following methods:
Methods whose names begin with "s_" are similar to the functions
beginning with "r_", but the code will be granted access to
restricted versions of the standard I/O streams `sys.stdin`,
`sys.stderr`, and `sys.stdout`.
RExec objects must also support various methods which will be
implicitly called by code executing in the restricted environment.
Overriding these methods in a subclass is used to change the policies
enforced by a restricted environment.
And their equivalents with access to restricted standard I/O streams:


writer-impls.html | netdata.html | message-objects.html | Python Library Reference | contents.html | genindex.html
---
# 12.6 rfc822 --
Parse RFC 822 mail headers
This module defines a class, Message, which represents a
collection of ``email headers'' as defined by the Internet standard
RFC 822 (http://www.ietf.org/rfc/rfc0822.txt). It is used in various contexts, usually to read such
headers from a file. This module also defines a helper class
AddressList for parsing RFC 822 (http://www.ietf.org/rfc/rfc0822.txt) addresses. Please refer to
the RFC for information on the specific syntax of RFC 822 (http://www.ietf.org/rfc/rfc0822.txt) headers.
The mailbox (module-mailbox.html) module provides classes
to read mailboxes produced by various end-user mail programs.
See Also:


module-colorsys.html | mmedia.html | module-imghdr.html | Python Library Reference | contents.html | genindex.html
---
# 14.8 rgbimg --
Read and write ``SGI RGB'' files
The rgbimg module allows Python programs to access SGI imglib image
files (also known as .rgb files). The module is far from
complete, but is provided anyway since the functionality that there is
enough in some cases. Currently, colormap files are not supported.
The module defines the following variables and functions:


zipfile-objects.html | someos.html | completer-objects.html | Python Library Reference | contents.html | genindex.html
---
# 7.15 rlcompleter --
Completion function for readline
The rlcompleter module defines a completion function for
the readline module by completing valid Python identifiers and
keyword.
The rlcompleter module defines the Completer class.
Example:
```text

>>> import rlcompleter
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> readline. <TAB PRESSED>
readline.__doc__ readline.get_line_buffer readline.read_init_file
readline.__file__ readline.insert_text readline.set_completer
readline.__name__ readline.parse_and_bind
>>> readline.
```
The rlcompleter module is designed for use with Python's
interactive mode. A user can add the following lines to his or her
initialization file (identified by the $PYTHONSTARTUP
environment variable) to get automatic Tab completion:
```text

try:
import readline
except ImportError:
print "Module readline not available."
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
```


netrc-objects.html | netdata.html | restricted.html | Python Library Reference | contents.html | genindex.html
---
# 12.22 robotparser --
Parser for robots.txt
This module provides a single class, RobotFileParser, which answers
questions about whether or not a particular user agent can fetch a URL on
the web site that published the robots.txt file. For more details on
the structure of robots.txt files, see
http://info.webcrawler.com/mak/projects/robots/norobots.html.
The following example demonstrates basic use of the RobotFileParser class.
```text

>>> import robotparser
>>> rp = robotparser.RobotFileParser()
>>> rp.set_url("http://www.musi-cal.com/robots.txt")
>>> rp.read()
>>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco")
0
>>> rp.can_fetch("*", "http://www.musi-cal.com/")
1
```


module-mpz.html | crypto.html | sgi.html | Python Library Reference | contents.html | genindex.html
---
# 15.4 rotor --
Enigma-like encryption and decryption.
This module implements a rotor-based encryption algorithm, contributed by
Lance Ellinghouse. The design is derived
from the Enigma device, a machine
used during World War II to encipher messages. A rotor is simply a
permutation. For example, if the character `A' is the origin of the rotor,
then a given rotor might map `A' to `L', `B' to `Z', `C' to `G', and so on.
To encrypt, we choose several different rotors, and set the origins of the
rotors to known positions; their initial position is the ciphering key. To
encipher a character, we permute the original character by the first rotor,
and then apply the second rotor's permutation to the result. We continue
until we've applied all the rotors; the resulting character is our
ciphertext. We then change the origin of the final rotor by one position,
from `A' to `B'; if the final rotor has made a complete revolution, then we
rotate the next-to-last rotor by one position, and apply the same procedure
recursively. In other words, after enciphering one character, we advance
the rotors in the same fashion as a car's odometer. Decoding works in the
same way, except we reverse the permutations and apply them in the opposite
order.
The available functions in this module are:
Rotor objects have the following methods:
An example usage:
```text

>>> import rotor
>>> rt = rotor.newrotor('key', 12)
>>> rt.encrypt('bar')
'\2534\363'
>>> rt.encryptmore('bar')
'\357\375$'
>>> rt.encrypt('bar')
'\2534\363'
>>> rt.decrypt('\2534\363')
'bar'
>>> rt.decryptmore('\357\375$')
'bar'
>>> rt.decrypt('\357\375$')
'l(\315'
>>> del rt
```
The module's code is not an exact simulation of the original Enigma
device; it implements the rotor encryption scheme differently from the
original. The most important difference is that in the original
Enigma, there were only 5 or 6 different rotors in existence, and they
were applied twice to each character; the cipher key was the order in
which they were placed in the machine. The Python rotor
module uses the supplied key to initialize a random number generator;
the rotor permutations and their initial positions are then randomly
generated. The original device only enciphered the letters of the
alphabet, while this module can handle any 8-bit binary data; it also
produces binary output. This module can also operate with an
arbitrary number of rotors.
The original Enigma cipher was broken in 1944. The version implemented here is probably a good deal more difficult to crack
(especially if you use many rotors), but it won't be impossible for
a truly skilful and determined attacker to break the cipher. So if you want
to keep the NSA out of your files, this rotor cipher may well be unsafe, but
for discouraging casual snooping through your files, it will probably be
just fine, and may be somewhat safer than using the Unix crypt
command.


6.9 sched -- Event scheduler

module-time.html | allos.html | scheduler-objects.html | Python Library Reference | contents.html | genindex.html
---
# 6.9 sched --
Event scheduler
The sched module defines a class which implements a general
purpose event scheduler:
Example:
```text

>>> import sched, time
>>> s=sched.scheduler(time.time, time.sleep)
>>> def print_time(): print "From print_time", time.time()
...
>>> def print_some_times():
... print time.time()
... s.enter(5, 1, print_time, ())
... s.enter(10, 1, print_time, ())
... s.run()
... print time.time()
...
>>> print_some_times()
930343690.257
From print_time 930343695.274
From print_time 930343700.273
930343700.276
```


Socket_Example.html | someos.html | module-thread.html | Python Library Reference | contents.html | genindex.html
---
# 7.3 select --
Waiting for I/O completion
This module provides access to the function select()
available in most operating systems. Note that on Windows, it only
works for sockets; on other operating systems, it also works for other
file types (in particular, on Unix, it works on pipes). It cannot
be used on regular files to determine whether a file has grown since
it was last read.
The module defines the following:


12.1 sgmllib -- Simple SGML parser

netdata.html | netdata.html | module-htmllib.html | Python Library Reference | contents.html | genindex.html
---
# 12.1 sgmllib --
Simple SGML parser
This module defines a class SGMLParser which serves as the
basis for parsing text files formatted in SGML (Standard Generalized
Mark-up Language). In fact, it does not provide a full SGML parser
-- it only parses SGML insofar as it is used by HTML, and the module
only exists as a base for the htmllib (module-htmllib.html)
module.
SGMLParser instances have the following interface methods:
Apart from overriding or extending the methods listed above, derived
classes may also define methods of the following form to define
processing of specific tags. Tag names in the input stream are case
independent; the tag occurring in method names must be in lower
case:


module-md5.html | crypto.html | module-mpz.html | Python Library Reference | contents.html | genindex.html
---
# 15.2 sha --
SHA message digest algorithm
This module implements the interface to NIST's secure hash
algorithm, known as SHA. It is used in
the same way as the md5 (module-md5.html) module: use the new()
to create an sha object, then feed this object with arbitrary strings
using the update() method, and at any point you can ask it
for the digest of the contatenation of the strings fed to it
so far. SHA digests are 160 bits instead of 128
bits.
The following values are provided as constants in the module and as
attributes of the sha objects returned by new():
A sha object has all the methods the md5 objects have, plus one:


module-copyreg.html | python.html | module-copy.html | Python Library Reference | contents.html | genindex.html
---
# 3.12 shelve --
Python object persistency
A ``shelf'' is a persistent, dictionary-like object. The difference
with ``dbm'' databases is that the values (not the keys!) in a shelf
can be essentially arbitrary Python objects -- anything that the
pickle (module-pickle.html) module can handle. This includes most class
instances, recursive data types, and objects containing lots of shared
sub-objects. The keys are ordinary strings.
To summarize the interface (`key` is a string, `data` is an
arbitrary object):
```text

import shelve

d = shelve.open(filename) # open, with (g)dbm filename -- no suffix

d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve data at key (raise KeyError if no
# such key)
del d[key] # delete data stored at key (raises KeyError
# if no such key)
flag = d.has_key(key) # true if the key exists
list = d.keys() # a list of all existing keys (slow!)

d.close() # close it
```
Restrictions:
- The choice of which database package will be used
(e.g. dbm (module-dbm.html) or gdbm (module-gdbm.html)) depends on which interface
is available. Therefore it is not safe to open the database directly
using dbm (module-dbm.html). The database is also (unfortunately) subject
to the limitations of dbm (module-dbm.html), if it is used -- this means
that (the pickled representation of) the objects stored in the
database should be fairly small, and in rare cases key collisions may
cause the database to refuse updates.
- Dependent on the implementation, closing a persistent dictionary may
or may not be necessary to flush changes to disk.
- The shelve module does not support concurrent read/write
access to shelved objects. (Multiple simultaneous read accesses are
safe.) When a program has a shelf open for writing, no other program
should have it open for reading or writing. Unix file locking can
be used to solve this, but this differs across Unix versions and
requires knowledge about the database implementation used.


5.11 shlex -- Simple lexical analysis

Cmd-objects.html | misc.html | shlex-objects.html | Python Library Reference | contents.html | genindex.html
---
# 5.11 shlex --
Simple lexical analysis
New in version 1.5.2.
The shlex class makes it easy to write lexical analyzers for
simple syntaxes resembling that of the Unix shell. This will often
be useful for writing minilanguages, e.g. in run control files for
Python applications.
See Also:


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


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


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


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

# foo package configuration

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

# bar package configuration

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

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


11.9 smtplib -- SMTP protocol client

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


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


Signal_Example.html | someos.html | socket-objects.html | Python Library Reference | contents.html | genindex.html
---
# 7.2 socket --
Low-level networking interface
This module provides access to the BSD socket interface.
It is available on all modern Unix systems, Windows, MacOS, BeOS,
OS/2, and probably additional platforms.
For an introduction to socket programming (in C), see the following
papers: An Introductory 4.3BSD Interprocess Communication
Tutorial, by Stuart Sechrest and An Advanced 4.3BSD
Interprocess Communication Tutorial, by Samuel J. Leffler et al,
both in the Unix Programmer's Manual, Supplementary Documents 1
(sections PS1:7 and PS1:8). The platform-specific reference material
for the various socket-related system calls are also a valuable source
of information on the details of socket semantics. For Unix, refer
to the manual pages; for Windows, see the WinSock (or Winsock 2)
specification.
The Python interface is a straightforward transliteration of the
Unix system call and library interface for sockets to Python's
object-oriented style: the socket() function returns a
socket object whose methods implement the
various socket system calls. Parameter types are somewhat
higher-level than in the C interface: as with read() and
write() operations on Python files, buffer allocation on
receive operations is automatic, and buffer length is implicit on send
operations.
Socket addresses are represented as a single string for the
AF_UNIX address family and as a pair
`( host , port )` for the AF_INET address
family, where host is a string representing
either a hostname in Internet domain notation like
`'daring.cwi.nl'` or an IP address like `'100.50.200.5'`,
and port is an integral port number. Other address families are
currently not supported. The address format required by a particular
socket object is automatically selected based on the address family
specified when the socket object was created.
For IP addresses, two special forms are accepted instead of a host
address: the empty string represents INADDR_ANY, and the string
`'<broadcast>'` represents INADDR_BROADCAST.
All errors raise exceptions. The normal exceptions for invalid
argument types and out-of-memory conditions can be raised; errors
related to socket or address semantics raise the error
socket.error.
Non-blocking mode is supported through the
setblocking() method.
The module socket exports the following constants and functions:


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


6.4 stat -- Interpreting stat() results

module-dircache.html | allos.html | module-statcache.html | Python Library Reference | contents.html | genindex.html
---
# 6.4 stat --
Interpreting stat() results
The stat module defines constants and functions for
interpreting the results of os.stat(),
os.fstat() and os.lstat() (if they exist). For
complete details about the stat(), fstat() and
lstat() calls, consult the documentation for your system.
The stat module defines the following functions to test for
specific file types:
Two additional functions are defined for more general manipulation of
the file's mode:
Normally, you would use the os.path.is*() functions for
testing the type of a file; the functions here are useful when you are
doing multiple tests of the same file and wish to avoid the overhead of
the stat() system call for each test. These are also
useful when checking for information about a file that isn't handled
by os.path (module-os.path.html), like the tests for block and character
devices.
All the variables below are simply symbolic indexes into the 10-tuple
returned by os.stat(), os.fstat() or
os.lstat().
Example:


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


4.1 string -- Common string operations

strings.html | strings.html | module-re.html | Python Library Reference | contents.html | genindex.html
---
# 4.1 string --
Common string operations
This module defines some constants useful for checking character
classes and some useful string functions. See the module
re (module-re.html) for string functions based on regular
expressions.
The constants defined in this module are are:
The functions defined in this module are:


module-fpformat.html | strings.html | module-cStringIO.html | Python Library Reference | contents.html | genindex.html
---
# 4.7 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 on file objects for operations (section
2.1.7 (bltin-file-objects.html#bltin-file-objects)).
The following methods of StringIO objects require special
mention:


module-regsub.html | strings.html | module-fpformat.html | Python Library Reference | contents.html | genindex.html
---
# 4.5 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 "I" conversion code will convert to a Python long if
the C int is the same size as a C long, which is
typical on most modern systems. If a C int is smaller than
a C long, an Python integer will be created instead.
A format character may be preceded by an integral repeat count;
e.g. 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; e.g. `'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 can be used to encode a Pascal
string. The first byte is the length of the stored string, with the
bytes of the string following. If count is given, it is used as the
total number of bytes used, including the length byte. If the string
passed in to pack() is too long, the stored representation
is truncated. If the string is too short, padding is used to ensure
that exactly enough bytes are used to satisfy the count.
For the "I" and "L" 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 (e.g. Motorola and Sun are big-endian; Intel and DEC 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. 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 (i.e. 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)
'\000\001\000\002\000\000\000\003'
>>> unpack('hhl', '\000\001\000\002\000\000\000\003')
(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, e.g. 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 | genindex.html
---
# 14.4 sunau --
Read and write Sun AU files
The sunau module provides a convenient interface to the Sun AU sound
format. Note that this module is interface-compatible with the modules
aifc (module-aifc.html) and wave (module-wave.html).
The sunau module defines the following functions:
The sunau module defines the following exception:
The sunau module defines the following data item:


audio-device-objects.html | sunos.html | node355.html | Python Library Reference | contents.html | genindex.html
---
# 17.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 | genindex.html
---
# 17.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-LAW format 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:


node56.html | python.html | module-token.html | Python Library Reference | contents.html | genindex.html
---
# 3.17 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 defintions 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-types.html | Python Library Reference | contents.html | genindex.html
---
# 3.1 sys --
System-specific parameters and functions
This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
It is always available.


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


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


11.10 telnetlib -- Telnet client

SMTP-example.html | internet.html | telnet-objects.html | Python Library Reference | contents.html | genindex.html
---
# 11.10 telnetlib --
Telnet client
The telnetlib module provides a Telnet class that
implements the Telnet protocol. See RFC 854 (http://www.ietf.org/rfc/rfc0854.txt) for details about the
protocol.
See Also:


module-getopt.html | allos.html | module-errno.html | Python Library Reference | contents.html | genindex.html
---
# 6.13 tempfile --
Generate temporary file names
This module generates temporary file names. It is not Unix specific,
but it may require some help on non-Unix systems.
Note: the modules does not create temporary files, nor does it
automatically remove them when the current process exits or dies.
The module defines a single user-callable function:
The module uses two global variables that tell it how to construct a
temporary name. The caller may assign values to them; by default they
are initialized at the first call to mktemp().


8.8 termios -- POSIX style tty control

module-gdbm.html | unix.html | termios_Example.html | Python Library Reference | contents.html | genindex.html
---
# 8.8 termios --
POSIX style tty control
Availability: Unix.
This module provides an interface to the POSIX calls for tty I/O
control. For a complete description of these calls, see the POSIX or
Unix manual pages. It is only available for those Unix versions
that support POSIX termios style tty I/O control (and then
only if configured at installation time).
All functions in this module take a file descriptor fd as their
first argument. This must be an integer file descriptor, such as
returned by `sys.stdin.fileno()`.
This module should be used in conjunction with the
TERMIOS (module-TERMIOSuppercase.html) module,
which defines the relevant symbolic constants (see the next section).
The module defines the following functions:
See Also:


termios_Example.html | unix.html | module-tty.html | Python Library Reference | contents.html | genindex.html
---
# 8.9 TERMIOS --
Constants used with the termios module
Availability: Unix.
This module defines the symbolic constants required to use the
termios (module-termios.html) module (see the previous
section). See the POSIX or Unix manual pages (or the source)
for a list of those constants.


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


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


6.8 time -- Time access and conversions

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


module-symbol.html | python.html | module-keyword.html | Python Library Reference | contents.html | genindex.html
---
# 3.18 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 defintions
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 | python.html | module-tabnanny.html | Python Library Reference | contents.html | genindex.html
---
# 3.20 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 scanner is exposed by a single function:
All constants from the token (module-token.html) module are also exported from
tokenize, as is one additional token type value that might be
passed to the tokeneater function by tokenize():


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


8.10 tty -- Terminal control functions

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


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

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


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

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

urllib._urlopener = AppURLopener
```
Restrictions:
- Currently, only the following protocols are supported: HTTP, (versions
0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files.
- The caching feature of urlretrieve() has been disabled
until I find the time to hack proper processing of Expiration time
headers.
- There should be a function to query whether a particular URL is in
the cache.
- For backward compatibility, if a URL appears to point to a local file
but the file can't be opened, the URL is re-interpreted using the FTP
protocol. This can sometimes cause confusing error messages.
- The urlopen() and urlretrieve() functions can
cause arbitrarily long delays while waiting for a network connection
to be set up. This means that it is difficult to build an interactive
web client using these functions without using threads.
- The data returned by urlopen() or urlretrieve()
is the raw data returned by the server. This may be binary data
(e.g. an image), plain text or (for example) HTML. The
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.
- 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).


telnet-example.html | internet.html | module-SocketServer.html | Python Library Reference | contents.html | genindex.html
---
# 11.11 urlparse --
Parse URLs into components.
This module defines a standard interface to break URL strings up in
components (addessing 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!). Refer to RFC 1808 (http://www.ietf.org/rfc/rfc1808.txt) for details on relative
URLs and RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) for information on basic URL syntax.
It defines the following functions:


module-site.html | python.html | module-builtin.html | Python Library Reference | contents.html | genindex.html
---
# 3.32 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, exececutes it (using
execfile()) in its own (i.e. 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 | genindex.html
---
# 3.3 UserDict --
Class wrapper for dictionary objects
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 behaviours to dictionaries.
The UserDict module defines the UserDict class:
In addition to supporting the methods and operations of mappings (see
section 2.1.6 (typesmapping.html#typesmapping)), UserDict instances provide the
following attribute:


module-UserDict.html | python.html | module-UserString.html | Python Library Reference | contents.html | genindex.html
---
# 3.4 UserList --
Class wrapper for list objects
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 behaviours to lists.
The UserList module defines the UserList class:
In addition to supporting the methods and operations of mutable
sequences (see section 2.1.5 (typesseq.html#typesseq)), UserList instances
provide the following attribute:


module-UserList.html | python.html | module-operator.html | Python Library Reference | contents.html | genindex.html
---
# 3.5 UserString --
Class wrapper for string objects
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 behaviours to strings.
The UserString module defines the UserString class:
In addition to supporting the methods and operations of string or
Unicode objects (see section 2.1.5 (typesseq.html#typesseq)), UserString instances
provide the following attribute:


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


14.5 wave -- Read and write WAV files

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


dbhash-objects.html | someos.html | module-bsddb.html | Python Library Reference | contents.html | genindex.html
---
# 7.10 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.


rng-objects.html | misc.html | module-bisect.html | Python Library Reference | contents.html | genindex.html
---
# 5.4 whrandom --
Pseudo-random number generator
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 5.3.1 (rng-objects.html#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.


msvcrt-other.html | node355.html | undoc.html | Python Library Reference | contents.html | genindex.html
---
# 18.2 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-binascii.html | netdata.html | xdr-packer-objects.html | Python Library Reference | contents.html | genindex.html
---
# 12.13 xdrlib --
Encode and decode XDR data.
The xdrlib module supports the External Data Representation
Standard as described in RFC 1014 (http://www.ietf.org/rfc/rfc1014.txt), 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.


module-htmlentitydefs.html | netdata.html | xml-namespace.html | Python Library Reference | contents.html | genindex.html
---
# 12.4 xmllib --
A parser for XML documents
Changed in version 1.5.2:
.
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:
The XML specification, published by the World Wide Web
Consortium (W3C), is available online at
http://www.w3.org/TR/REC-xml. References to
additional material on XML are available at
http://www.w3.org/XML/.
The Python XML Topic Guide provides a great deal of information
on using XML from Python and links to other sources of information
on XML. It's located on the Web at
http://www.python.org/topics/xml/.
The Python XML Special Interest Group is developing substantial
support for processing XML from Python. See
http://www.python.org/sigs/xml-sig/ for more information.
---
#### Footnotes


bsddb-objects.html | someos.html | module-gzip.html | Python Library Reference | contents.html | genindex.html
---
# 7.12 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.cdrom.com/pub/infozip/zlib/. Version 1.1.3 is the
most recent version as of April 1999; 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 a single attribute:


18.1.2 Console I/O

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


18.1.1 File Operations

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


18.1.3 Other Functions

msvcrt-console.html | module-msvcrt.html | module-winsound.html | Python Library Reference | contents.html | genindex.html
---
## 18.1.3 Other Functions


12.9.2 MultiFile Example

MultiFile-objects.html | module-multifile.html | module-binhex.html | Python Library Reference | contents.html | genindex.html
---
## 12.9.2 MultiFile Example


12.9.1 MultiFile Objects

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


6.19.1 Mutex Objects

module-mutex.html | module-mutex.html | someos.html | Python Library Reference | contents.html | genindex.html
---
## 6.19.1 Mutex Objects
mutex objects have following methods:


12. Internet Data Handling

asyncore-example.html | lib.html | module-sgmllib.html | Python Library Reference | contents.html | genindex.html
---
# 12. Internet Data Handling
This chapter describes modules which support handling data formats
commonly used on the internet. Some, like SGML and XML, may be useful
for other applications as well.


12.21.1 netrc Objects

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


11.8.1 NNTP Objects

module-nntplib.html | module-nntplib.html | module-smtplib.html | Python Library Reference | contents.html | genindex.html
---
## 11.8.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.


module-locale.html | module-locale.html | embedding-locale.html | Python Library Reference | contents.html | genindex.html
---
## 6.18.1 Background, details, hints, tips and caveats
The C standard defines the locale as a program-wide property that may
be relatively expensive to change. On top of that, some
implementation are broken in such a way that frequent locale changes
may cause core dumps. This makes the locale somewhat painful to use
correctly.
Initially, when a program is started, the locale is the "C" locale, no
matter what the user's preferred locale is. The program must
explicitly say that it wants the user's preferred locale settings by
calling `setlocale(LC_ALL, "")`.
It is generally a bad idea to call setlocale() in some library
routine, since as a side effect it affects the entire program. Saving
and restoring it is almost as bad: it is expensive and affects other
threads that happen to run before the settings have been restored.
If, when coding a module for general use, you need a locale
independent version of an operation that is affected by the locale
(e.g. string.lower(), or certain formats used with
time.strftime())), you will have to find a way to do it
without using the standard library routine. Even better is convincing
yourself that using locale settings is okay. Only as a last resort
should you document that your module is not compatible with
non-"C" locale settings.
The case conversion functions in the
string (module-string.html) and
strop modules are affected by the locale
settings. When a call to the setlocale() function changes
the LC_CTYPE settings, the variables
`string.lowercase`, `string.uppercase` and
`string.letters` (and their counterparts in strop) are
recalculated. Note that this code that uses these variable through
`from ... import ...', e.g. `from string
import letters`, is not affected by subsequent setlocale()
calls.
The only way to perform numeric operations according to the locale
is to use the special functions defined by this module:
atof(), atoi(), format(),
str().


7.14 zipfile -- Work with ZIP archives

module-gzip.html | someos.html | zipfile-objects.html | Python Library Reference | contents.html | genindex.html
---
# 7.14 zipfile --
Work with ZIP archives
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.
The available attributes of this module are:
See Also:
XXX point to ZIP format definition
XXX point to Info-ZIP home page; mention WiZ


8.15.1 Resource Limits

module-resource.html | module-resource.html | node201.html | Python Library Reference | contents.html | genindex.html
---
## 8.15.1 Resource Limits
Resources usage can be limited using the setrlimit() function
described below. Each resource is controlled by a pair of limits: a
soft limit and a hard limit. The soft limit is the current limit, and
may be lowered or raised by a process over time. The soft limit can
never exceed the hard limit. The hard limit can be lowered to any
value greater than the soft limit, but not raised. (Only processes with
the effective UID of the super-user can raise a hard limit.)
The specific resources that can be limited are system dependent. They
are described in the getrlimit(2) man page. The resources
listed below are supported when the underlying operating system
supports them; resources which cannot be checked or controlled by the
operating system are not defined in this module for those platforms.
These symbols define resources whose consumption can be controlled
using the setrlimit() and getrlimit() functions
described below. The values of these symbols are exactly the constants
used by C programs.
The Unix man page for getrlimit(2) lists the available
resources. Note that not all systems use the same symbol or same
value to denote the same resource.


8.15.2 Resource Usage

node200.html | module-resource.html | module-nis.html | Python Library Reference | contents.html | genindex.html
---
## 8.15.2 Resource Usage
These functiona are used to retrieve resource usage information:
The following RUSAGE_* symbols are passed to the
getrusage() function to specify which processes information
should be provided for.


9.2 How It Works

debugger-commands.html | module-pdb.html | profile.html | Python Library Reference | contents.html | genindex.html
---
# 9.2 How It Works
Some changes were made to the interpreter:
- `sys.settrace( func )` sets the global trace function
- there can also a local trace function (see later)
Trace functions have three arguments: frame, event, and
arg. frame is the current stack frame. event is a
string: `'call'`, `'line'`, `'return'` or
`'exception'`. arg depends on the event type.
The global trace function is invoked (with event set to
`'call'`) whenever a new local scope is entered; it should return
a reference to the local trace function to be used that scope, or
`None` if the scope shouldn't be traced.
The local trace function should return a reference to itself (or to
another function for further tracing in that scope), or `None` to
turn off tracing in that scope.
Instance methods are accepted (and very useful!) as trace functions.
The events have the following meaning:
`'call'`: A function is called (or some other code block entered). The global
trace function is called; arg is the argument list to the function;
the return value specifies the local trace function.
`'line'`: The interpreter is about to execute a new line of code (sometimes
multiple line events on one line exist). The local trace function is
called; arg in None; the return value specifies the new local trace
function.
`'return'`: A function (or other code block) is about to return. The local trace
function is called; arg is the value that will be returned. The trace
function's return value is ignored.
`'exception'`: An exception has occurred. The local trace function is called; arg is
a triple (exception, value, traceback); the return value specifies the
new local trace function
Note that as an exception is propagated down the chain of callers, an
`'exception'` event is generated at each level.
For more information on code and frame objects, refer to the
Python Reference Manual (../ref/ref.html).


11.1.3 Old classes

Using_the_cgi_module.html | module-cgi.html | Functions_in_cgi_module.html | Python Library Reference | contents.html | genindex.html
---
## 11.1.3 Old classes
These classes, present in earlier versions of the cgi module,
are still supported for backward compatibility. New applications
should use the FieldStorage class.
SvFormContentDict stores single value form content as
dictionary; it assumes each field name occurs in the form only once.
FormContentDict stores multiple value form content as a
dictionary (the form items are lists of values). Useful if your form
contains multiple fields with the same name.
Other classes (FormContent, InterpFormContentDict) are
present for backwards compatibility with really old applications only.
If you still use these and would be inconvenienced when they
disappeared from a next version of this module, drop me a note.


11.1.5 Caring about security

Functions_in_cgi_module.html | module-cgi.html | node229.html | Python Library Reference | contents.html | genindex.html
---
## 11.1.5 Caring about security
There's one important rule: if you invoke an external program (e.g.
via the os.system() or os.popen() functions),
make very sure you don't pass arbitrary strings received from the
client to the shell. This is a well-known security hole whereby
clever hackers anywhere on the web can exploit a gullible CGI script
to invoke arbitrary shell commands. Even parts of the URL or field
names cannot be trusted, since the request doesn't have to come from
your form!
To be on the safe side, if you must pass a string gotten from a form
to a shell command, you should make sure the string contains only
alphanumeric characters, dashes, underscores, and periods.