4.2.2 Matching vs. Searching

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

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


12.6.1 Message Objects

module-rfc822.html | module-rfc822.html | addresslist-objects.html | Python Library Reference | contents.html | genindex.html
---
## 12.6.1 Message Objects
A Message instance has the following methods:
Message instances also support a read-only mapping interface.
In particular: `m [name]` is like
`m .getheader(name)` but raises KeyError if
there is no matching header; and `len( m )`,
`m .has_key(name)`, `m .keys()`,
`m .values()` and `m .items()` act as expected
(and consistently).
Finally, Message instances have two public instance variables:


12.19.2 Folder Objects

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


12.19.3 Message Objects

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


12.19.1 MH Objects

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


module-mimetools.html | module-mimetools.html | module-MimeWriter.html | Python Library Reference | contents.html | genindex.html
---
## 12.7.1 Additional Methods of Message objects
The Message class defines the following methods in
addition to the rfc822.Message methods:


12.8.1 MimeWriter Objects

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


5. Miscellaneous Services

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


14. Multimedia Services

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


Module Index

node367.html | lib.html | genindex.html | Python Library Reference | contents.html | genindex.html
---
## Module Index
Some module names are followed by an annotation indicating what
platform they are available on.


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


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


16.1 al -- Audio functions on the SGI

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


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


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

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


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


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

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


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


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

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


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


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


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


5.5 bisect -- Array bisection algorithm

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


module-whichdb.html | someos.html | bsddb-objects.html | Python Library Reference | contents.html | genindex.html
---
# 7.11 bsddb --
Interface to Berkeley DB library
Availability: Unix, Windows.
The bsddb module provides an interface to the Berkeley DB
library. Users can create hash, btree or record based library files
using the appropriate open call. Bsddb objects behave generally like
dictionaries. Keys and values must be strings, however, so to use
other objects as keys or to store other kinds of objects the user must
serialize them somehow, typically using marshal.dumps or pickle.dumps.
The bsddb module is only available on Unix systems, so it
is not built by default in the standard Python distribution. Also,
there are two incompatible versions of the underlying library.
Version 1.85 is widely available, but has some known bugs. Version 2
is not quite as widely used, but does offer some improvements. The
bsddb module uses the 1.85 interface. Users wishing to use
version 2 of the Berkeley DB library will have to modify the source
for the module to include db_185.h instead of
db.h (db_185.h contains the version 1.85 compatibility
interface).
The bsddb module defines the following functions that create
objects that access the appropriate type of Berkeley DB file. The
first two arguments of each function are the same. For ease of
portability, only the first two arguments should be used in most
instances.
See Also:


3.33 __builtin__ -- Built-in functions

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


module-fileinput.html | misc.html | module-cmd.html | Python Library Reference | contents.html | genindex.html
---
# 5.9 calendar --
General calendar-related functions
This module allows you to output calendars like the Unix
cal program, and provides additional useful functions
related to the calendar.


16.3 cd -- CD-ROM access on SGI systems

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


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


module-SimpleHTTPServer.html | internet.html | module-asyncore.html | Python Library Reference | contents.html | genindex.html
---
# 11.15 CGIHTTPServer --
A Do-Something Request Handler
Availability: Unix.
The CGIHTTPServer module defines a request-handler class,
interface compatible with
BaseHTTPServer.BaseHTTPRequestHandler and inherits behaviour
from SimpleHTTPServer.SimpleHTTPRequestHandler but can also
run CGI scripts.
Note: This module is Unix dependent since it creates the
CGI process using os.fork() and os.exec().
The CGIHTTPServer module defines the following class:
The CGIHTTPRequestHandler defines the following data member:
The CGIHTTPRequestHandler defines the following methods:
Note that CGI scripts will be run with UID of user nobody, for security
reasons. Problems with the CGI script will be translated to error 403.
For example usage, see the implementation of the test()
function.


14.6 chunk -- Read IFF chunked data

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


module-math.html | misc.html | module-random.html | Python Library Reference | contents.html | genindex.html
---
# 5.2 cmath --
Mathematical functions for complex numbers
This module is always available. It provides access to mathematical
functions for complex numbers. The functions are:
The module also defines two mathematical constants:


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


3.23 code -- Interpreter base classes

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


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


3.24 codeop -- Compile Python code

console-objects.html | python.html | module-pprint.html | Python Library Reference | contents.html | genindex.html
---
# 3.24 codeop --
Compile Python code
The codeop module provides a function to compile Python code
with hints on whether it is certainly complete, possibly complete or
definitely incomplete. This is used by the code (module-code.html) module
and should not normally be used directly.
The codeop module defines the following function:


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


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

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


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


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

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


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

import copy

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


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


pickle-example.html | python.html | module-copyreg.html | Python Library Reference | contents.html | genindex.html
---
# 3.10 cPickle --
Alternate implementation of pickle
The cPickle module provides a similar interface and identical
functionality as the pickle (module-pickle.html) module,
but can be up to 1000 times faster since it is implemented in C. The
only other important difference to note is that Pickler()
and Unpickler() are functions and not classes, and so
cannot be subclassed. This should not be an issue in most cases.
The format of the pickle data is identical to that produced using the
pickle (module-pickle.html) module, so it is possible to use pickle (module-pickle.html) and
cPickle interchangably with existing pickles.


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


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


