Cryptographic Services -- Python library reference

---
Prev: Multimedia Services (Multimedia-Services.html)
Top: Top (Top.html)
---
# 13. Cryptographic Services
The modules described in this chapter implement various algorithms of
a cryptographic nature. They are available at the discretion of the
installation. Here's an overview:
Hardcore cypherpunks will probably find the Python Cryptography Kit of
further interest; the package adds built-in modules for DES and IDEA
encryption, and provides a Python module for reading and decrypting
PGP files. The Python Cryptography Kit is not distributed with Python
but available separately. See the URL
http://www.cs.mcgill.ca/%7Efnord/crypt.html for more information.
## Menu
---
Prev: Multimedia Services (Multimedia-Services.html)
Top: Top (Top.html)
---


ctb -- Python library reference

---
Prev: macpath (macpath.html)
Top: Top (Top.html)
---
# 14.3. Built-in Module `ctb`
This module provides a partial interface to the Macintosh
Communications Toolbox. Currently, only Connection Manager tools are
supported. It may not be available in all Mac Python versions.
## Menu
---
Prev: macpath (macpath.html)
Top: Top (Top.html)
---


dbm -- Python library reference

---
Prev: grp (grp.html)
Top: Top (Top.html)
---
# 8.5. Built-in Module `dbm`
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, which provides a similar interface
using the GNU GDBM library.
The module defines the following constant and functions:
---
Prev: grp (grp.html)
Top: Top (Top.html)
---


Debugger Commands -- Python library reference

---
Prev: The Python Debugger (The-Python-Debugger.html)
Top: Top (Top.html)
---
# 9.1. Debugger Commands
The debugger recognizes the following commands. Most commands can be
abbreviated to one or two letters; e.g. ```h(elp)`'' means that
either ```h`'' or ```help`'' can be used to enter the help
command (but not ```he`'' or ```hel`'', nor ```H`'' or
```Help` or ```HELP`''). Arguments to commands must be
separated by whitespace (spaces or tabs). Optional arguments are
enclosed in square brackets (```[]`'') in the command syntax; the
square brackets must not be typed. Alternatives in the command syntax
are separated by a vertical bar (```|`'').

Entering a blank line repeats the last command entered. Exception: if
the last command was a ```list`'' command, the next 11 lines are
listed.

Commands that the debugger doesn't recognize are assumed to be Python
statements and are executed in the context of the program being
debugged. Python statements can also be prefixed with an exclamation
point (```!`''). This is a powerful way to inspect the program
being debugged; it is even possible to change a variable or call a
function. When an
exception occurs in such a statement, the exception name is printed
but the debugger's state is not changed.

---

Next: How It Works (How-It-Works.html)
Prev: The Python Debugger (The-Python-Debugger.html)
Up: The Python Debugger (The-Python-Debugger.html)
Top: Top (Top.html)

---


Deterministic Profiling -- Python library reference

---
Prev: Instant Users Manual (Instant-Users-Manual.html)
Top: Top (Top.html)
---
# 10.4. What Is Deterministic Profiling?
Deterministic profiling is meant to reflect the fact that all
function call, function return, and exception events
are monitored, and precise timings are made for the intervals between
these events (during which time the user's code is executing). In
contrast, statistical profiling (which is not done by this
module) randomly samples the effective instruction pointer, and
deduces where time is being spent. The latter technique traditionally
involves less overhead (as the code does not need to be instrumented),
but provides only relative indications of where time is being spent.
In Python, since there is an interpreter active during execution, the
presence of instrumented code is not required to do deterministic
profiling. Python automatically provides a hook (optional
callback) for each event. In addition, the interpreted nature of
Python tends to add so much overhead to execution, that deterministic
profiling tends to only add small processing overhead in typical
applications. The result is that deterministic profiling is not that
expensive, yet provides extensive run time statistics about the
execution of a Python program.
Call count statistics can be used to identify bugs in code (surprising
counts), and to identify possible inline-expansion points (high call
counts). Internal time statistics can be used to identify ``hot
loops'' that should be carefully optimized. Cumulative time
statistics should be used to identify high level errors in the
selection of algorithms. Note that the unusual handling of cumulative
times in this profiler allows statistics for recursive implementations
of algorithms to be directly compared to iterative implementations.
---
Prev: Instant Users Manual (Instant-Users-Manual.html)
Top: Top (Top.html)
---


DialogWindow Objects -- Python library reference

---
Prev: Window Objects (Window-Objects.html)
Top: Top (Top.html)
---
## 14.12.3. DialogWindow Objects
DialogWindow objects have the following methods besides those of
`Window` objects:
---
Prev: Window Objects (Window-Objects.html)
Top: Top (Top.html)
---


dnr result object -- Python library reference

---
Prev: macdnr (macdnr.html)
Top: Top (Top.html)
---
## 14.5.1. dnr result object
Since the DNR calls all execute asynchronously you do not get the
results back immediately. Instead, you get a dnr result object. You
can check this object to see whether the query is complete, and access
its attributes to obtain the information when it is.
Alternatively, you can also reference the result attributes directly,
this will result in an implicit wait for the query to complete.
The rtnCode and cname attributes are always available, the
others depend on the type of query (address, hinfo or mx).
The simplest way to use the module to convert names to dotted-decimal
strings, without worrying about idle time, etc:
```text
>>> def gethostname(name):

... import macdnr

... dnrr = macdnr.StrToAddr(name)

... return macdnr.AddrToStr(dnrr.ip0)
```
---
Prev: macdnr (macdnr.html)
Top: Top (Top.html)
---


Drawing Objects -- Python library reference

---
Prev: Window Objects (Window-Objects.html)
Top: Top (Top.html)
---
## 15.1.3. Drawing Objects
Drawing objects are created exclusively by the window method
`begindrawing()`.
Only one drawing object can exist at any given time; the drawing object
must be deleted to finish drawing.
No drawing object may exist when
`stdwin.getevent()`
is called.
Drawing objects have the following methods:
---
Prev: Window Objects (Window-Objects.html)
Top: Top (Top.html)
---


EasyDialogs -- Python library reference

---
Prev: macspeech (macspeech.html)
Top: Top (Top.html)
---
# 14.11. Standard module `EasyDialogs`
The `EasyDialogs` module contains some simple dialogs for
the Macintosh, modelled after the `stdwin` dialogs with similar
names.
The `EasyDialogs` module defines the following functions:
Note that `EasyDialogs` does not currently use the notification
manager. This means that displaying dialogs while the program is in
the background will need to unexpected results and possibly crashes.
---
Prev: macspeech (macspeech.html)
Top: Top (Top.html)
---


Example -- Python library reference

---
Prev: Exceptions and Error Handling (Exceptions-and-Error-Handling.html)
Top: Top (Top.html)
---
## 3.9.2. Example
A simple example:
```text
>>> import parser

>>> ast = parser.expr('a + 5')

>>> code = parser.compileast(ast)

>>> a = 5

>>> eval(code)

10
```
---
Prev: Exceptions and Error Handling (Exceptions-and-Error-Handling.html)
Top: Top (Top.html)
---


Examples -- Python library reference

---
Prev: imp (imp.html)
Top: Top (Top.html)
---
## 3.8.1. Examples
The following function emulates the default import statement:
```text
import imp

import sys

def __import__(name, globals=None, locals=None, fromlist=None):

# Fast path: see if the module has already been imported.

if sys.modules.has_key(name):

return sys.modules[name]

# If any of the following calls raises an exception,

# there's a problem we can't handle -- let the caller handle it.

# See if it's a built-in module.

m = imp.init_builtin(name)

if m:

return m

# See if it's a frozen module.

m = imp.init_frozen(name)

if m:

return m

# Search the default path (i.e. sys.path).

fp, pathname, (suffix, mode, type) = imp.find_module(name)

# See what we got.

try:

if type == imp.C_EXTENSION:

return imp.load_dynamic(name, pathname)

if type == imp.PY_SOURCE:

return imp.load_source(name, pathname, fp)

if type == imp.PY_COMPILED:

return imp.load_compiled(name, pathname, fp)

# Shouldn't get here at all.

raise ImportError, '%s: unknown module type (%d)' % (name, type)

finally:

# Since we may exit via an exception, close fp explicitly.

fp.close()
```
---
Prev: imp (imp.html)
Top: Top (Top.html)
---


Exceptions and Error Handling -- Python library reference

---
Prev: parser (parser.html)
Top: Top (Top.html)
---
## 3.9.1. Exceptions and Error Handling
The parser module defines a single exception, but may also pass other
built-in exceptions from other portions of the Python runtime
environment. See each function for information about the exceptions
it can raise.
Note that the functions `compileast()`, `expr()`, and
`suite()` may throw exceptions which are normally thrown by the
parsing and compilation process. These include the built in
exceptions `MemoryError`, `OverflowError`,
`SyntaxError`, and `SystemError`. In these cases, these
exceptions carry all the meaning normally associated with them. Refer
to the descriptions of each function for detailed information.
---
Prev: parser (parser.html)
Top: Top (Top.html)
---


Exceptions -- Python library reference

---
Prev: Types (Types.html)
Top: Top (Top.html)
---
# 2.2. Built-in Exceptions
Exceptions are string objects. Two distinct string objects with the
same value are 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.
The following exceptions 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).
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.
---
Prev: Types (Types.html)
Top: Top (Top.html)
---


fcntl -- Python library reference

---
Prev: TERMIOS (TERMIOS.html)
Top: Top (Top.html)
---
# 8.9. Built-in Module `fcntl`
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` and
`sys/ioctl`. 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

file = open(...)

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

lockdata = struct.pack('hhllhh', FCNTL.F_WRLCK, 0, 0, 0, 0, 0)

rv = fcntl(file.fileno(), FCNTL.F_SETLKW, lockdata)
```
Note that in the first example the return value variable `rv` will
hold an integer value; in the second example it will hold a string
value.
---
Prev: TERMIOS (TERMIOS.html)
Top: Top (Top.html)
---


File Objects -- Python library reference

---
Prev: The Null Object (The-Null-Object.html)
Top: Top (Top.html)
---
### 2.1.7.8. File Objects
File objects are implemented using C's `stdio` package and can be
created with the built-in function `open()` described under
Built-in Functions below. They are also returned by some other
built-in functions and methods, e.g. `posix.popen()` and
`posix.fdopen()` and the `makefile()` method of socket
objects.
When a file operation fails for an I/O-related reason, the exception
`IOError` is raised. This includes situations where the
operation is not defined for some reason, like `seek()` on a tty
device or writing a file opened for reading.
Files have the following methods:
## ---------- Footnotes ----------
(1) (#footnoteref1)
The advantage of leaving the newline on is that an empty string
can be returned to mean EOF without being ambiguous. Another
advantage is that (in cases where it might matter, e.g. if you
want to make an exact copy of a file while scanning its lines)
you can tell whether the last line of a file ended in a newline
or not (yes this happens!).
---
Prev: The Null Object (The-Null-Object.html)
Top: Top (Top.html)
---


FInfo objects -- Python library reference

---
Prev: alias objects (alias-objects.html)
Top: Top (Top.html)
---
## 14.6.3. FInfo objects
See Inside Mac for a complete description of what the various fields
mean.
---
Prev: alias objects (alias-objects.html)
Top: Top (Top.html)
---


FL (uppercase) -- Python library reference

---
Prev: fl (fl.html)
Top: Top (Top.html)
---
# 16.5. Standard Module `FL`
This module defines symbolic constants needed to use the built-in
module `fl` (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 *
```
---
Prev: fl (fl.html)
Top: Top (Top.html)
---


FL Functions -- Python library reference

---
Prev: fl (fl.html)
Top: Top (Top.html)
---
## 16.4.1. Functions Defined in Module `fl`
Module `fl` defines the following functions. For more information
about what they do, see the description of the equivalent C function
in the FORMS documentation:
---
Prev: fl (fl.html)
Top: Top (Top.html)
---


fl -- Python library reference

---
Prev: cd (cd.html)
Top: Top (Top.html)
---
# 16.4. Built-in Module `fl`
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` 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()`.
## Menu
---
Prev: cd (cd.html)
Top: Top (Top.html)
---


flp -- Python library reference

---
Prev: FL (uppercase) (FL--uppercase-.html)
Top: Top (Top.html)
---
# 16.6. Standard Module `flp`
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` above).
For now, see the file flp.doc in the Python library source
directory for a description.
XXX A complete description should be inserted here!
---
Prev: FL (uppercase) (FL--uppercase-.html)
Top: Top (Top.html)
---


fm -- Python library reference

---
Prev: flp (flp.html)
Top: Top (Top.html)
---
# 16.7. Built-in Module `fm`
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:
---
Prev: flp (flp.html)
Top: Top (Top.html)
---


Form Objects -- Python library reference

---
Prev: FL Functions (FL-Functions.html)
Top: Top (Top.html)
---
## 16.4.2. Form Objects
Form objects (returned by `fl.make_form()` above) have the
following methods. Each method corresponds to a C function whose name
is prefixed with `fl_'; and whose first argument is a form
pointer; please refer to the official FORMS documentation for
descriptions.
All the `add_...' functions return a Python object representing
the FORMS object. Methods of FORMS objects are described below. Most
kinds of FORMS object also have some methods specific to that kind;
these methods are listed here.
Form objects have the following data attributes; see the FORMS
documentation:
---
Prev: FL Functions (FL-Functions.html)
Top: Top (Top.html)
---


FORMS Objects -- Python library reference

---
Prev: Form Objects (Form-Objects.html)
Top: Top (Top.html)
---
## 16.4.3. FORMS Objects
Besides methods specific to particular kinds of FORMS objects, all
FORMS objects also have the following methods:
FORMS objects have these data attributes; see the FORMS documentation:
---
Prev: Form Objects (Form-Objects.html)
Top: Top (Top.html)
---


FrameWork -- Python library reference

---
Prev: EasyDialogs (EasyDialogs.html)
Top: Top (Top.html)
---
# 14.12. Standard module `FrameWork`
The `FrameWork` module contains classes that together provide a
framework for an interactive Macintosh application. The programmer
builds an application by creating subclasses that override various
methods of the bases classes, thereby implementing the functionality
wanted. Overriding functionality can often be done on various
different levels, i.e. to handle clicks in a single dialog window in a
non-standard way it is not necessary to override the complete event
handling.
The `FrameWork` is still very much work-in-progress, and the
documentation describes only the most important functionality, and not
in the most logical manner at that. Examine the source for more
esoteric needs.
The `EasyDialogs` module defines the following functions:
## Menu
---
Prev: EasyDialogs (EasyDialogs.html)
Top: Top (Top.html)
---


FSSpec objects -- Python library reference

---
Prev: macfs (macfs.html)
Top: Top (Top.html)
---
## 14.6.1. FSSpec objects
---
Prev: macfs (macfs.html)
Top: Top (Top.html)
---


FTP Objects -- Python library reference

---
Prev: ftplib (ftplib.html)
Top: Top (Top.html)
---
## 11.4.1. FTP Objects
FTP instances have the following methods:
---
Prev: ftplib (ftplib.html)
Top: Top (Top.html)
---


ftplib -- Python library reference

---
Prev: httplib (httplib.html)
Top: Top (Top.html)
---
# 11.4. Standard Module `ftplib`
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` to handle URLs that use FTP. For
more information on FTP (File Transfer Protocol), see Internet RFC
959.
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.quit()
```
The module defines the following items:
## Menu
---
Prev: httplib (httplib.html)
Top: Top (Top.html)
---


Functions -- Python library reference

---
Prev: Classes and Instances (Classes-and-Instances.html)
Top: Top (Top.html)
---
### 2.1.7.3. Functions
Function objects are created by function definitions. The only
operation on a function object is to call it:
`func ( argument-list )`.
There are really two flavors of function objects: built-in functions
and user-defined functions. Both support the same operation (to call
the function), but the implementation is different, hence the
different object types.
The implementation adds two special read-only attributes:
`f .func_code` is a function's code object (see below) and
`f .func_globals` is the dictionary used as the function's
global name space (this is the same as `m .__dict__` where
m is the module in which the function f was defined).
---
Prev: Classes and Instances (Classes-and-Instances.html)
Top: Top (Top.html)
---


gdbm -- Python library reference

---
Prev: dbm (dbm.html)
Top: Top (Top.html)
---
# 8.6. Built-in Module `gdbm`
This module is nearly identical to the `dbm` module, but uses
GDBM instead. Its interface is identical, and not repeated here.
Warning: the file formats created by gdbm and dbm are incompatible.


Generic Operating System Services -- Python library reference

---
Prev: Miscellaneous Services (Miscellaneous-Services.html)
Top: Top (Top.html)
---
# 6. Generic Operating System Services
The modules described in this chapter provide interfaces to operating
system features that are available on (almost) all operating systems,
such as files and a clock. The interfaces are generally modelled
after the UNIX or C interfaces but they are available on most other
systems as well. Here's an overview:
## Menu
---
Prev: Miscellaneous Services (Miscellaneous-Services.html)
Top: Top (Top.html)
---


getopt -- Python library reference

---
Prev: time (time.html)
Top: Top (Top.html)
---
# 6.3. Standard Module `getopt`
This module helps scripts to parse the command line arguments in
`sys.argv`.
It uses the same conventions as the UNIX
`getopt()`
function (including the special meanings of arguments of the form
`-' and `--').
It defines the function
`getopt.getopt(args, options)`
and the exception
`getopt.error`.
The first argument to
`getopt()`
is the argument list passed to the script with its first element
chopped off (i.e.,
`sys.argv[1:]`).
The second argument is the string of option letters that the
script wants to recognize, with options that require an argument
followed by a colon (i.e., the same format that UNIX
`getopt()`
uses).
The return value consists of two elements: the first is a list of
option-and-value pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice of the
first argument).
Each option-and-value pair returned has the option as its first element,
prefixed with a hyphen (e.g.,
`'-x'`),
and the option argument as its second element, or an empty string if the
option has no argument.
The options occur in the list in the same order in which they were
found, thus allowing multiple occurrences.
Example:
```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']

>>>
```
The exception
`getopt.error = 'getopt error'`
is raised when an unrecognized option is found in the argument list or
when an option requiring an argument is given none.
The argument to the exception is a string indicating the cause of the
error.
---
Prev: time (time.html)
Top: Top (Top.html)
---


GL and DEVICE -- Python library reference

---
Prev: gl (gl.html)
Top: Top (Top.html)
---
# 16.9. Standard Modules `GL` and `DEVICE`
These modules define the constants used by the Silicon Graphics
Graphics Library
that C programmers find in the header files
<gl/gl.h>
and
<gl/device.h>.
Read the module source files for details.
---
Prev: gl (gl.html)
Top: Top (Top.html)
---


gl -- Python library reference

---
Prev: fm (fm.html)
Top: Top (Top.html)
---
# 16.8. Built-in Module `gl`
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()
```
---
Prev: fm (fm.html)
Top: Top (Top.html)
---


gopherlib -- Python library reference

---
Prev: ftplib (ftplib.html)
Top: Top (Top.html)
---
# 11.5. Standard Module `gopherlib`
This module provides a minimal implementation of client side of the
the Gopher protocol. It is used by the module `urllib` to handle
URLs that use the Gopher protocol.
The module defines the following functions:
Note that the data returned by the Gopher server can be of any type,
depending on the first character of the selector string. If the data
is text (first character of the selector is `0'), lines are
terminated by CRLF, and the data is terminated by a line consisting of
a single `.', and a leading `.' should be stripped from
lines that begin with `..'. Directory listings (first charactger
of the selector is `1') are transferred using the same protocol.
---
Prev: ftplib (ftplib.html)
Top: Top (Top.html)
---


grp -- Python library reference

---
Prev: pwd (pwd.html)
Top: Top (Top.html)
---
# 8.4. Built-in Module `grp`
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:
`gr_name`,
`gr_passwd`,
`gr_gid`,
`gr_mem`.
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.)
An exception is raised if the entry asked for cannot be found.
It defines the following items:
---
Prev: pwd (pwd.html)
Top: Top (Top.html)
---