module-getpass.html | allos.html | curses-functions.html | Python Library Reference | contents.html | genindex.html
---
# 6.11 curses --
Terminal independant console handling
The curses module provides an interface to the curses Unix
library, the de-facto standard for portable advanced terminal
handling.
While curses is most widely used in the Unix environment, versions
are available for DOS, OS/2, and possibly other systems as well. The
extension module has not been tested with all available versions of
curses.
See Also:
Tutorial material on using curses with Python is available
on the Python Web site as Andrew Kuchling's
Curses
Programming with Python (http://www.python.org/doc/howto/curses/curses.html), at
http://www.python.org/doc/howto/curses/curses.html.


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


dl-objects.html | unix.html | module-gdbm.html | Python Library Reference | contents.html | genindex.html
---
# 8.6 dbm --
Simple ``database'' interface
Availability: Unix.
The dbm module provides an interface to the Unix
`(n)dbm` library. Dbm objects behave like mappings
(dictionaries), except that keys and values are always strings.
Printing a dbm object doesn't print the keys and values, and the
items() and values() methods are not supported.
See also the gdbm (module-gdbm.html) module, which
provides a similar interface using the GNU GDBM library.
The module defines the following constant and functions:


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


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


3.29 dis -- Disassembler.

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

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

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

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


module-crypt.html | unix.html | dl-objects.html | Python Library Reference | contents.html | genindex.html
---
# 8.5 dl --
Call C functions in shared objects
Availability: Unix.
The dl module defines an interface to the
dlopen() function, which is the most common interface on
Unix platforms for handling dynamically linked libraries. It allows
the program to call arbitary functions in such a library.
Note: This module will not work unless
```text

sizeof(int) == sizeof(long) == sizeof(char *)
```
If this is not the case, SystemError will be raised on
import.
The dl module defines the following function:
The dl module defines the following constants:
The dl module defines the following exception:
Example:
```text

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


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


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


2.2 Built-in Exceptions

specialattrs.html | builtin.html | built-in-funcs.html | Python Library Reference | contents.html | genindex.html
---
# 2.2 Built-in Exceptions
Exceptions can be class objects or string objects. While
traditionally, most exceptions have been string objects, in Python
1.5, all standard exceptions have been converted to class objects,
and users are encouraged to do the same. The source code for those
exceptions is present in the standard library module
exceptions; this module never needs to be imported explicitly.
Two distinct string objects with the same value are considered different
exceptions. This is done to force programmers to use exception names
rather than their string value when specifying exception handlers.
The string value of all built-in exceptions is their name, but this is
not a requirement for user-defined exceptions or exceptions defined by
library modules.
For class exceptions, in a try statement with
an except clause that mentions a particular
class, that clause also handles any exception classes derived from
that class (but not exception classes from which it is
derived). Two exception classes that are not related via subclassing
are never equivalent, even if they have the same name.
The built-in exceptions listed below can be generated by the
interpreter or built-in functions. Except where mentioned, they have
an ``associated value'' indicating the detailed cause of the error.
This may be a string or a tuple containing several items of
information (e.g., an error code and a string explaining the code).
The associated value is the second argument to the
raise statement. For string exceptions, the
associated value itself will be stored in the variable named as the
second argument of the except clause (if any). For class
exceptions, that variable receives the exception instance. If the
exception class is derived from the standard root class
Exception, the associated value is present as the
exception instance's args attribute, and possibly on other
attributes as well.
User code can raise built-in exceptions. This can be used to test an
exception handler or to report an error condition ``just like'' the
situation in which the interpreter raises the same exception; but
beware that there is nothing to prevent user code from raising an
inappropriate error.
The following exceptions are only used as base classes for other
exceptions.
The following exceptions are the exceptions that are actually raised.
They are class objects, except when the -X option is used
to revert back to string-based standard exceptions.


module-pty.html | unix.html | module-pipes.html | Python Library Reference | contents.html | genindex.html
---
# 8.12 fcntl --
The fcntl() and ioctl() system calls
Availability: Unix.
This module performs file control and I/O control on file descriptors.
It is an interface to the fcntl() and ioctl()
Unix routines. File descriptors can be obtained with the
fileno() method of a file or socket object.
The module defines the following functions:
If the library modules FCNTL or
IOCTL are missing, you can find the
opcodes in the C include files `<sys/fcntl.h>` and
`<sys/ioctl.h>`. You can create the modules yourself with the
h2py script, found in the Tools/scripts/ directory.
Examples (all on a SVR4 compliant system):
```text

import struct, fcntl, FCNTL

file = open(...)
rv = fcntl(file.fileno(), FCNTL.O_NDELAY, 1)

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


6.7 filecmp -- File Comparisons

module-statvfs.html | allos.html | module-time.html | Python Library Reference | contents.html | genindex.html
---
# 6.7 filecmp --
File Comparisons
The filecmp module defines a function to compare files, taking all
sort of short-cuts to make it a highly efficient operation.
The filecmp module defines the following function:
Example:


ConfigParser-objects.html | misc.html | module-calendar.html | Python Library Reference | contents.html | genindex.html
---
# 5.8 fileinput --
Iterate over lines from multiple input streams
This module implements a helper class and functions to quickly write a
loop over standard input or a list of files.
The typical use is:
```text

import fileinput
for line in fileinput.input():
process(line)
```
This iterates over the lines of all files listed in
`sys.argv[1:]`, defaulting to `sys.stdin` if the list is
empty. If a filename is `'-'`, it is also replaced by
`sys.stdin`. To specify an alternative list of filenames, pass
it as the first argument to input(). A single file name is
also allowed.
All files are opened in text mode. If an I/O error occurs during
opening or reading a file, IOError is raised.
If `sys.stdin` is used more than once, the second and further use
will return no lines, except perhaps for interactive use, or if it has
been explicitly reset (e.g. using `sys.stdin.seek(0)`).
Empty files are opened and immediately closed; the only time their
presence in the list of filenames is noticeable at all is when the
last file opened is empty.
It is possible that the last line of a file does not end in a newline
character; lines are returned including the trailing newline when it
is present.
The following function is the primary interface of this module:
The following functions use the global state created by
input(); if there is no active state,
RuntimeError is raised.
The class which implements the sequence behavior provided by the
module is available for subclassing as well:
Optional in-place filtering: if the keyword argument
`inplace =1` is passed to input() or to the
FileInput constructor, the file is moved to a backup file and
standard output is directed to the input file.
This makes it possible to write a filter that rewrites its input file
in place. If the keyword argument `backup ='.<some
extension>'` is also given, it specifies the extension for the backup
file, and the backup file remains around; by default, the extension is
`'.bak'` and it is deleted when the output file is closed. In-place
filtering is disabled when standard input is read.


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

import fl
from FL import *
```


cd-parser-objects.html | sgi.html | FL_Functions.html | Python Library Reference | contents.html | genindex.html
---
# 16.4 fl --
FORMS library interface for GUI applications
Availability: IRIX.
This module provides an interface to the FORMS Library by Mark Overmars. The source for the
library can be retrieved by anonymous ftp from host
"ftp.cs.ruu.nl", directory SGI/FORMS. It was last tested
with version 2.0b.
Most functions are literal translations of their C equivalents,
dropping the initial "fl_" from their name. Constants used by
the library are defined in module FL (module-fl-constants.html)
described below.
The creation of objects is a little different in Python than in C:
instead of the `current form' maintained by the library to which new
FORMS objects are added, all functions that add a FORMS object to a
form are methods of the Python object representing the form.
Consequently, there are no Python equivalents for the C functions
fl_addto_form() and fl_end_form(), and the
equivalent of fl_bgn_form() is called
fl.make_form().
Watch out for the somewhat confusing terminology: FORMS uses the word
object for the buttons, sliders etc. that you can place in a form.
In Python, `object' means any value. The Python interface to FORMS
introduces two new Python object types: form objects (representing an
entire form) and FORMS objects (representing one button, slider etc.).
Hopefully this isn't too confusing.
There are no `free objects' in the Python interface to FORMS, nor is
there an easy way to add object classes written in Python. The FORMS
interface to GL event handling is available, though, so you can mix
FORMS with pure GL windows.
Please note: importing fl implies a call to the GL
function foreground() and to the FORMS routine
fl_init().


module-fl-constants.html | sgi.html | module-fm.html | Python Library Reference | contents.html | genindex.html
---
# 16.6 flp --
Functions for loading stored FORMS designs
Availability: IRIX.
This module defines functions that can read form definitions created
by the `form designer' (fdesign) program that comes with the
FORMS library (see module fl (module-fl.html) above).
For now, see the file flp.doc in the Python library source
directory for a description.


16.7 fm -- Font Manager interface

module-flp.html | sgi.html | module-gl.html | Python Library Reference | contents.html | genindex.html
---
# 16.7 fm --
Font Manager interface
Availability: IRIX.
This module provides access to the IRIS Font Manager library.
It is available only on Silicon Graphics machines.
See also: 4Sight User's Guide, section 1, chapter 5: ``Using
the IRIS Font Manager.''
This is not yet a full interface to the IRIS Font Manager.
Among the unsupported features are: matrix operations; cache
operations; character operations (use string operations instead); some
details of font info; individual glyph metrics; and printer matching.
It supports the following operations:
Font handle objects support the following operations:


module-glob.html | allos.html | module-shutil.html | Python Library Reference | contents.html | genindex.html
---
# 6.16 fnmatch --
Unix filename pattern matching
This module provides support for Unix shell-style wildcards, which
are not the same as regular expressions (which are documented
in the re (module-re.html) module). The special
characters used in shell-style wildcards are:
Note that the filename separator (`'/'` on Unix) is not
special to this module. See module
glob (module-glob.html) for pathname expansion
(glob (module-glob.html) uses fnmatch() to match pathname
segments). Similarly, filenames starting with a period are
not special for this module, and are matched by the `*` and
`?` patterns.


xml-namespace.html | netdata.html | formatter-interface.html | Python Library Reference | contents.html | genindex.html
---
# 12.5 formatter --
Generic output formatting
This module supports two interface definitions, each with mulitple
implementations. The formatter interface is used by the
HTMLParser class of the htmllib (module-htmllib.html) module, and the
writer interface is required by the formatter interface.
Formatter objects transform an abstract flow of formatting events into
specific output events on writer objects. Formatters manage several
stack structures to allow various properties of a writer object to be
changed and restored; writers need not be able to handle relative
changes nor any sort of ``change back'' operation. Specific writer
properties which may be controlled via formatter objects are
horizontal alignment, font, and left margin indentations. A mechanism
is provided which supports providing arbitrary, non-exclusive style
settings to a writer as well. Additional interfaces facilitate
formatting events which are not reversible, such as paragraph
separation.
Writer objects encapsulate device interfaces. Abstract devices, such
as file formats, are supported as well as physical devices. The
provided implementations all work with abstract devices. The
interface makes available mechanisms for setting the properties which
formatter objects manage and inserting data into the output.


module-struct.html | strings.html | module-StringIO.html | Python Library Reference | contents.html | genindex.html
---
# 4.6 fpformat --
Floating point conversions
The fpformat module defines functions for dealing with
floating point numbers representations in 100% pure
Python. Note: This module is unneeded: everything here could
be done via the `%` string interpolation operator.
The fpformat module defines the following functions and an
exception:
Example:


11.4 ftplib -- FTP protocol client

HTTP_Example.html | internet.html | ftp-objects.html | Python Library Reference | contents.html | genindex.html
---
# 11.4 ftplib --
FTP protocol client
This module defines the class FTP and a few related items.
The FTP class implements the client side of the FTP
protocol. You can use this to write Python
programs that perform a variety of automated FTP jobs, such as
mirroring other ftp servers. It is also used by the module
urllib (module-urllib.html) to handle URLs that use FTP. For more information
on FTP (File Transfer Protocol), see Internet RFC 959 (http://www.ietf.org/rfc/rfc0959.txt).
Here's a sample session using the ftplib module:
```text

>>> from ftplib import FTP
>>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
>>> ftp.login() # user anonymous, passwd user@hostname
>>> ftp.retrlines('LIST') # list directory contents
total 24418
drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .
dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 ..
-rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX
.
.
.
>>> ftp.retrbinary('RETR README', open('README', 'wb').write)
'226 Transfer complete.'
>>> ftp.quit()
```
The module defines the following items:
See Also:
The file Tools/scripts/ftpmirror.py
in the Python source distribution is a script that can mirror
FTP sites, or portions thereof, using the ftplib module.
It can be used as an extended example that applies this module.


module-dbm.html | unix.html | module-termios.html | Python Library Reference | contents.html | genindex.html
---
# 8.7 gdbm --
GNU's reinterpretation of dbm
Availability: Unix.
This module is quite similar to the dbm (module-dbm.html)
module, but uses `gdbm` instead to provide some additional
functionality. Please note that the file formats created by
`gdbm` and `dbm` are incompatible.
The gdbm module provides an interface to the GNU DBM
library. `gdbm` objects behave like mappings
(dictionaries), except that keys and values are always strings.
Printing a `gdbm` object doesn't print the keys and values, and
the items() and values() methods are not supported.
The module defines the following constant and functions:
In addition to the dictionary-like methods, `gdbm` objects have the
following methods:


curses-window-objects.html | allos.html | module-tempfile.html | Python Library Reference | contents.html | genindex.html
---
# 6.12 getopt --
Parser for command line options.
This module helps scripts to parse the command line arguments in
`sys.argv`.
It supports the same conventions as the Unix getopt()
function (including the special meanings of arguments of the form
``-`' and ``-``-`').
Long options similar to those supported by
GNU software may be used as well via an optional third argument.
This module provides a single function and an exception:
An example using only Unix style options:
```text

>>> import getopt, string
>>> args = string.split('-a -b -cfoo -d bar a1 a2')
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
>>>
```
Using long option names is equally easy:


6.10 getpass -- Portable password input

scheduler-objects.html | allos.html | module-curses.html | Python Library Reference | contents.html | genindex.html
---
# 6.10 getpass
-- Portable password input
The getpass module provides two functions:


module-DEVICE.html | sgi.html | module-imgfile.html | Python Library Reference | contents.html | genindex.html
---
# 16.10 GL --
Constants used with the gl module
Availability: IRIX.


16.8 gl -- Graphics Library interface

module-fm.html | sgi.html | module-DEVICE.html | Python Library Reference | contents.html | genindex.html
---
# 16.8 gl --
Graphics Library interface
Availability: IRIX.
This module provides access to the Silicon Graphics
Graphics Library.
It is available only on Silicon Graphics machines.
Warning:
Some illegal calls to the GL library cause the Python interpreter to dump
core.
In particular, the use of most GL calls is unsafe before the first
window is opened.
The module is too large to document here in its entirety, but the
following should help you to get started.
The parameter conventions for the C functions are translated to Python as
follows:
- All (short, long, unsigned) int values are represented by Python
integers.
- All float and double values are represented by Python floating point
numbers.
In most cases, Python integers are also allowed.
- All arrays are represented by one-dimensional Python lists.
In most cases, tuples are also allowed.
- All string and character arguments are represented by Python strings,
for instance,
`winopen('Hi There!')`and
`rotate(900, 'z')`.
- All (short, long, unsigned) integer arguments or return values that are
only used to specify the length of an array argument are omitted.
For example, the C call
```text

lmdef(deftype, index, np, props)
```
is translated to Python as
```text

lmdef(deftype, index, props)
```
- Output arguments are omitted from the argument list; they are
transmitted as function return values instead.
If more than one value must be returned, the return value is a tuple.
If the C function has both a regular return value (that is not omitted
because of the previous rule) and an output argument, the return value
comes first in the tuple.
Examples: the C call
```text

getmcolor(i, &red, &green, &blue)
```
is translated to Python as
```text

red, green, blue = getmcolor(i)
```
The following functions are non-standard or have special argument
conventions:
Here is a tiny but complete example GL program in Python:
```text

import gl, GL, time

def main():
gl.foreground()
gl.prefposition(500, 900, 500, 900)
w = gl.winopen('CrissCross')
gl.ortho2(0.0, 400.0, 0.0, 400.0)
gl.color(GL.WHITE)
gl.clear()
gl.color(GL.RED)
gl.bgnline()
gl.v2f(0.0, 0.0)
gl.v2f(400.0, 400.0)
gl.endline()
gl.bgnline()
gl.v2f(400.0, 0.0)
gl.v2f(0.0, 400.0)
gl.endline()
time.sleep(5)

main()
```
See Also:
An interface to OpenGL is also available; see
information about David Ascher's
PyOpenGL online at
http://starship.python.net/crew/da/PyOpenGL/. This may
be a better option if support for SGI hardware from before about
1996 is not required.