HotProfile Class -- Python library reference

---
Prev: OldProfile Class (OldProfile-Class.html)
Top: Top (Top.html)
---
## 10.8.2. HotProfile Class
This profiler is the fastest derived profile example. It does not
calculate caller-callee relationships, and does not calculate
cumulative time under a function. It only calculates time spent in a
function, so it runs very quickly (re: very low overhead). In truth,
the basic profiler is so fast, that is probably not worth the savings
to give up the data, but this class still provides a nice example.
```text
class HotProfile(Profile):

def trace_dispatch_exception(self, frame, t):

rt, rtt, rfn, rframe, rcur = self.cur

if rcur and not rframe is frame:

return self.trace_dispatch_return(rframe, t)

return 0

def trace_dispatch_call(self, frame, t):

self.cur = (t, 0, frame, self.cur)

return 1

def trace_dispatch_return(self, frame, t):

rt, rtt, frame, rcur = self.cur

rfn = `frame.f_code`

pt, ptt, pframe, pcur = rcur

self.cur = pt, ptt+rt, pframe, pcur

if self.timings.has_key(rfn):

nc, tt = self.timings[rfn]

self.timings[rfn] = nc + 1, rt + rtt + tt

else:

self.timings[rfn] = 1, rt + rtt

return 1

def snapshot_stats(self):

self.stats = {}

for func in self.timings.keys():

nc, tt = self.timings[func]

nor_func = self.func_normalize(func)

self.stats[nor_func] = nc, nc, tt, 0, {}
```
---
Prev: OldProfile Class (OldProfile-Class.html)
Top: Top (Top.html)
---


How It Works -- Python library reference

---
Prev: Debugger Commands (Debugger-Commands.html)
Top: Top (Top.html)
---
# 9.2. How It Works
Some changes were made to the interpreter:
- sys.settrace(func) sets the global trace function
there can also a local trace function (see later)
Trace functions have three arguments: (frame, event, arg)
A trace function should return a new trace function or None.
Class methods are accepted (and most useful!) as trace methods.
The events have the following meaning:
Note that as an exception is propagated down the chain of callers, an
`'exception'` event is generated at each level.
Stack frame objects have the following read-only attributes:
Code objects have the following read-only attributes:
---
Prev: Debugger Commands (Debugger-Commands.html)
Top: Top (Top.html)
---


htmllib -- Python library reference

---
Prev: urlparse (urlparse.html)
Top: Top (Top.html)
---
# 11.8. Standard Module `htmllib`
This module defines a number of classes which can serve as a basis for
parsing text files formatted in HTML (HyperText Mark-up Language).
The classes are not directly concerned with I/O --- the have to be fed
their input in string form, and will make calls to methods of a
``formatter'' object in order to produce output. The classes are
designed to be used as base classes for other classes in order to add
functionality, and allow most of their methods to be extended or
overridden. In turn, the classes are derived from and extend the
class `SGMLParser` defined in module `sgmllib`.
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 elements, these are processed immediately; incomplete elements
are saved in a buffer. To force processing of all unprocessed data,
call the `close()` method.
Example: to parse the entire contents of a file, do*
`parser.feed(open(file).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 the following classes:
Instances of `CollectingParser` (and thus also instances of
`FormattingParser` and `AnchoringParser`) have the following
instance variables:
The `anchors`, `anchornames` and `anchortypes` lists
are ``parallel arrays'': items in these lists with the same index
pertain to the same anchor. Missing attributes default to the empty
string. Anchors with neither a `HREF` nor a `NAME`
attribute are not entered in these lists at all.
The module also defines a number of style sheet classes. These should
never be instantiated --- their class variables are the only behavior
required. Note that style sheets are specifically designed for a
particular formatter implementation. The currently defined style
sheets are:
Style sheets have the following class variables:
Although no documented implementation of a formatter exists, the
`FormattingParser` class assumes that formatters have a
certain interface. This interface requires the following methods:
A sample formatter implementation can be found in the module
`fmt`, which in turn uses the module `Para`. These modules are
not intended as standard library modules; they are available as an
example of how to write a formatter.
---
Prev: urlparse (urlparse.html)
Top: Top (Top.html)
---


HTTP Example -- Python library reference

---
Prev: HTTP Objects (HTTP-Objects.html)
Top: Top (Top.html)
---
## 11.3.2. Example
Here is an example session:
```text
>>> import httplib

>>> h = httplib.HTTP('www.cwi.nl')

>>> h.putrequest('GET', '/index.html')

>>> h.putheader('Accept', 'text/html')

>>> h.putheader('Accept', 'text/plain')

>>> h.endheaders()

>>> errcode, errmsg, headers = h.getreply()

>>> print errcode # Should be 200

>>> f = h.getfile()

>>> data f.read() # Get the raw HTML

>>> f.close()

>>>
```
---
Prev: HTTP Objects (HTTP-Objects.html)
Top: Top (Top.html)
---


HTTP Objects -- Python library reference

---
Prev: httplib (httplib.html)
Top: Top (Top.html)
---
## 11.3.1. HTTP Objects
`HTTP` instances have the following methods:
---
Prev: httplib (httplib.html)
Top: Top (Top.html)
---


httplib -- Python library reference

---
Prev: urllib (urllib.html)
Top: Top (Top.html)
---
# 11.3. Standard Module `httplib`
This module defines a class which implements the client side of the
HTTP protocol. It is normally not used directly --- the module
`urllib` uses it to handle URLs that use HTTP.
The module defines one class, `HTTP`. An `HTTP` instance
represents one transaction with an HTTP server. It should be
instantiated passing it a host and optional port number. If no port
number is passed, the port is extracted from the host string if it has
the form `host:port`, else the default HTTP port (80) is used.
If no host is passed, no connection is made, and the `connect`
method should be used to connect to a server. For example, the
following calls all create instances that connect to the server at the
same host and port:
```text
>>> h1 = httplib.HTTP('www.cwi.nl')

>>> h2 = httplib.HTTP('www.cwi.nl:80')

>>> h3 = httplib.HTTP('www.cwi.nl', 80)
```
Once an `HTTP` instance has been connected to an HTTP server, it
should be used as follows:
- 1. 1. Make exactly one call to the `putrequest()` method.
2. 2. Make zero or more calls to the `putheader()` method.
3. 3. Call the `endheaders()` method (this can be omitted if
step 4 makes no calls).
4. 4. Optional calls to the `send()` method.
5. 5. Call the `getreply()` method.
6. 6. Call the `getfile()` method and read the data off the
file object that it returns.
## Menu
---
Prev: urllib (urllib.html)
Top: Top (Top.html)
---


imageop -- Python library reference

---
Prev: audioop (audioop.html)
Top: Top (Top.html)
---
# 12.2. Built-in Module `imageop`
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.
The module defines the following variables and functions:
---
Prev: audioop (audioop.html)
Top: Top (Top.html)
---


imgfile -- Python library reference

---
Prev: GL and DEVICE (GL-and-DEVICE.html)
Top: Top (Top.html)
---
# 16.10. Built-in Module `imgfile`
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:
---
Prev: GL and DEVICE (GL-and-DEVICE.html)
Top: Top (Top.html)
---


imp -- Python library reference

---
Prev: marshal (marshal.html)
Top: Top (Top.html)
---
# 3.8. Built-in Module `imp`
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 the module,
are used to indicate the search result of `imp.find_module`.
## Menu
---
Prev: marshal (marshal.html)
Top: Top (Top.html)
---


Instant Users Manual -- Python library reference

---
Prev: Profiler Changes (Profiler-Changes.html)
Top: Top (Top.html)
---
# 10.3. Instant Users Manual
This section is provided for users that ``don't want to read the
manual.'' It provides a very brief overview, and allows a user to
rapidly perform profiling on an existing application.
To profile an application with a main entry point of `foo()', you
would add the following to your module:
```text
import profile

profile.run("foo()")
```
The above action would cause `foo()' to be run, and a series of
informative lines (the profile) to be printed. The above approach is
most useful when working with the interpreter. If you would like to
save the results of a profile into a file for later examination, you
can supply a file name as the second argument to the `run()`
function:
```text
import profile

profile.run("foo()", 'fooprof')
```
When you wish to review the profile, you should use the methods in the
`pstats` module. Typically you would load the statistics data as
follows:
```text
import pstats

p = pstats.Stats('fooprof')
```
The class `Stats` (the above code just created an instance of
this class) has a variety of methods for manipulating and printing the
data that was just read into `p'. When you ran
`profile.run()` above, what was printed was the result of three
method calls:
```text
p.strip_dirs().sort_stats(-1).print_stats()
```
The first method removed the extraneous path from all the module
names. The second method sorted all the entries according to the
standard module/line/name string that is printed (this is to comply
with the semantics of the old profiler). The third method printed out
all the statistics. You might try the following sort calls:
```text
p.sort_stats('name')

p.print_stats()
```
The first call will actually sort the list by function name, and the
second call will print out the statistics. The following are some
interesting calls to experiment with:
```text
p.sort_stats('cumulative').print_stats(10)
```
This sorts the profile by cumulative time in a function, and then only
prints the ten most significant lines. If you want to understand what
algorithms are taking time, the above line is what you would use.
If you were looking to see what functions were looping a lot, and
taking a lot of time, you would do:
```text
p.sort_stats('time').print_stats(10)
```
to sort according to time spent within each function, and then print
the statistics for the top ten functions.
You might also try:
```text
p.sort_stats('file').print_stats('__init__')
```
This will sort all the statistics by file name, and then print out
statistics for only the class init methods ('cause they are spelled
with `__init__` in them). As one final example, you could try:
```text
p.sort_stats('time', 'cum').print_stats(.5, 'init')
```
This line sorts statistics with a primary key of time, and a secondary
key of cumulative time, and then prints out some of the statistics.
To be specific, the list is first culled down to 50% (re: `.5')
of its original size, then only lines containing `init` are
maintained, and that sub-sub-list is printed.
If you wondered what functions called the above functions, you could
now (`p' is still sorted according to the last criteria) do:
```text
p.print_callers(.5, 'init')
```
and you would get a list of callers for each of the listed functions.
If you want more functionality, you're going to have to read the
manual, or guess what the following functions do:
```text
p.print_callees()

p.add('fooprof')
```
---
Prev: Profiler Changes (Profiler-Changes.html)
Top: Top (Top.html)
---


Internal Objects -- Python library reference

---
Prev: File Objects (File-Objects.html)
Top: Top (Top.html)
---
### 2.1.7.9. Internal Objects
(See the Python Reference Manual for these.)


Internet and WWW -- Python library reference

---
Prev: The Python Profiler (The-Python-Profiler.html)
Top: Top (Top.html)
---
# 11. Internet and WWW Services
The modules described in this chapter provide various services to
World-Wide Web (WWW) clients and/or services, and a few modules
related to news and email. They are all implemented in Python. Some
of these modules require the presence of the system-dependent module
`sockets`, which is currently only fully supported on Unix and
Windows NT. Here is an overview:
## Menu
---
Prev: The Python Profiler (The-Python-Profiler.html)
Top: Top (Top.html)
---


Introduction -- Python library reference

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


jpeg -- Python library reference

---
Prev: aifc (aifc.html)
Top: Top (Top.html)
---
# 12.4. Built-in Module `jpeg`
The module `jpeg` provides access to the jpeg compressor and
decompressor written by the Independent JPEG Group. JPEG is a (draft?)
standard for compressing pictures. For details on jpeg or the
Independent JPEG Group software refer to the JPEG standard or the
documentation provided with the software.
The `jpeg` module defines these functions:
Compress and uncompress raise the error `jpeg.error` in case of errors.
---
Prev: aifc (aifc.html)
Top: Top (Top.html)
---


Limitations -- Python library reference

---
Prev: Reference Manual (Reference-Manual.html)
Top: Top (Top.html)
---
# 10.6. Limitations
There are two fundamental limitations on this profiler. The first is
that it relies on the Python interpreter to dispatch call,
return, and exception events. Compiled C code does not
get interpreted, and hence is ``invisible'' to the profiler. All time
spent in C code (including builtin functions) will be charged to the
Python function that invoked the C code. If the C code calls out
to some native Python code, then those calls will be profiled
properly.
The second limitation has to do with accuracy of timing information.
There is a fundamental problem with deterministic profilers involving
accuracy. The most obvious restriction is that the underlying ``clock''
is only ticking at a rate (typically) of about .001 seconds. Hence no
measurements will be more accurate that that underlying clock. If
enough measurements are taken, then the ``error'' will tend to average
out. Unfortunately, removing this first error induces a second source
of error...
The second problem is that it ``takes a while'' from when an event is
dispatched until the profiler's call to get the time actually
gets the state of the clock. Similarly, there is a certain lag
when exiting the profiler event handler from the time that the clock's
value was obtained (and then squirreled away), until the user's code
is once again executing. As a result, functions that are called many
times, or call many functions, will typically accumulate this error.
The error that accumulates in this fashion is typically less than the
accuracy of the clock (i.e., less than one clock tick), but it
can accumulate and become very significant. This profiler
provides a means of calibrating itself for a given platform so that
this error can be probabilistically (i.e., on the average) removed.
After the profiler is calibrated, it will be more accurate (in a least
square sense), but it will sometimes produce negative numbers (when
call counts are exceptionally low, and the gods of probability work
against you :-). ) Do NOT be alarmed by negative numbers in
the profile. They should only appear if you have calibrated
your profiler, and the results are actually better than without
calibration.
---
Prev: Reference Manual (Reference-Manual.html)
Top: Top (Top.html)
---


mac -- Python library reference

---
Prev: Macintosh Specific Services (Macintosh-Specific-Services.html)
Top: Top (Top.html)
---
# 14.1. Built-in Module `mac`
This module provides a subset of the operating system dependent
functionality provided by the optional built-in module `posix`.
It is best accessed through the more portable standard module
`os`.
The following functions are available in this module:
`chdir`,
`getcwd`,
`listdir`,
`mkdir`,
`rename`,
`rmdir`,
`stat`,
`sync`,
`unlink`,
as well as the exception `error`.
---
Prev: Macintosh Specific Services (Macintosh-Specific-Services.html)
Top: Top (Top.html)
---


macconsole options object -- Python library reference

---
Prev: macconsole (macconsole.html)
Top: Top (Top.html)
---
## 14.4.1. macconsole options object
These options are examined when a window is created:
---
Prev: macconsole (macconsole.html)
Top: Top (Top.html)
---


macconsole -- Python library reference

---
Prev: ctb (ctb.html)
Top: Top (Top.html)
---
# 14.4. Built-in Module `macconsole`
This module is available on the Macintosh, provided Python has been
built using the Think C compiler. It provides an interface to the
Think console package, with which basic text windows can be created.
## Menu
---
Prev: ctb (ctb.html)
Top: Top (Top.html)
---


macdnr -- Python library reference