module-errno.html | allos.html | module-fnmatch.html | Python Library Reference | contents.html | genindex.html
---
# 6.15 glob --
Unix style pathname pattern expansion
The glob module finds all the pathnames matching a specified
pattern according to the rules used by the Unix shell. No tilde
expansion is done, but `*`, `?`, and character ranges
expressed with `[]` will be correctly matched. This is done by
using the os.listdir() and fnmatch.fnmatch()
functions in concert, and not by actually invoking a subshell. (For
tilde and shell variable expansion, use os.path.expanduser()
and os.path.expandvars().)
For example, consider a directory containing only the following files:
1.gif, 2.txt, and card.gif. glob()
will produce the following results. Notice how any leading components
of the path are preserved.
```text

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
```


ftp-objects.html | internet.html | module-poplib.html | Python Library Reference | contents.html | genindex.html
---
# 11.5 gopherlib --
Gopher protocol client
This module provides a minimal implementation of client side of the
the Gopher protocol. It is used by the module urllib (module-urllib.html) to
handle URLs that use the Gopher protocol.
The module defines the following functions:


8.3 grp -- The group database

module-pwd.html | unix.html | module-crypt.html | Python Library Reference | contents.html | genindex.html
---
# 8.3 grp --
The group database
Availability: Unix.
This module provides access to the Unix group database.
It is available on all Unix versions.
Group database entries are reported as 4-tuples containing the
following items from the group database (see `<grp.h>`), in order:
The gid is an integer, name and password are strings, and the member
list is a list of strings.
(Note that most users are not explicitly listed as members of the
group they are in according to the password database.)
KeyError is raised if the entry asked for cannot be found.
It defines the following items:


7.13 gzip -- Support for gzip files

module-zlib.html | someos.html | node175.html | Python Library Reference | contents.html | genindex.html
---
# 7.13 gzip --
Support for gzip files
The data compression provided by the `zlib` module is compatible
with that used by the GNU compression program gzip.
Accordingly, the gzip module provides the GzipFile
class to read and write gzip-format files, automatically
compressing or decompressing the data so it looks like an ordinary
file object. Note that additional file formats which can be
decompressed by the gzip and gunzip programs, such
as those produced by compress and pack, are not
supported by this module.
The module defines the following items:


html-parser-objects.html | netdata.html | module-xmllib.html | Python Library Reference | contents.html | genindex.html
---
# 12.3 htmlentitydefs --
Definitions of HTML general entities
This module defines a single dictionary, `entitydefs`, which is
used by the htmllib (module-htmllib.html) module to provide the
entitydefs member of the HTMLParser class. The
definition provided here contains all the entities defined by HTML 2.0
that can be handled using simple textual substitution in the Latin-1
character set (ISO-8859-1).