---
Prev: macconsole (macconsole.html)
Top: Top (Top.html)
---
# 14.5. Built-in Module `macdnr`
This module provides an interface to the Macintosh Domain Name
Resolver. It is usually used in conjunction with the mactcp
module, to map hostnames to IP-addresses. It may not be available in
all Mac Python versions.
The `macdnr` module defines the following functions:
## Menu
---
Prev: macconsole (macconsole.html)
Top: Top (Top.html)
---


macfs -- Python library reference

---
Prev: macdnr (macdnr.html)
Top: Top (Top.html)
---
# 14.6. Built-in Module `macfs`
This module provides access to macintosh FSSpec handling, the Alias
Manager, finder aliases and the Standard File package.
Whenever a function or method expects a file argument, this
argument can be one of three things: (1) a full or partial Macintosh
pathname, (2) an FSSpec object or (3) a 3-tuple `(wdRefNum,
parID, name)` as described in Inside Mac VI.
and the standard file package can also be found there.
## Menu
---
Prev: macdnr (macdnr.html)
Top: Top (Top.html)
---


Macintosh Specific Services -- Python library reference

---
Prev: Cryptographic Services (Cryptographic-Services.html)
Top: Top (Top.html)
---
# 14. Macintosh Specific Services
The modules in this chapter are available on the Apple Macintosh only.
## Menu


MacOS -- Python library reference

---
Prev: macfs (macfs.html)
Top: Top (Top.html)
---
# 14.7. Built-in Module `MacOS`
This module provides access to MacOS specific functionality in the
python interpreter, such as how the interpreter eventloop functions
and the like. Use with care.
Note the capitalisation of the module name, this is a historical
artefact.
---
Prev: macfs (macfs.html)
Top: Top (Top.html)
---


macostools -- Python library reference

---
Prev: MacOS (MacOS.html)
Top: Top (Top.html)
---
# 14.8. Standard module `macostools`
This module contains some convenience routines for file-manipulation
on the Macintosh.
The `macostools` module defines the following functions:
Note that the process of creating finder aliases is not specified in
the Apple documentation. Hence, aliases created with `mkalias`
could conceivably have incompatible behaviour in some cases.
---
Prev: MacOS (MacOS.html)
Top: Top (Top.html)
---


macpath -- Python library reference

---
Prev: mac (mac.html)
Top: Top (Top.html)
---
# 14.2. Standard Module `macpath`
This module provides a subset of the pathname manipulation functions
available from the optional standard module `posixpath`. It is
best accessed through the more portable standard module `os`, as
`os.path`.
The following functions are available in this module:
`normcase`,
`isabs`,
`join`,
`split`,
`isdir`,
`isfile`,
`exists`.
---
Prev: mac (mac.html)
Top: Top (Top.html)
---


macspeech -- Python library reference

---
Prev: mactcp (mactcp.html)
Top: Top (Top.html)
---
# 14.10. Built-in Module `macspeech`
This module provides an interface to the Macintosh Speech Manager,
allowing you to let the Macintosh utter phrases. You need a version of
the speech manager extension (version 1 and 2 have been tested) in
your `Extensions` folder for this to work. The module does not
provide full access to all features of the Speech Manager yet. It may
not be available in all Mac Python versions.
## Menu
---
Prev: mactcp (mactcp.html)
Top: Top (Top.html)
---


mactcp -- Python library reference

---
Prev: macostools (macostools.html)
Top: Top (Top.html)
---
# 14.9. Built-in Module `mactcp`
This module provides an interface to the Macintosh TCP/IP driver
MacTCP.`macdnr` which provides an
interface to the name-server (allowing you to translate hostnames to
ip-addresses), a module `MACTCP` which has symbolic names for
constants constants used by MacTCP and a wrapper module `socket`
which mimics the UNIX socket interface (as far as possible). It may
not be available in all Mac Python versions.
A complete description of the MacTCP interface can be found in the
Apple MacTCP API documentation.
## Menu
---
Prev: macostools (macostools.html)
Top: Top (Top.html)
---


Mapping Types -- Python library reference

---
Prev: Sequence Types (Sequence-Types.html)
Top: Top (Top.html)
---
## 2.1.6. Mapping Types
A mapping object maps values of one type (the key type) to
arbitrary objects. Mappings are mutable objects. There is currently
only one standard mapping type, the dictionary. A dictionary's keys are
almost arbitrary values. The only types of values not acceptable as
keys are values containing lists or dictionaries or other mutable
types that are compared by value rather than by object identity.
Numeric types used for keys obey the normal rules for numeric
comparison: if two numbers compare equal (e.g. 1 and 1.0) then they
can be used interchangeably to index the same dictionary entry.
Dictionaries are created by placing a comma-separated list of
`key :,varvalue` pairs within braces, for example:
`{'jack':,4098, 'sjoerd':,4127}` or
`{4098:,'jack', 4127:,'sjoerd'}`.
The following operations are defined on mappings (where a is a
mapping, k is a key and x is an arbitrary object):
Notes:
---
Prev: Sequence Types (Sequence-Types.html)
Top: Top (Top.html)
---


marshal -- Python library reference

---
Prev: copy (copy.html)
Top: Top (Top.html)
---
# 3.7. Built-in Module `marshal`
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).(1) (#footnotetext1)
This is not a general ``persistency'' module. For general persistency
and transfer of Python objects through RPC calls, see the modules
`pickle` and `shelve`. 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, 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.(2) (#footnotetext2)
There are functions that read/write files as well as functions
operating on strings.
The module defines these functions:
## ---------- Footnotes ----------
(1) (#footnoteref1)
The name of this module stems from a bit of terminology used
by the designers of Modula-3 (amongst others), who use the term
``marshalling'' for shipping of data around in a self-contained form.
Strictly speaking, ``to marshal'' means to convert some data from
internal to external form (in an RPC buffer for instance) and
``unmarshalling'' for the reverse process.
(2) (#footnoteref2)
A solution would be to refuse such literals in the parser,
since they are inherently non-portable. Another solution would be to
let the `marshal` module raise an exception when an integer value
would be truncated. At least one of these solutions will be
implemented in a future version.
---
Prev: copy (copy.html)
Top: Top (Top.html)
---


math -- Python library reference

---
Prev: Miscellaneous Services (Miscellaneous-Services.html)
Top: Top (Top.html)
---
# 5.1. Built-in Module `math`
This module is always available.
It provides access to the mathematical functions defined by the C
standard.
They are:
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 `hypot` function, which is not standard C, is not available
on all platforms.
The module also defines two mathematical constants:
---
Prev: Miscellaneous Services (Miscellaneous-Services.html)
Top: Top (Top.html)
---


md5 -- Python library reference

---
Prev: Cryptographic Services (Cryptographic-Services.html)
Top: Top (Top.html)
---
# 13.1. Built-in Module `md5`
This module implements the interface to RSA's MD5 message digest
algorithm (see also Internet RFC 1321). Its use is quite
straightforward: use the `md5.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:
---
Prev: Cryptographic Services (Cryptographic-Services.html)
Top: Top (Top.html)
---


Menu Objects -- Python library reference

---
Prev: Drawing Objects (Drawing-Objects.html)
Top: Top (Top.html)
---
## 15.1.4. Menu Objects
A menu object represents a menu.
The menu is destroyed when the menu object is deleted.
The following methods are defined:
---
Prev: Drawing Objects (Drawing-Objects.html)
Top: Top (Top.html)
---


Message Objects -- Python library reference

---
Prev: rfc822 (rfc822.html)
Top: Top (Top.html)
---
## 11.10.1. Message Objects
A `Message` instance has the following methods:
`Message` instances also support a read-only mapping interface.
In particular: `m[name]` is the same as `m.getheader(name)`;
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:
---
Prev: rfc822 (rfc822.html)
Top: Top (Top.html)
---


Methods -- Python library reference

---
Prev: Functions (Functions.html)
Top: Top (Top.html)
---
### 2.1.7.4. Methods
Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods (such as `append()` on
lists) and class instance methods. Built-in methods are described
with the types that support them.
The implementation adds two special read-only attributes to class
instance methods: `m .im_self` is the object whose method this
is, and `m .im_func` is the function implementing the method.
Calling `m ( arg-1 , arg-2 , ... , arg-n )` is completely equivalent to calling
`m .im_func( m .im_self, arg-1 , arg-2 , ... , arg-n )`.
(See the Python Reference Manual for more info.)
---
Prev: Functions (Functions.html)
Top: Top (Top.html)
---


mimetools -- Python library reference

---
Prev: rfc822 (rfc822.html)
Top: Top (Top.html)
---
# 11.11. Standard Module `mimetools`
This module defines a subclass of the class `rfc822.Message` and
a number of utility functions that are useful for the manipulation for
MIME style multipart or encoded message.
It defines the following items:
## Menu
---
Prev: rfc822 (rfc822.html)
Top: Top (Top.html)
---


mimetools.Message Methods -- Python library reference

---
Prev: mimetools (mimetools.html)
Top: Top (Top.html)
---
## 11.11.1. Additional Methods of Message objects
The `mimetools.Message` class defines the following methods in
addition to the `rfc822.Message` class:
---
Prev: mimetools (mimetools.html)
Top: Top (Top.html)
---


Miscellaneous Services -- Python library reference

---
Prev: String Services (String-Services.html)
Top: Top (Top.html)
---
# 5. Miscellaneous Services
The modules described in this chapter provide miscellaneous services
that are available in all Python versions. Here's an overview:
## Menu
---
Prev: String Services (String-Services.html)
Top: Top (Top.html)
---


Module Index -- Python library reference

---
Prev: Variable Index (Variable-Index.html)
Top: Top (Top.html)
---
# Module Index
---
Prev: Variable Index (Variable-Index.html)
Top: Top (Top.html)
---


Modules -- Python library reference

---
Prev: Other Built-in Types (Other-Built-in-Types.html)
Top: Top (Top.html)
---
### 2.1.7.1. Modules
The only special operation on a module is attribute access:
`m . name`, where m is a module and name accesses
a name defined in m's symbol table. Module attributes can be
assigned to. (Note that the `import` statement is not, strictly
spoken, an operation on a module object; `import foo` does not
require a module object named foo to exist, rather it requires
an (external) definition for a module named foo
somewhere.)
A special member of every module is `__dict__`.
This is the dictionary containing the module's symbol table.
Modifying this dictionary will actually change the module's symbol
table, but direct assignment to the `__dict__` attribute is not
possible (i.e., you can write `m .__dict__['a'] = 1`, which
defines `m .a` to be `1`, but you can't write `m .__dict__ = {}`.
Modules are written like this: `<module 'sys'>`.
---
Prev: Other Built-in Types (Other-Built-in-Types.html)
Top: Top (Top.html)
---


More String Operations -- Python library reference

---
Prev: Sequence Types (Sequence-Types.html)
Top: Top (Top.html)
---
### 2.1.5.1. More String Operations
String objects have one unique built-in operation: the `%`
operator (modulo) with a string left argument interprets this string
as a C sprintf format string to be applied to the right argument, and
returns the string resulting from this formatting operation.
The right argument should be a tuple with one item for each argument
required by the format string; if the string requires a single
argument, the right argument may also be a single non-tuple object.(1) (#footnotetext1)
The following format characters are understood:
%, c, s, i, d, u, o, x, X, e, E, f, g, G.
Width and precision may be a * to specify that an integer argument
specifies the actual width or precision. The flag characters -, +,
blank, # and 0 are understood. The size specifiers h, l or L may be
present but are ignored. The `%s` conversion takes any Python
object and converts it to a string using `str()` before
formatting it. The ANSI features `%p` and `%n`
are not supported. Since Python strings have an explicit length,
`%s` conversions don't assume that `'\0'` is the end of
the string.
For safety reasons, floating point precisions are clipped to 50;
`%f` conversions for numbers whose absolute value is over 1e25
are replaced by `%g` conversions.(2) (#footnotetext2)
All other errors raise exceptions.
If the right argument is a dictionary (or any kind of mapping), then
the formats in the string must have a parenthesized key into that
dictionary inserted immediately after the `%` character, and
each format formats the corresponding entry from the mapping. E.g.
```text
>>> count = 2

>>> language = 'Python'

>>> print '%(language)s has %(count)03d quote types.' % vars()

Python has 002 quote types.

>>>
```
In this case no * specifiers may occur in a format (since they a
require sequential parameter list).
Additional string operations are defined in standard module
`string` and in built-in module `regex`.
## ---------- Footnotes ----------
(1) (#footnoteref1)
A tuple object in this case should be a singleton.
(2) (#footnoteref2)
These numbers are fairly arbitrary. They are intended to
avoid printing endless strings of meaningless digits without hampering
correct use and without having to know the exact precision of floating
point values on a particular machine.
---
Prev: Sequence Types (Sequence-Types.html)
Top: Top (Top.html)
---


mpz -- Python library reference

---
Prev: md5 (md5.html)
Top: Top (Top.html)
---
# 13.2. Built-in Module `mpz`
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.
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 called `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:
---
Prev: md5 (md5.html)
Top: Top (Top.html)
---


Multimedia Services -- Python library reference

---
Prev: Internet and WWW (Internet-and-WWW.html)
Top: Top (Top.html)
---
# 12. 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:
## Menu
---
Prev: Internet and WWW (Internet-and-WWW.html)
Top: Top (Top.html)
---


Mutable Sequence Types -- Python library reference

---
Prev: More String Operations (More-String-Operations.html)
Top: Top (Top.html)
---
### 2.1.5.2. Mutable Sequence Types
List objects support additional operations that allow in-place
modification of the object.
These operations would be supported by other mutable sequence types
(when added to the language) as well.
Strings and tuples are immutable sequence types and such objects cannot
be modified once created.
The following operations are defined on mutable sequence types (where
x is an arbitrary object):
Notes:
---
Prev: More String Operations (More-String-Operations.html)
Top: Top (Top.html)
---


NNTP Objects -- Python library reference

---
Prev: nntplib (nntplib.html)
Top: Top (Top.html)
---
## 11.6.1. NNTP Objects
NNTP instances have the following methods. The response that is
returned as the first item in the return tuple of almost all methods
is the server's response: a string beginning with a three-digit code.
If the server's response indicates an error, the method raises one of
the above exceptions.
---
Prev: nntplib (nntplib.html)
Top: Top (Top.html)
---


nntplib -- Python library reference

---
Prev: gopherlib (gopherlib.html)
Top: Top (Top.html)
---
# 11.6. Standard Module `nntplib`
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.
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:
## Menu
---
Prev: gopherlib (gopherlib.html)
Top: Top (Top.html)
---


notes -- Python library reference

---
Prev: binhex (binhex.html)
Top: Top (Top.html)
---
## 11.12.1. notes
There is an alternative, more powerful interface to the coder and
decoder, see the source for details.
If you code or decode textfiles on non-Macintosh platforms they will
still use the macintosh newline convention (carriage-return as end of
line).
As of this writing, hexbin appears to not work in all cases.
---
Prev: binhex (binhex.html)
Top: Top (Top.html)
---


Numeric Types -- Python library reference

---
Prev: Comparisons (Comparisons.html)
Top: Top (Top.html)
---
## 2.1.4. Numeric Types
There are three numeric types: plain integers, long integers, and
floating point numbers. Plain integers (also just called integers)
are implemented using `long` in C, which gives them at least 32
bits of precision. Long integers have unlimited precision. Floating
point numbers are implemented using `double` in C. All bets on
their precision are off unless you happen to know the machine you are
working with.
Numbers are created by numeric literals or as the result of built-in
functions and operators. Unadorned integer literals (including hex
and octal numbers) yield plain integers. Integer literals with an `L'
or `l' suffix yield long integers
(`L' is preferred because `1l` looks too much like eleven!).
Numeric literals containing a decimal point or an exponent sign yield
floating point numbers.
Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
``smaller'' type is converted to that of the other, where plain
integer is smaller than long integer is smaller than floating point.
Comparisons between numbers of mixed type use the same rule.(1) (#footnotetext1)
The functions `int()`, `long()` and `float()` can be used
to coerce numbers to a specific type.
All numeric types support the following operations, sorted by
ascending priority (operations in the same box have the same
priority; all numeric operations have a higher priority than
comparison operations):
Notes:
## Menu
## ---------- Footnotes ----------
(1) (#footnoteref1)
As a consequence, the list `[1, 2]` is considered equal
to `[1.0, 2.0]`, and similar for tuples.
---
Prev: Comparisons (Comparisons.html)
Top: Top (Top.html)
---


OldProfile Class -- Python library reference

---
Prev: Profiler Extensions (Profiler-Extensions.html)
Top: Top (Top.html)
---
## 10.8.1. OldProfile Class
The following derived profiler simulates the old style profiler,
providing errant results on recursive functions. The reason for the
usefulness of this profiler is that it runs faster (i.e., less
overhead) than the old profiler. It still creates all the caller
stats, and is quite useful when there is no recursion in the
user's code. It is also a lot more accurate than the old profiler, as
it does not charge all its overhead time to the user's code.
```text
class OldProfile(Profile):

def trace_dispatch_exception(self, frame, t):

rt, rtt, rct, rfn, rframe, rcur = self.cur

if rcur and not rframe is frame:

return self.trace_dispatch_return(rframe, t)

return 0

def trace_dispatch_call(self, frame, t):

fn = `frame.f_code`

self.cur = (t, 0, 0, fn, frame, self.cur)

if self.timings.has_key(fn):

tt, ct, callers = self.timings[fn]

self.timings[fn] = tt, ct, callers

else:

self.timings[fn] = 0, 0, {}

return 1

def trace_dispatch_return(self, frame, t):

rt, rtt, rct, rfn, frame, rcur = self.cur

rtt = rtt + t

sft = rtt + rct

pt, ptt, pct, pfn, pframe, pcur = rcur

self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur

tt, ct, callers = self.timings[rfn]

if callers.has_key(pfn):

callers[pfn] = callers[pfn] + 1

else:

callers[pfn] = 1

self.timings[rfn] = tt+rtt, ct + sft, callers

return 1

def snapshot_stats(self):

self.stats = {}

for func in self.timings.keys():

tt, ct, callers = self.timings[func]

nor_func = self.func_normalize(func)

nor_callers = {}

nc = 0

for func_caller in callers.keys():

nor_callers[self.func_normalize(func_caller)]=\

callers[func_caller]

nc = nc + callers[func_caller]

self.stats[nor_func] = nc, nc, tt, ct, nor_callers
```
---
Prev: Profiler Extensions (Profiler-Extensions.html)
Top: Top (Top.html)
---


Optional Operating System Services -- Python library reference

---
Prev: Generic Operating System Services (Generic-Operating-System-Services.html)
Top: Top (Top.html)
---
# 7. Optional Operating System Services
The modules described in this chapter provide interfaces to operating
system features that are available on selected operating systems only.
The interfaces are generally modelled after the UNIX or C
interfaces but they are available on some other systems as well
(e.g. Windows or NT). Here's an overview:
## Menu
---
Prev: Generic Operating System Services (Generic-Operating-System-Services.html)
Top: Top (Top.html)
---


os -- Python library reference

---
Prev: Generic Operating System Services (Generic-Operating-System-Services.html)
Top: Top (Top.html)
---
# 6.1. Standard Module `os`
This module provides a more portable way of using operating system
(OS) dependent functionality than importing an OS dependent built-in
module like `posix`.
When the optional built-in module `posix` is available, this
module exports the same functions and data as `posix`; otherwise,
it searches for an OS dependent built-in module like `mac` 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( file )` returns stat info about a file in a
format compatible 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`!
In addition to whatever the correct OS dependent module exports, the
following variables and functions are always exported by `os`:
(The functions `os.execv()` and `execve()` are not
documented here, since they are implemented by the OS dependent
module. If the OS dependent module doesn't define either of these,
the functions that rely on it will raise an exception. They are
documented in the section on module `posix`, together with all
other functions that `os` imports from the OS dependent module.)
---
Prev: Generic Operating System Services (Generic-Operating-System-Services.html)
Top: Top (Top.html)
---


Other Built-in Types -- Python library reference

---
Prev: Mapping Types (Mapping-Types.html)
Top: Top (Top.html)
---
## 2.1.7. Other Built-in Types
The interpreter supports several other kinds of objects.
Most of these support only one or two operations.
## Menu


parser -- Python library reference

---
Prev: imp (imp.html)
Top: Top (Top.html)
---
# 3.9. Built-in Module `parser`
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 can be better than trying
to parse and modify an arbitrary Python code fragment as a string, and
ensures that parsing is performed in a manner identical to the code
forming the application. It's 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.
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 Language Reference. 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 `tuple2ast()` faithfully simulate those
structures.
Each element of the tuples returned by `ast2tuple()` has a simple
form. Tuples 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 `Lib/symbol.py`. Each additional element of the
tuple represents a component of the production as recognized in the
input string: these are always tuples 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` elements, including
variable and function names defined by the user.
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
`Lib/token.py`.
The AST objects are not actually 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 tuple representation, and to ease the creation
of additional modules in C which manipulate parse trees. A simple
``wrapper'' module may be created in Python if desired to hide the use
of AST objects.
The `parser` module defines the following functions:
## Menu
---
Prev: imp (imp.html)
Top: Top (Top.html)
---


pickle -- Python library reference

---
Prev: traceback (traceback.html)
Top: Top (Top.html)
---
# 3.4. Standard Module `pickle`
The `pickle` module implements a basic but powerful algorithm for
``pickling'' (a.k.a. serializing, marshalling or flattening) nearly
arbitrary Python objects. This is the act of converting objects to a
stream of bytes (and back: ``unpickling'').
This is a more primitive notion than
persistency --- although `pickle` reads and writes file objects,
it does not handle the issue of naming persistent objects, nor the
(even more complicated) area of concurrent access to persistent
objects. The `pickle` module can transform a complex object into
a byte stream and it can transform the byte stream into an object with
the same internal structure. The most obvious thing to do with these
byte streams is to write them onto a file, but it is also conceivable
to send them across a network or store them in a database. The module
`shelve` provides a simple interface to pickle and unpickle
objects on ``dbm''-style database files.
Unlike the built-in module `marshal`, `pickle` handles the
following correctly:
- recursive objects (objects containing references to themselves)
object sharing (references to the same object in different places)
user-defined classes and their instances
The data format used by `pickle` is Python-specific. This has
the advantage that there are no restrictions imposed by external
standards such as CORBA (which probably can't represent pointer
sharing or recursive objects); however it means that non-Python
programs may not be able to reconstruct pickled Python objects.
The `pickle` data format uses a printable ASCII representation.
This is slightly more voluminous than a binary representation.
However, small integers actually take less space when
represented as minimal-size decimal strings than when represented as
32-bit binary numbers, and strings are only much longer if they
contain many control characters or 8-bit characters. The big
advantage of using printable ASCII (and of some other characteristics
of `pickle`'s representation) is that for debugging or recovery
purposes it is possible for a human to read the pickled file with a
standard text editor. (I could have gone a step further and used a
notation like S-expressions, but the parser
(currently written in Python) would have been
considerably more complicated and slower, and the files would probably
have become much larger.)
The `pickle` module doesn't handle code objects, which the
`marshal` module does. I suppose `pickle` could, and maybe
it should, but there's probably no great need for it right now (as
long as `marshal` continues to be used for reading and writing
code objects), and at least this avoids the possibility of smuggling
Trojan horses into a program.
For the benefit of persistency modules written using `pickle`, it
supports the notion of a reference to an object outside the pickled
data stream. Such objects are referenced by a name, which is an
arbitrary string of printable ASCII characters. The resolution of
such names is not defined by the `pickle` module --- the
persistent object module will have to implement a method
`persistent_load`. To write references to persistent objects,
the persistent module must define a method `persistent_id` which
returns either `None` or the persistent ID of the object.
There are some restrictions on the pickling of class instances.
First of all, the class must be defined at the top level in a module.
Next, it must normally be possible to create class instances by
calling the class without arguments. If this is undesirable, the
class can define a method `__getinitargs__()`, which should
return a tuple containing the arguments to be passed to the
class constructor (`__init__()`).
Classes can further influence how their instances are pickled --- if the class
defines the method `__getstate__()`, it is called and the return
state is pickled as the contents for the instance, and if the class
defines the method `__setstate__()`, it is called with the
unpickled state. (Note that these methods can also be used to
implement copying class instances.) If there is no
`__getstate__()` method, the instance's `__dict__` is
pickled. If there is no `__setstate__()` method, the pickled
object must be a dictionary and its items are assigned to the new
instance's dictionary. (If a class defines both `__getstate__()`
and `__setstate__()`, the state object needn't be a dictionary
--- these methods can do what they want.) This protocol is also used
by the shallow and deep copying operations defined in the `copy`
module.
Note that when class instances are pickled, their class's code and
data are not pickled along with them. Only the instance data are
pickled. This is done on purpose, so you can fix bugs in a class or
add methods and still load objects that were created with an earlier
version of the class. If you plan to have long-lived objects that
will see many versions of a class, it may be worthwhile to put a version
number in the objects so that suitable conversions can be made by the
class's `__setstate__()` method.
When a class itself is pickled, only its name is pickled --- the class
definition is not pickled, but re-imported by the unpickling process.
Therefore, the restriction that the class must be defined at the top
level in a module applies to pickled classes as well.
The interface can be summarized as follows.
To pickle an object `x` onto a file `f`, open for writing:
```text
p = pickle.Pickler(f)

p.dump(x)
```
A shorthand for this is:
```text
pickle.dump(x, f)
```
To unpickle an object `x` from a file `f`, open for reading:
```text
u = pickle.Unpickler(f)

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


Port Objects -- Python library reference

---
Prev: Configuration Objects (Configuration-Objects.html)
Top: Top (Top.html)
---
## 16.1.2. Port Objects
Port objects (returned by `al.openport()` have the following
methods:
---
Prev: Configuration Objects (Configuration-Objects.html)
Top: Top (Top.html)
---


posix -- Python library reference

---
Prev: UNIX Specific Services (UNIX-Specific-Services.html)
Top: Top (Top.html)
---
# 8.1. Built-in Module `posix`
This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly disguised
UNIX interface).
Do not import this module directly. Instead, import the
module `os`, which provides a portable version of this
interface. On UNIX, the `os` module provides a superset of
the `posix` interface. On non-UNIX operating systems the
`posix` module is not available, but a subset is always available
through the `os` interface. Once `os` is imported, there is
no performance penalty in using it instead of
`posix`.
The descriptions below are very terse; refer to the
corresponding UNIX manual entry for more information. Arguments
called path refer to a pathname given as a string.
Errors are reported as exceptions; the usual exceptions are given
for type errors, while errors reported by the system calls raise
`posix.error`, described below.
Module `posix` defines the following data items:
It defines the following functions and constants:
## ---------- Footnotes ----------
(1) (#footnoteref1)
The problem with automatically passing on `environ` is
that there is no portable way of changing the environment.
---
Prev: UNIX Specific Services (UNIX-Specific-Services.html)
Top: Top (Top.html)
---


posixfile -- Python library reference

---
Prev: fcntl (fcntl.html)
Top: Top (Top.html)
---
# 8.10. Standard Module `posixfile`
This module implements some additional functionality over the built-in
file objects. In particular, it implements file locking, control over
the file flags, and an easy interface to duplicate the file object.
The module defines a new file object, the posixfile object. It
has all the standard file object methods and adds the methods
described below. This module only works for certain flavors of
UNIX, since it uses `fcntl()` for file locking.
To instantiate a posixfile object, use the `open()` function in
the posixfile module. The resulting object looks and feels roughly
the same as a standard file object.
The posixfile module defines the following constants:
The posixfile module defines the following functions:
The posixfile object defines the following additional methods:
All methods return `IOError` when the request fails.
Format characters for the `lock()` method have the following meaning:
In addition the following modifiers can be added to the format:
Note:
(1) The lock returned is in the format `(mode, len, start,
whence, pid)` where mode is a character representing the type of lock
('r' or 'w'). This modifier prevents a request from being granted; it
is for query purposes only.
Format character for the `flags()` method have the following meaning:
In addition the following modifiers can be added to the format:
Note:
(1) The `!` and `=` modifiers are mutually exclusive.
(2) This string represents the flags after they may have been altered
by the same call.
Examples:
```text
from posixfile import *

file = open('/tmp/test', 'w')

file.lock('w|')

...

file.lock('u')

file.close()
```
---
Prev: fcntl (fcntl.html)
Top: Top (Top.html)
---


posixpath -- Python library reference

---
Prev: posix (posix.html)
Top: Top (Top.html)
---
# 8.2. Standard Module `posixpath`
This module implements some useful functions on POSIX pathnames.
Do not import this module directly. Instead, import the
module `os` and use `os.path`.
---
Prev: posix (posix.html)
Top: Top (Top.html)
---


Profiler Changes -- Python library reference

---
Prev: Profiler Introduction (Profiler-Introduction.html)
Top: Top (Top.html)
---
# 10.2. How Is This Profiler Different From The Old Profiler?
The big changes from old profiling module are that you get more
information, and you pay less CPU time. It's not a trade-off, it's a
trade-up.
To be specific:
---
Prev: Profiler Introduction (Profiler-Introduction.html)
Top: Top (Top.html)
---


Profiler Extensions -- Python library reference

---
Prev: Calibration (Calibration.html)
Top: Top (Top.html)
---
# 10.8. Extensions --- Deriving Better Profilers
The `Profile` class of module `profile` was written so that
derived classes could be developed to extend the profiler. Rather
than describing all the details of such an effort, I'll just present
the following two examples of derived classes that can be used to do
profiling. If the reader is an avid Python programmer, then it should
be possible to use these as a model and create similar (and perchance
better) profile classes.
If all you want to do is change how the timer is called, or which
timer function is used, then the basic class has an option for that in
the constructor for the class. Consider passing the name of a
function to call into the constructor:
```text
pr = profile.Profile(your_time_func)
```
The resulting profiler will call `your_time_func()` instead of
`os.times()`. The function should return either a single number
or a list of numbers (like what `os.times()` returns). If the
function returns a single time number, or the list of returned numbers
has length 2, then you will get an especially fast version of the
dispatch routine.
Be warned that you should calibrate the profiler class for the
timer function that you choose. For most machines, a timer that
returns a lone integer value will provide the best results in terms of
low overhead during profiling. (os.times is pretty bad, 'cause
it returns a tuple of floating point values, so all arithmetic is
floating point in the profiler!). If you want to substitute a
better timer in the cleanest fashion, you should derive a class, and
simply put in the replacement dispatch method that better handles your
timer call, along with the appropriate calibration constant :-).
## Menu
---
Prev: Calibration (Calibration.html)
Top: Top (Top.html)
---


Profiler Introduction -- Python library reference

---
Prev: The Python Profiler (The-Python-Profiler.html)
Top: Top (Top.html)
---
# 10.1. Introduction to the profiler
A profiler is a program that describes the run time performance
of a program, providing a variety of statistics. This documentation
describes the profiler functionality provided in the modules
`profile` and `pstats.` This profiler provides
deterministic profiling of any Python programs. It also
provides a series of report generation tools to allow users to rapidly
examine the results of a profile operation.
---
Prev: The Python Profiler (The-Python-Profiler.html)
Top: Top (Top.html)
---


pwd -- Python library reference

---
Prev: posixpath (posixpath.html)
Top: Top (Top.html)
---
# 8.3. Built-in Module `pwd`
This module provides access to the UNIX password database.
It is available on all UNIX versions.
Password database entries are reported as 7-tuples containing the
following items from the password database (see <pwd.h>), in order:
`pw_name`,
`pw_passwd`,
`pw_uid`,
`pw_gid`,
`pw_gecos`,
`pw_dir`,
`pw_shell`.
The uid and gid items are integers, all others are strings.
An exception is raised if the entry asked for cannot be found.
It defines the following items:
---
Prev: posixpath (posixpath.html)
Top: Top (Top.html)
---


Python Services -- Python library reference

---
Prev: Built-in Objects (Built-in-Objects.html)
Top: Top (Top.html)
---
# 3. Python Services
The modules described in this chapter provide a wide range of services
related to the Python interpreter and its interaction with its
environment. Here's an overview:
## Menu
---
Prev: Built-in Objects (Built-in-Objects.html)
Top: Top (Top.html)
---


rand -- Python library reference

---
Prev: math (math.html)
Top: Top (Top.html)
---
# 5.2. Standard Module `rand`
This module implements a pseudo-random number
generator with an interface similar to `rand()` in C.
the following functions:
---
Prev: math (math.html)
Top: Top (Top.html)
---


rect -- Python library reference

---
Prev: stdwinevents (stdwinevents.html)
Top: Top (Top.html)
---
# 15.3. Standard Module `rect`
This module contains useful operations on rectangles.
A rectangle is defined as in module
`stdwin`:
a pair of points, where a point is a pair of integers.
For example, the rectangle
```text
(10, 20), (90, 80)
```
is a rectangle whose left, top, right and bottom edges are 10, 20, 90
and 80, respectively.
Note that the positive vertical axis points down (as in
`stdwin`).
The module defines the following objects:
---
Prev: stdwinevents (stdwinevents.html)
Top: Top (Top.html)
---


Reference Manual -- Python library reference

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


regex -- Python library reference

---
Prev: string (string.html)
Top: Top (Top.html)
---
# 4.2. Built-in Module `regex`
This module provides regular expression matching operations similar to
those found in Emacs. It is always available.
By default the patterns are Emacs-style regular expressions,
with one exception. There is
a way to change the syntax to match that of several well-known
UNIX utilities. The exception is that Emacs' `\s'
pattern is not supported, since the original implementation references
the Emacs syntax tables.
This module is 8-bit clean: both patterns and strings may contain null
bytes and characters whose high bit is set.
Please note: There is a little-known fact about Python string
literals which means that you don't usually have to worry about
doubling backslashes, even though they are used to escape special
characters in string literals as well as in regular expressions. This
is because Python doesn't remove backslashes from string literals if
they are followed by an unrecognized escape character.
However, if you want to include a literal backslash in a
regular expression represented as a string literal, you have to
quadruple it. E.g. to extract LaTeX `\section{...}' headers from a document, you can use this pattern:
`'\\\\section{\(.*\)}'`.
The module defines these functions, and an exception:
Compiled regular expression objects support these methods:
Compiled regular expressions support these data attributes:
---
Prev: string (string.html)
Top: Top (Top.html)
---


regsub -- Python library reference

---
Prev: regex (regex.html)
Top: Top (Top.html)
---
# 4.3. Standard Module `regsub`
This module defines a number of functions useful for working with
regular expressions (see built-in module `regex`).
---
Prev: regex (regex.html)
Top: Top (Top.html)
---