module-sgmllib.html | netdata.html | html-parser-objects.html | Python Library Reference | contents.html | genindex.html
---
# 12.2 htmllib --
A parser for HTML documents
This module defines a class which can serve as a base for parsing text
files formatted in the HyperText Mark-up Language (HTML). The class
is not directly concerned with I/O -- it must be provided with input
in string form via a method, and makes calls to methods of a
``formatter'' object in order to produce output. The
HTMLParser class is designed to be used as a base class for
other classes in order to add functionality, and allows most of its
methods to be extended or overridden. In turn, this class is derived
from and extends the SGMLParser class defined in module
sgmllib (module-sgmllib.html). The HTMLParser
implementation supports the HTML 2.0 language as described in
RFC 1866 (http://www.ietf.org/rfc/rfc1866.txt). Two implementations of formatter objects are provided in
the formatter (module-formatter.html) module; refer to the
documentation for that module for information on the formatter
interface.
The following is a summary of the interface defined by
sgmllib.SGMLParser:
- The interface to feed data to an instance is through the feed()
method, which takes a string argument. This can be called with as
little or as much text at a time as desired; "p.feed(a);
p.feed(b)" has the same effect as "p.feed(a+b)". When the data
contains complete HTML tags, these are processed immediately;
incomplete elements are saved in a buffer. To force processing of all
unprocessed data, call the close() method.
For example, to parse the entire contents of a file, use:
```text

parser.feed(open('myfile.html').read())
parser.close()
```
- The interface to define semantics for HTML tags is very simple: derive
a class and define methods called start_tag(),
end_tag(), or do_tag(). The parser will
call these at appropriate moments: start_tag or
do_tag() is called when an opening tag of the form
`< tag ...>` is encountered; end_tag() is called
when a closing tag of the form `< tag >` is encountered. If
an opening tag requires a corresponding closing tag, like `<H1>`... `</H1>`, the class should define the start_tag()
method; if a tag requires no closing tag, like `<P>`, the class
should define the do_tag() method.
The module defines a single class:
See Also:


11.3 httplib -- HTTP protocol client

Urllib_Examples.html | internet.html | node237.html | Python Library Reference | contents.html | genindex.html
---
# 11.3 httplib --
HTTP protocol client
This module defines a class which implements the client side of the
HTTP protocol. It is normally not used directly -- the module
urllib (module-urllib.html) uses it to handle URLs that
use HTTP.
The module defines one class, HTTP:


module-audioop.html | mmedia.html | module-aifc.html | Python Library Reference | contents.html | genindex.html
---
# 14.2 imageop --
Manipulate raw image data
The imageop module contains some useful operations on images.
It operates on images consisting of 8 or 32 bit pixels stored in
Python strings. This is the same format as used by
gl.lrectwrite() and the imgfile (module-imgfile.html) module.
The module defines the following variables and functions:


11.7 imaplib -- IMAP4 protocol client

pop3-example.html | internet.html | imap4-objects.html | Python Library Reference | contents.html | genindex.html
---
# 11.7 imaplib --
IMAP4 protocol client
This module defines a class, IMAP4, which encapsulates a
connection to an IMAP4 server and implements the IMAP4rev1 client
protocol as defined in RFC 2060 (http://www.ietf.org/rfc/rfc2060.txt). It is backward compatible with
IMAP4 (RFC 1730 (http://www.ietf.org/rfc/rfc1730.txt)) servers, but note that the "STATUS" command is
not supported in IMAP4.
A single class is provided by the imaplib module:
Two exceptions are defined as attributes of the IMAP4 class:
The following utility functions are defined:
Note that IMAP4 message numbers change as the mailbox changes, so it
is highly advisable to use UIDs instead, with the UID command.
At the end of the module, there is a test section that contains a more
extensive example of usage.
See Also:
Documents describing the protocol, and sources and binaries
for servers implementing it, can all be found at the
University of Washington's IMAP Information Center
(http://www.cac.washington.edu/imap/).


module-gl-constants.html | sgi.html | module-jpeg.html | Python Library Reference | contents.html | genindex.html
---
# 16.11 imgfile --
Support for SGI imglib files
Availability: IRIX.
The imgfile 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
is enough in some cases. Currently, colormap files are not supported.
The module defines the following variables and functions:


module-rgbimg.html | mmedia.html | module-sndhdr.html | Python Library Reference | contents.html | genindex.html
---
# 14.9 imghdr --
Determine the type of an image.
The imghdr module determines the type of image contained in a
file or byte stream.
The imghdr module defines the following function:
The following image types are recognized, as listed below with the
return value from what():
You can extend the list of file types imghdr can recognize by
appending to this variable:
Example:


3.15 imp -- Access the import internals

module-marshal.html | python.html | examples-imp.html | Python Library Reference | contents.html | genindex.html
---
# 3.15 imp --
Access the import internals
This module provides an interface to the mechanisms
used to implement the import statement. It defines the
following constants and functions:
The following constants with integer values, defined in this module,
are used to indicate the search result of find_module().
The following constant and functions are obsolete; their functionality
is available through find_module() or load_module().
They are kept around for backward compatibility:


16.12 jpeg -- Read and write JPEG files

module-imgfile.html | sgi.html | sunos.html | Python Library Reference | contents.html | genindex.html
---
# 16.12 jpeg --
Read and write JPEG files
Availability: IRIX.
The module jpeg provides access to the jpeg compressor and
decompressor written by the Independent JPEG Group
(IJG). JPEG is a standard for
compressing pictures; it is defined in ISO 10918. For details on JPEG
or the Independent JPEG Group software refer to the JPEG standard or
the documentation provided with the software.
A portable interface to JPEG image files is available with the Python
Imaging Library (PIL) by Fredrik Lundh. Information on PIL is
available at http://www.pythonware.com/products/pil/.
The jpeg module defines an exception and some functions.
See Also:
JPEG Still Image Data Compression Standard, by
Pennebaker and Mitchell, is the canonical reference for the JPEG
image format.
The ISO standard for JPEG is also published as ITU T.81.
This is available in PDF form at
http://www.w3.org/Graphics/JPEG/itu-t81.pdf.


module-token.html | python.html | module-tokenize.html | Python Library Reference | contents.html | genindex.html
---
# 3.19 keyword --
Testing for Python keywords
This module allows a Python program to determine if a string is a
keyword. A single function is provided:


traceback-example.html | python.html | module-pickle.html | Python Library Reference | contents.html | genindex.html
---
# 3.8 linecache --
Random access to text lines
The linecache module allows one to get any line from any file,
while attempting to optimize internally, using a cache, the common case
where many lines are read from a single file. This is used by the
traceback (module-traceback.html) module to retrieve source lines for inclusion in
the formatted traceback.
The linecache module defines the following functions:
Example:


shutil-example.html | allos.html | node145.html | Python Library Reference | contents.html | genindex.html
---
# 6.18 locale --
Internationalization services
The locale module opens access to the POSIX locale database
and functionality. The POSIX locale mechanism allows programmers
to deal with certain cultural issues in an application, without
requiring the programmer to know all the specifics of each country
where the software is executed.
The locale module is implemented on top of the
_locale module, which in turn uses an
ANSI C locale implementation if available.
The locale module defines the following exception and
functions:
Example:
```text

>>> import locale
>>> loc = locale.setlocale(locale.LC_ALL) # get current locale
>>> locale.setlocale(locale.LC_ALL, "de") # use German locale
>>> locale.strcoll("f\344n", "foo") # compare a string containing an umlaut
>>> locale.setlocale(locale.LC_ALL, "") # use user's preferred locale
>>> locale.setlocale(locale.LC_ALL, "C") # use default (C) locale
>>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale
```


module-quopri.html | netdata.html | mailbox-objects.html | Python Library Reference | contents.html | genindex.html
---
# 12.18 mailbox --
Read various mailbox formats
This module defines a number of classes that allow easy and uniform
access to mail messages in a (Unix) mailbox.


12.14 mailcap -- Mailcap file handling.

xdr-exceptions.html | netdata.html | module-mimetypes.html | Python Library Reference | contents.html | genindex.html
---
# 12.14 mailcap --
Mailcap file handling.
Mailcap files are used to configure how MIME-aware applications such
as mail readers and Web browsers react to files with different MIME
types. (The name ``mailcap'' is derived from the phrase ``mail
capability''.) For example, a mailcap file might contain a line like
"video/mpeg; xmpeg %s". Then, if the user encounters an email
message or Web document with the MIME type video/mpeg,
"%s" will be replaced by a filename (usually one belonging to a
temporary file) and the xmpeg program can be automatically
started to view the file.
The mailcap format is documented in RFC 1524 (http://www.ietf.org/rfc/rfc1524.txt), ``A User Agent
Configuration Mechanism For Multimedia Mail Format Information,'' but
is not an Internet standard. However, mailcap files are supported on
most Unix systems.


module-builtin.html | python.html | strings.html | Python Library Reference | contents.html | genindex.html
---
# 3.34 __main__ --
Top-level script environment.
This module represents the (otherwise anonymous) scope in which the
interpreter's main program executes -- commands read either from
standard input or from a script file.


module-copy.html | python.html | module-imp.html | Python Library Reference | contents.html | genindex.html
---
# 3.14 marshal --
Alternate Python object serialization
This module contains functions that can read and write Python
values in a binary format. The format is specific to Python, but
independent of machine architecture issues (e.g., you can write a
Python value to a file on a PC, transport the file to a Sun, and read
it back there). Details of the format are undocumented on purpose;
it may change between Python versions (although it rarely
does).3.1 (#foot5464)
This is not a general ``persistency'' module. For general persistency
and transfer of Python objects through RPC calls, see the modules
pickle (module-pickle.html) and shelve (module-shelve.html). The marshal module exists
mainly to support reading and writing the ``pseudo-compiled'' code for
Python modules of .pyc files.
Not all Python object types are supported; in general, only objects
whose value is independent from a particular invocation of Python can
be written and read by this module. The following types are supported:
`None`, integers, long integers, floating point numbers,
strings, Unicode objects, tuples, lists, dictionaries, and code
objects, where it should be understood that tuples, lists and
dictionaries are only supported as long as the values contained
therein are themselves supported; and recursive lists and dictionaries
should not be written (they will cause infinite loops).
Caveat: On machines where C's `long int` type has more than
32 bits (such as the DEC Alpha), it
is possible to create plain Python integers that are longer than 32
bits. Since the current marshal module uses 32 bits to
transfer plain Python integers, such values are silently truncated.
This particularly affects the use of very long integer literals in
Python modules -- these will be accepted by the parser on such
machines, but will be silently be truncated when the module is read
from the .pyc instead.3.2 (#foot5517)
There are functions that read/write files as well as functions
operating on strings.
The module defines these functions:


5.1 math -- Mathematical functions

misc.html | misc.html | module-cmath.html | Python Library Reference | contents.html | genindex.html
---
# 5.1 math --
Mathematical functions
This module is always available. It provides access to the
mathematical functions defined by the C standard.
These functions cannot be used with complex numbers; use the functions
of the same name from the cmath (module-cmath.html) module if you require
support for complex numbers. The distinction between functions which
support complex numbers and those which don't is made since most users
do not want to learn quite as much mathematics as required to
understand complex numbers. Receiving an exception instead of a
complex result allows earlier detection of the unexpected complex
number used as a parameter, so that the programmer can determine how
and why it was generated in the first place.
The following functions provided by this module:
Note that frexp() and modf() have a different
call/return pattern than their C equivalents: they take a single
argument and return a pair of values, rather than returning their
second return value through an `output parameter' (there is no such
thing in Python).
The module also defines two mathematical constants:


crypto.html | crypto.html | module-sha.html | Python Library Reference | contents.html | genindex.html
---
# 15.1 md5 --
MD5 message digest algorithm
This module implements the interface to RSA's MD5 message digest
algorithm (see also Internet RFC 1321 (http://www.ietf.org/rfc/rfc1321.txt)). Its use is quite
straightforward: use the new() to create an md5 object.
You can now feed this object with arbitrary strings using the
update() method, and at any point you can ask it for the
digest (a strong kind of 128-bit checksum,
a.k.a. ``fingerprint'') of the contatenation of the strings fed to it
so far using the digest() method.
For example, to obtain the digest of the string `'Nobody inspects
the spammish repetition'`:
```text

>>> import md5
>>> m = md5.new()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
```
More condensed:
```text

>>> md5.new("Nobody inspects the spammish repetition").digest()
'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
```
An md5 object has the following methods:


12.19 mhlib -- Access to MH mailboxes

mailbox-objects.html | netdata.html | mh-objects.html | Python Library Reference | contents.html | genindex.html
---
# 12.19 mhlib --
Access to MH mailboxes
The mhlib module provides a Python interface to MH folders and
their contents.
The module contains three basic classes, MH, which represents a
particular collection of folders, Folder, which represents a single
folder, and Message, which represents a single message.


addresslist-objects.html | netdata.html | mimetools.Message_Methods.html | Python Library Reference | contents.html | genindex.html
---
# 12.7 mimetools --
Tools for parsing MIME messages
This module defines a subclass of the
rfc822 (module-rfc822.html) module's
Message class and a number of utility functions that are
useful for the manipulation for MIME multipart or encoded message.
It defines the following items:
See Also:


module-mailcap.html | netdata.html | module-base64.html | Python Library Reference | contents.html | genindex.html
---
# 12.15 mimetypes --
Map filenames to MIME types
The mimetypes converts between a filename or URL and the MIME
type associated with the filename extension. Conversions are provided
from filename to MIME type and from MIME type to filename extension;
encodings are not supported for the later conversion.
The functions described below provide the primary interface for this
module. If the module has not been initialized, they will call
init().
Some additional functions and data items are available for controlling
the behavior of the module.


mimetools.Message_Methods.html | netdata.html | MimeWriter-objects.html | Python Library Reference | contents.html | genindex.html
---
# 12.8 MimeWriter --
Generic MIME file writer
This module defines the class MimeWriter. The
MimeWriter class implements a basic formatter for creating
MIME multi-part files. It doesn't seek around the output file nor
does it use large amounts of buffer space. You must write the parts
out in the order that they should occur in the final
file. MimeWriter does buffer the headers you add, allowing you
to rearrange their order.


mh-message-objects.html | netdata.html | module-netrc.html | Python Library Reference | contents.html | genindex.html
---
# 12.20 mimify --
MIME processing of mail messages
The mimify module defines two functions to convert mail messages to
and from MIME format. The mail message can be either a simple message
or a so-called multipart message. Each part is treated separately.
Mimifying (a part of) a message entails encoding the message as
quoted-printable if it contains any characters that cannot be
represented using 7-bit ASCII. Unmimifying (a part of) a message
entails undoing the quoted-printable encoding. Mimify and unmimify
are especially useful when a message has to be edited before being
sent. Typical use would be:
```text

unmimify message
edit message
mimify message
send message
```
The modules defines the following user-callable functions and
user-settable variables:
This module can also be used from the command line. Usage is as
follows:
```text

mimify.py -e [-l length] [infile [outfile]]
mimify.py -d [-b] [infile [outfile]]
```
to encode (mimify) and decode (unmimify) respectively. infile
defaults to standard input, outfile defaults to standard output.
The same file can be specified for input and output.
If the -l option is given when encoding, if there are any lines
longer than the specified length, the containing part will be
encoded.
If the -b option is given when decoding, any base64 parts will
be decoded as well.


module-sha.html | crypto.html | module-rotor.html | Python Library Reference | contents.html | genindex.html
---
# 15.3 mpz --
GNU arbitrary magnitude integers
This is an optional module. It is only available when Python is
configured to include it, which requires that the GNU MP software is
installed.
This module implements the interface to part of the GNU MP library,
which defines arbitrary precision integer and rational number
arithmetic routines. Only the interfaces to the integer
(mpz_*()) routines are provided. If not stated
otherwise, the description in the GNU MP documentation can be applied.
Support for rational numbers can be
implemented in Python. For an example, see the
Rat module, provided as
Demos/classes/Rat.py in the Python source distribution.
In general, mpz-numbers can be used just like other standard
Python numbers, e.g., you can use the built-in operators like `+`,
`*`, etc., as well as the standard built-in functions like
abs(), int(), ..., divmod(),
pow(). Please note: the bitwise-xor
operation has been implemented as a bunch of ands,
inverts and ors, because the library lacks an
mpz_xor() function, and I didn't need one.
You create an mpz-number by calling the function mpz() (see
below for an exact description). An mpz-number is printed like this:
`mpz( value )`.
A number of extra functions are defined in this module. Non
mpz-arguments are converted to mpz-values first, and the functions
return mpz-numbers.
An mpz-number has one method:


node355.html | node355.html | msvcrt-files.html | Python Library Reference | contents.html | genindex.html
---
# 18.1 msvcrt -
Useful routines from the MS VC++ runtime
Availability: Windows.
These functions provide access to some useful capabilities on Windows
platforms. Some higher-level modules use these functions to build the
Windows implementations of their services. For example, the
getpass (module-getpass.html) module uses this in the implementation of the
getpass() function.
Further documentation on these functions can be found in the Platform
API documentation.


MimeWriter-objects.html | netdata.html | MultiFile-objects.html | Python Library Reference | contents.html | genindex.html
---
# 12.9 multifile --
Support for files containing distinct parts
The MultiFile object enables you to treat sections of a text
file as file-like input objects, with `''` being returned by
readline() when a given delimiter pattern is encountered. The
defaults of this class are designed to make it useful for parsing
MIME multipart messages, but by subclassing it and overriding methods
it can be easily adapted for more general use.
It will be useful to know that in MultiFile's view of the world, text
is composed of three kinds of lines: data, section-dividers, and
end-markers. MultiFile is designed to support parsing of
messages that may have multiple nested message parts, each with its
own pattern for section-divider and end-marker lines.


6.19 mutex -- Mutual exclusion support

embedding-locale.html | allos.html | mutex-objects.html | Python Library Reference | contents.html | genindex.html
---
# 6.19 mutex --
Mutual exclusion support
The mutex defines a class that allows mutual-exclusion
via aquiring and releasing locks. It does not require (or imply)
threading or multi-tasking, though it could be useful for
those purposes.
The mutex module defines the following class:


12.21 netrc -- netrc file processing

module-mimify.html | netdata.html | netrc-objects.html | Python Library Reference | contents.html | genindex.html
---
# 12.21 netrc --
netrc file processing
New in version 1.5.2.
The netrc class parses and encapsulates the netrc file format
used by the Unix ftp program and other FTP clients.


bytecodes.html | python.html | module-site.html | Python Library Reference | contents.html | genindex.html
---
# 3.30 new --
Runtime implementation object creation
The new module allows an interface to the interpreter object
creation functions. This is for use primarily in marshal-type functions,
when a new object needs to be created ``magically'' and not by using the
regular creation functions. This module provides a low-level interface
to the interpreter, so care must be exercised when using this module.
The new module defines the following functions:


node201.html | unix.html | module-syslog.html | Python Library Reference | contents.html | genindex.html
---
# 8.16 nis --
Interface to Sun's NIS (Yellow Pages)
Availability: UNIX.
The nis module gives a thin wrapper around the NIS library, useful
for central administration of several hosts.
Because NIS exists only on Unix systems, this module is
only available for Unix.
The nis module defines the following functions:
The nis module defines the following exception:


11.8 nntplib -- NNTP protocol client

imap4-example.html | internet.html | nntp-objects.html | Python Library Reference | contents.html | genindex.html
---
# 11.8 nntplib --
NNTP protocol client
This module defines the class NNTP which implements the client
side of the NNTP protocol. It can be used to implement a news reader
or poster, or automated news processors. For more information on NNTP
(Network News Transfer Protocol), see Internet RFC 977 (http://www.ietf.org/rfc/rfc0977.txt).
Here are two small examples of how it can be used. To list some
statistics about a newsgroup and print the subjects of the last 10
articles:
```text

>>> s = NNTP('news.cwi.nl')
>>> resp, count, first, last, name = s.group('comp.lang.python')
>>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
Group comp.lang.python has 59 articles, range 3742 to 3803
>>> resp, subs = s.xhdr('subject', first + '-' + last)
>>> for id, sub in subs[-10:]: print id, sub
...
3792 Re: Removing elements from a list while iterating...
3793 Re: Who likes Info files?
3794 Emacs and doc strings
3795 a few questions about the Mac implementation
3796 Re: executable python scripts
3797 Re: executable python scripts
3798 Re: a few questions about the Mac implementation
3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules
3802 Re: executable python scripts
3803 Re: \POSIX{} wait and SIGCHLD
>>> s.quit()
'205 news.cwi.nl closing connection. Goodbye.'
```
To post an article from a file (this assumes that the article has
valid headers):
```text

>>> s = NNTP('news.cwi.nl')
>>> f = open('/tmp/article')
>>> s.post(f)
'240 Article posted successfully.'
>>> s.quit()
'205 news.cwi.nl closing connection. Goodbye.'
```
The module itself defines the following items:


module-UserString.html | python.html | module-traceback.html | Python Library Reference | contents.html | genindex.html
---
# 3.6 operator --
Standard operators as functions.
The operator module exports a set of functions implemented in C
corresponding to the intrinsic operators of Python. For example,
`operator.add(x, y)` is equivalent to the expression `x+y`. The
function names are those used for special class methods; variants without
leading and trailing "__" are also provided for convenience.
The operator module defines the following functions:
Example: Build a dictionary that maps the ordinals from `0` to
`256` to their character equivalents.


6.1 os -- Miscellaneous OS interfaces

allos.html | allos.html | os-procinfo.html | Python Library Reference | contents.html | genindex.html
---
# 6.1 os --
Miscellaneous OS interfaces
This module provides a more portable way of using operating system
(OS) dependent functionality than importing an OS dependent built-in
module like posix (module-posix.html) or nt.
This module searches for an OS dependent built-in module like
mac or posix (module-posix.html) and exports the same functions and data
as found there. The design of all Python's built-in OS dependent
modules is such that as long as the same functionality is available,
it uses the same interface; e.g., the function
`os.stat( path )` returns stat information about path in
the same format (which happens to have originated with the
POSIX interface).
Extensions peculiar to a particular OS are also available through the
os module, but using them is of course a threat to
portability!
Note that after the first time os is imported, there is
no performance penalty in using functions from os
instead of directly from the OS dependent built-in module, so there
should be no reason not to use os!
The os module contains many functions and data values.
The items below and in the following sub-sections are all available
directly from the os module.


os-path.html | allos.html | module-dircache.html | Python Library Reference | contents.html | genindex.html
---
# 6.2 os.path --
Common pathname manipulations
This module implements some useful functions on pathnames.


examples-imp.html | python.html | Creating_ASTs.html | Python Library Reference | contents.html | genindex.html
---
# 3.16 parser --
Access Python parse trees
The parser module provides an interface to Python's internal
parser and byte-code compiler. The primary purpose for this interface
is to allow Python code to edit the parse tree of a Python expression
and create executable code from this. This is better than trying
to parse and modify an arbitrary Python code fragment as a string
because parsing is performed in a manner identical to the code
forming the application. It is also faster.
There are a few things to note about this module which are important
to making use of the data structures created. This is not a tutorial
on editing the parse trees for Python code, but some examples of using
the parser module are presented.
Most importantly, a good understanding of the Python grammar processed
by the internal parser is required. For full information on the
language syntax, refer to the Python
Language Reference (../ref/ref.html). The parser itself is created from a grammar
specification defined in the file Grammar/Grammar in the
standard Python distribution. The parse trees stored in the AST
objects created by this module are the actual output from the internal
parser when created by the expr() or suite()
functions, described below. The AST objects created by
sequence2ast() faithfully simulate those structures. Be
aware that the values of the sequences which are considered
``correct'' will vary from one version of Python to another as the
formal grammar for the language is revised. However, transporting
code from one Python version to another as source text will always
allow correct parse trees to be created in the target version, with
the only restriction being that migrating to an older version of the
interpreter will not support more recent language constructs. The
parse trees are not typically compatible from one version to another,
whereas source code has always been forward-compatible.
Each element of the sequences returned by ast2list() or
ast2tuple() has a simple form. Sequences representing
non-terminal elements in the grammar always have a length greater than
one. The first element is an integer which identifies a production in
the grammar. These integers are given symbolic names in the C header
file Include/graminit.h and the Python module
symbol (module-symbol.html). Each additional element of the sequence represents
a component of the production as recognized in the input string: these
are always sequences which have the same form as the parent. An
important aspect of this structure which should be noted is that
keywords used to identify the parent node type, such as the keyword
if in an if_stmt, are included in the node tree without
any special treatment. For example, the if keyword is
represented by the tuple `(1, 'if')`, where `1` is the
numeric value associated with all NAME tokens, including
variable and function names defined by the user. In an alternate form
returned when line number information is requested, the same token
might be represented as `(1, 'if', 12)`, where the `12`represents the line number at which the terminal symbol was found.
Terminal elements are represented in much the same way, but without
any child elements and the addition of the source text which was
identified. The example of the if keyword above is
representative. The various types of terminal symbols are defined in
the C header file Include/token.h and the Python module
token (module-token.html).
The AST objects are not required to support the functionality of this
module, but are provided for three purposes: to allow an application
to amortize the cost of processing complex parse trees, to provide a
parse tree representation which conserves memory space when compared
to the Python list or tuple representation, and to ease the creation
of additional modules in C which manipulate parse trees. A simple
``wrapper'' class may be created in Python to hide the use of AST
objects.
The parser module defines functions for a few distinct
purposes. The most important purposes are to create AST objects and
to convert AST objects to other representations such as parse trees
and compiled code objects, but there are also functions which serve to
query the type of parse tree represented by an AST object.
See Also:


9. The Python Debugger

module-commands.html | lib.html | debugger-commands.html | Python Library Reference | contents.html | genindex.html
---
# 9. The Python Debugger
The module pdb defines an interactive source code
debugger for Python programs. It supports setting
(conditional) breakpoints and single stepping at the source line
level, inspection of stack frames, source code listing, and evaluation
of arbitrary Python code in the context of any stack frame. It also
supports post-mortem debugging and can be called under program
control.
The debugger is extensible -- it is actually defined as the class
Pdb.
This is currently undocumented but easily understood by reading the
source. The extension interface uses the modules
bdb (undocumented) and
cmd (module-cmd.html).
A primitive windowing version of the debugger also exists -- this is
module wdb, which requires
stdwin.
The debugger's prompt is "(Pdb) ".
Typical usage to run a program under control of the debugger is:
```text

>>> import pdb
>>> import mymodule
>>> pdb.run('mymodule.test()')
> <string>(0)?()
(Pdb) continue
> <string>(1)?()
(Pdb) continue
NameError: 'spam'
> <string>(1)?()
(Pdb)
```
pdb.py can also be invoked as
a script to debug other scripts. For example:
```text

python /usr/local/lib/python1.5/pdb.py myscript.py
```
Typical usage to inspect a crashed program is:
```text

>>> import pdb
>>> import mymodule
>>> mymodule.test()
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "./mymodule.py", line 4, in test
test2()
File "./mymodule.py", line 3, in test2
print spam
NameError: spam
>>> pdb.pm()
> ./mymodule.py(3)test2()
-> print spam
(Pdb)
```
The module defines the following functions; each enters the debugger
in a slightly different way: