Commit 5fdeeeae authored by Guido van Rossum's avatar Guido van Rossum

Restructured library documentation

parent 0b071986
\section{Built-in Module \sectcode{al}}
\bimodindex{al}
This module provides access to the audio facilities of the Indigo and
4D/35 workstations, described in section 3A of the IRIX 4.0 man pages
(and also available as an option in IRIX 3.3). You'll need to read
those man pages to understand what these functions do!
Some of the functions are not available in releases below 4.0.5.
Again, see the manual to check whether a specific function is
available on your platform.
Symbolic constants from the C header file \file{<audio.h>} are defined
in the standard module \code{AL}, see below.
\strong{Warning:} the current version of the audio library may dump core
when bad argument values are passed rather than returning an error
status. Unfortunately, since the precise circumstances under which
this may happen are undocumented and hard to check, the Python
interface can provide no protection against this kind of problems.
(One example is specifying an excessive queue size --- there is no
documented upper limit.)
Module \code{al} defines the following functions:
\renewcommand{\indexsubitem}{(in module al)}
\begin{funcdesc}{openport}{name\, direction\, config}
Equivalent to the C function ALopenport(). The name and direction
arguments are strings. The optional config argument is an opaque
configuration object as returned by \code{al.newconfig()}. The return
value is an opaque port object; methods of port objects are described
below.
\end{funcdesc}
\begin{funcdesc}{newconfig}{}
Equivalent to the C function ALnewconfig(). The return value is a new
opaque configuration object; methods of configuration objects are
described below.
\end{funcdesc}
\begin{funcdesc}{queryparams}{device}
Equivalent to the C function ALqueryparams(). The device argument is
an integer. The return value is a list of integers containing the
data returned by ALqueryparams().
\end{funcdesc}
\begin{funcdesc}{getparams}{device\, list}
Equivalent to the C function ALgetparams(). The device argument is an
integer. The list argument is a list such as returned by
\code{queryparams}; it is modified in place (!).
\end{funcdesc}
\begin{funcdesc}{setparams}{device\, list}
Equivalent to the C function ALsetparams(). The device argument is an
integer.The list argument is a list such as returned by
\code{al.queryparams}.
\end{funcdesc}
Configuration objects (returned by \code{al.newconfig()} have the
following methods:
\renewcommand{\indexsubitem}{(audio configuration object method)}
\begin{funcdesc}{getqueuesize}{}
Return the queue size; equivalent to the C function ALgetqueuesize().
\end{funcdesc}
\begin{funcdesc}{setqueuesize}{size}
Set the queue size; equivalent to the C function ALsetqueuesize().
\end{funcdesc}
\begin{funcdesc}{getwidth}{}
Get the sample width; equivalent to the C function ALgetwidth().
\end{funcdesc}
\begin{funcdesc}{getwidth}{width}
Set the sample width; equivalent to the C function ALsetwidth().
\end{funcdesc}
\begin{funcdesc}{getchannels}{}
Get the channel count; equivalent to the C function ALgetchannels().
\end{funcdesc}
\begin{funcdesc}{setchannels}{nchannels}
Set the channel count; equivalent to the C function ALsetchannels().
\end{funcdesc}
\begin{funcdesc}{getsampfmt}{}
Get the sample format; equivalent to the C function ALgetsampfmt().
\end{funcdesc}
\begin{funcdesc}{setsampfmt}{sampfmt}
Set the sample format; equivalent to the C function ALsetsampfmt().
\end{funcdesc}
\begin{funcdesc}{getfloatmax}{}
Get the maximum value for floating sample formats;
equivalent to the C function ALgetfloatmax().
\end{funcdesc}
\begin{funcdesc}{setfloatmax}{floatmax}
Set the maximum value for floating sample formats;
equivalent to the C function ALsetfloatmax().
\end{funcdesc}
Port objects (returned by \code{al.openport()} have the following
methods:
\renewcommand{\indexsubitem}{(audio port object method)}
\begin{funcdesc}{closeport}{}
Close the port; equivalent to the C function ALcloseport().
\end{funcdesc}
\begin{funcdesc}{getfd}{}
Return the file descriptor as an int; equivalent to the C function
ALgetfd().
\end{funcdesc}
\begin{funcdesc}{getfilled}{}
Return the number of filled samples; equivalent to the C function
ALgetfilled().
\end{funcdesc}
\begin{funcdesc}{getfillable}{}
Return the number of fillable samples; equivalent to the C function
ALgetfillable().
\end{funcdesc}
\begin{funcdesc}{readsamps}{nsamples}
Read a number of samples from the queue, blocking if necessary;
equivalent to the C function ALreadsamples. The data is returned as a
string containing the raw data (e.g. 2 bytes per sample in big-endian
byte order (high byte, low byte) if you have set the sample width to 2
bytes.
\end{funcdesc}
\begin{funcdesc}{writesamps}{samples}
Write samples into the queue, blocking if necessary; equivalent to the
C function ALwritesamples. The samples are encoded as described for
the \code{readsamps} return value.
\end{funcdesc}
\begin{funcdesc}{getfillpoint}{}
Return the `fill point'; equivalent to the C function ALgetfillpoint().
\end{funcdesc}
\begin{funcdesc}{setfillpoint}{fillpoint}
Set the `fill point'; equivalent to the C function ALsetfillpoint().
\end{funcdesc}
\begin{funcdesc}{getconfig}{}
Return a configuration object containing the current configuration of
the port; equivalent to the C function ALgetconfig().
\end{funcdesc}
\begin{funcdesc}{setconfig}{config}
Set the configuration from the argument, a configuration object;
equivalent to the C function ALsetconfig().
\end{funcdesc}
\begin{funcdesc}{getstatus}{list}
Get status information on last error
equivalent to C function ALgetstatus().
\end{funcdesc}
\section{Standard Module \sectcode{AL}}
\nodename{AL (uppercase)}
\stmodindex{AL}
This module defines symbolic constants needed to use the built-in
module \code{al} (see above); they are equivalent to those defined in
the C header file \file{<audio.h>} except that the name prefix
\samp{AL_} is omitted. Read the module source for a complete list of
the defined names. Suggested use:
\bcode\begin{verbatim}
import al
from AL import *
\end{verbatim}\ecode
\chapter{AMOEBA ONLY}
\section{Built-in Module \sectcode{amoeba}}
\bimodindex{amoeba}
This module provides some object types and operations useful for
Amoeba applications. It is only available on systems that support
Amoeba operations. RPC errors and other Amoeba errors are reported as
the exception \code{amoeba.error = 'amoeba.error'}.
The module \code{amoeba} defines the following items:
\renewcommand{\indexsubitem}{(in module amoeba)}
\begin{funcdesc}{name_append}{path\, cap}
Stores a capability in the Amoeba directory tree.
Arguments are the pathname (a string) and the capability (a capability
object as returned by
\code{name_lookup()}).
\end{funcdesc}
\begin{funcdesc}{name_delete}{path}
Deletes a capability from the Amoeba directory tree.
Argument is the pathname.
\end{funcdesc}
\begin{funcdesc}{name_lookup}{path}
Looks up a capability.
Argument is the pathname.
Returns a
\dfn{capability}
object, to which various interesting operations apply, described below.
\end{funcdesc}
\begin{funcdesc}{name_replace}{path\, cap}
Replaces a capability in the Amoeba directory tree.
Arguments are the pathname and the new capability.
(This differs from
\code{name_append()}
in the behavior when the pathname already exists:
\code{name_append()}
finds this an error while
\code{name_replace()}
allows it, as its name suggests.)
\end{funcdesc}
\begin{datadesc}{capv}
A table representing the capability environment at the time the
interpreter was started.
(Alas, modifying this table does not affect the capability environment
of the interpreter.)
For example,
\code{amoeba.capv['ROOT']}
is the capability of your root directory, similar to
\code{getcap("ROOT")}
in C.
\end{datadesc}
\begin{excdesc}{error}
The exception raised when an Amoeba function returns an error.
The value accompanying this exception is a pair containing the numeric
error code and the corresponding string, as returned by the C function
\code{err_why()}.
\end{excdesc}
\begin{funcdesc}{timeout}{msecs}
Sets the transaction timeout, in milliseconds.
Returns the previous timeout.
Initially, the timeout is set to 2 seconds by the Python interpreter.
\end{funcdesc}
\subsection{Capability Operations}
Capabilities are written in a convenient ASCII format, also used by the
Amoeba utilities
{\it c2a}(U)
and
{\it a2c}(U).
For example:
\bcode\begin{verbatim}
>>> amoeba.name_lookup('/profile/cap')
aa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a
>>>
\end{verbatim}\ecode
The following methods are defined for capability objects.
\renewcommand{\indexsubitem}{(capability method)}
\begin{funcdesc}{dir_list}{}
Returns a list of the names of the entries in an Amoeba directory.
\end{funcdesc}
\begin{funcdesc}{b_read}{offset\, maxsize}
Reads (at most)
\var{maxsize}
bytes from a bullet file at offset
\var{offset.}
The data is returned as a string.
EOF is reported as an empty string.
\end{funcdesc}
\begin{funcdesc}{b_size}{}
Returns the size of a bullet file.
\end{funcdesc}
\begin{funcdesc}{dir_append}{}
\funcline{dir_delete}{}\
\funcline{dir_lookup}{}\
\funcline{dir_replace}{}
Like the corresponding
\samp{name_}*
functions, but with a path relative to the capability.
(For paths beginning with a slash the capability is ignored, since this
is the defined semantics for Amoeba.)
\end{funcdesc}
\begin{funcdesc}{std_info}{}
Returns the standard info string of the object.
\end{funcdesc}
\begin{funcdesc}{tod_gettime}{}
Returns the time (in seconds since the Epoch, in UCT, as for POSIX) from
a time server.
\end{funcdesc}
\begin{funcdesc}{tod_settime}{t}
Sets the time kept by a time server.
\end{funcdesc}
\section{Built-in module \sectcode{array}}
\bimodindex{array}
\index{arrays}
This module defines a new object type which can efficiently represent
an array of basic values: characters, integers, floating point
numbers. Arrays are sequence types and behave very much like lists,
except that the type of objects stored in them is constrained. The
type is specified at object creation time by using a \dfn{type code},
which is a single character. The following type codes are defined:
\begin{tableiii}{|c|c|c|}{code}{Typecode}{Type}{Minimal size in bytes}
\lineiii{'c'}{character}{1}
\lineiii{'b'}{signed integer}{1}
\lineiii{'h'}{signed integer}{2}
\lineiii{'i'}{signed integer}{2}
\lineiii{'l'}{signed integer}{4}
\lineiii{'f'}{floating point}{4}
\lineiii{'d'}{floating point}{8}
\end{tableiii}
The actual representation of values is determined by the machine
architecture (strictly spoken, by the C implementation). The actual
size can be accessed through the \var{typecode} attribute.
The module defines the following function:
\renewcommand{\indexsubitem}{(in module array)}
\begin{funcdesc}{array}{typecode\, initializer}
Return a new array whose items are restricted by \var{typecode}, and
initialized from the optional \var{initializer} value, which must be a
list or a string. The list or string is passed to the new array's
\code{fromlist()} or \code{fromstring()} method (see below) to add
initial items to the array.
\end{funcdesc}
Array objects support the following data items and methods:
\begin{datadesc}{typecode}
The typecode character used to create the array.
\end{datadesc}
\begin{datadesc}{itemsize}
The length in bytes of one array item in the internal representation.
\end{datadesc}
\begin{funcdesc}{append}{x}
Append a new item with value \var{x} to the end of the array.
\end{funcdesc}
\begin{funcdesc}{byteswap}{x}
``Byteswap'' all items of the array. This is only supported for
integer values. It is useful when reading data ffrom a file written
on a machine with a different byte order.
\end{funcdesc}
\begin{funcdesc}{fromfile}{f\, n}
Read \var{n} items (as machine values) from the file object \var{f}
and append them to the end of the array. If less than \var{n} items
are available, \code{EOFError} is raised, but the items that were
available are still inserted into the array.
\end{funcdesc}
\begin{funcdesc}{fromlist}{list}
Appends items from the list. This is equivalent to
\code{for x in \var{list}: a.append(x)}
except that if there is a type error, the array is unchanged.
\end{funcdesc}
\begin{funcdesc}{fromstring}{s}
Appends items from the string, interpreting the string as an
array of machine values (i.e. as if it had been read from a
file using the \code{fromfile()} method).
\end{funcdesc}
\begin{funcdesc}{insert}{i\, x}
Insert a new item with value \var{x} in the array before position
\var{i}.
\end{funcdesc}
\begin{funcdesc}{tofile}{f}
Write all items (as machine values) to the file object \var{f}.
\end{funcdesc}
\begin{funcdesc}{tolist}{}
Convert the array to an ordinary list with the same items.
\end{funcdesc}
\begin{funcdesc}{tostring}{}
Convert the array to an array of machine values and return the
string representation (the same sequence of bytes that would
be written to a file by the \code{tofile()} method.)
\end{funcdesc}
When an array object is printed or converted to a string, it is
represented as \code{array(\var{typecode}, \var{initializer})}. The
\var{initializer} is omitted if the array is empty, otherwise it is a
string if the \var{typecode} is \code{'c'}, otherwise it is a list of
numbers. The string is guaranteed to be able to be converted back to
an array with the same type and value using reverse quotes
(\code{``}). Examples:
\bcode\begin{verbatim}
array('l')
array('c', 'hello world')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])
\end{verbatim}\ecode
This diff is collapsed.
\section{Built-in Module \sectcode{__builtin__}}
\bimodindex{__builtin__}
This module provides direct access to all `built-in' identifier of
Python; e.g. \code{__builtin__.open} is the full name for the built-in
function \code{open}.
\chapter{CRYPTOGRAPHIC EXTENSIONS}
The modules described in this chapter implement various algorithms of
a cryptographic nature. They are available at the discretion of the
installation.
\section{Built-in Module \sectcode{dbm}}
\bimodindex{dbm}
Dbm provides python programs with an interface to the unix \code{ndbm}
database library. Dbm objects are of the mapping type, so they can be
handled just like objects of the built-in \dfn{dictionary} type,
except that keys and values are always strings, and printing a dbm
object doesn't print the keys and values.
The module defines the following constant and functions:
\renewcommand{\indexsubitem}{(in module dbm)}
\begin{excdesc}{error}
Raised on dbm-specific errors, such as I/O errors. \code{KeyError} is
raised for general mapping errors like specifying an incorrect key.
\end{excdesc}
\begin{funcdesc}{open}{filename\, rwmode\, filemode}
Open a dbm database and return a mapping object. \var{filename} is
the name of the database file (without the \file{.dir} or \file{.pag}
extensions), \var{rwmode} is \code{'r'}, \code{'w'} or \code{'rw'} as for
\code{open}, and \var{filemode} is the unix mode of the file, used only
when the database has to be created.
\end{funcdesc}
\section{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.
\renewcommand{\indexsubitem}{(built-in exception)}
\begin{excdesc}{AttributeError}
% xref to attribute reference?
Raised when an attribute reference or assignment fails. (When an
object does not support attributes references or attribute assignments
at all, \code{TypeError} is raised.)
\end{excdesc}
\begin{excdesc}{EOFError}
% XXXJH xrefs here
Raised when one of the built-in functions (\code{input()} or
\code{raw_input()}) hits an end-of-file condition (\EOF{}) without
reading any data.
% XXXJH xrefs here
(N.B.: the \code{read()} and \code{readline()} methods of file
objects return an empty string when they hit \EOF{}.) No associated value.
\end{excdesc}
\begin{excdesc}{IOError}
% XXXJH xrefs here
Raised when an I/O operation (such as a \code{print} statement, the
built-in \code{open()} function or a method of a file object) fails
for an I/O-related reason, e.g., `file not found', `disk full'.
\end{excdesc}
\begin{excdesc}{ImportError}
% XXXJH xref to import statement?
Raised when an \code{import} statement fails to find the module
definition or when a \code{from {\rm \ldots} import} fails to find a
name that is to be imported.
\end{excdesc}
\begin{excdesc}{IndexError}
% XXXJH xref to sequences
Raised when a sequence subscript is out of range. (Slice indices are
silently truncated to fall in the allowed range; if an index is not a
plain integer, \code{TypeError} is raised.)
\end{excdesc}
\begin{excdesc}{KeyError}
% XXXJH xref to mapping objects?
Raised when a mapping (dictionary) key is not found in the set of
existing keys.
\end{excdesc}
\begin{excdesc}{KeyboardInterrupt}
Raised when the user hits the interrupt key (normally
\kbd{Control-C} or
\key{DEL}). During execution, a check for interrupts is made regularly.
% XXXJH xrefs here
Interrupts typed when a built-in function \code{input()} or
\code{raw_input()}) is waiting for input also raise this exception. No
associated value.
\end{excdesc}
\begin{excdesc}{MemoryError}
Raised when an operation runs out of memory but the situation may
still be rescued (by deleting some objects). The associated value is
a string indicating what kind of (internal) operation ran out of memory.
Note that because of the underlying memory management architecture
(\C{}'s \code{malloc()} function), the interpreter may not always be able
to completely recover from this situation; it nevertheless raises an
exception so that a stack traceback can be printed, in case a run-away
program was the cause.
\end{excdesc}
\begin{excdesc}{NameError}
Raised when a local or global name is not found. This applies only
to unqualified names. The associated value is the name that could
not be found.
\end{excdesc}
\begin{excdesc}{OverflowError}
% XXXJH reference to long's and/or int's?
Raised when the result of an arithmetic operation is too large to be
represented. This cannot occur for long integers (which would rather
raise \code{MemoryError} than give up). Because of the lack of
standardization of floating point exception handling in \C{}, most
floating point operations also aren't checked. For plain integers,
all operations that can overflow are checked except left shift, where
typical applications prefer to drop bits than raise an exception.
\end{excdesc}
\begin{excdesc}{RuntimeError}
Raised when an error is detected that doesn't fall in any of the
other categories. The associated value is a string indicating what
precisely went wrong. (This exception is a relic from a previous
version of the interpreter; it is not used any more except by some
extension modules that haven't been converted to define their own
exceptions yet.)
\end{excdesc}
\begin{excdesc}{SyntaxError}
% XXXJH xref to these functions?
Raised when the parser encounters a syntax error. This may occur in
an \code{import} statement, in an \code{exec} statement, in a call
to the built-in function \code{eval()} or \code{input()}, or
when reading the initial script or standard input (also
interactively).
\end{excdesc}
\begin{excdesc}{SystemError}
Raised when the interpreter finds an internal error, but the
situation does not look so serious to cause it to abandon all hope.
The associated value is a string indicating what went wrong (in
low-level terms).
You should report this to the author or maintainer of your Python
interpreter. Be sure to report the version string of the Python
interpreter (\code{sys.version}; it is also printed at the start of an
interactive Python session), the exact error message (the exception's
associated value) and if possible the source of the program that
triggered the error.
\end{excdesc}
\begin{excdesc}{SystemExit}
% XXXJH xref to module sys?
This exception is raised by the \code{sys.exit()} function. When it
is not handled, the Python interpreter exits; no stack traceback is
printed. If the associated value is a plain integer, it specifies the
system exit status (passed to \C{}'s \code{exit()} function); if it is
\code{None}, the exit status is zero; if it has another type (such as
a string), the object's value is printed and the exit status is one.
A call to \code{sys.exit} is translated into an exception so that
clean-up handlers (\code{finally} clauses of \code{try} statements)
can be executed, and so that a debugger can execute a script without
running the risk of losing control. The \code{posix._exit()} function
can be used if it is absolutely positively necessary to exit
immediately (e.g., after a \code{fork()} in the child process).
\end{excdesc}
\begin{excdesc}{TypeError}
Raised when a built-in operation or function is applied to an object
of inappropriate type. The associated value is a string giving
details about the type mismatch.
\end{excdesc}
\begin{excdesc}{ValueError}
Raised when a built-in operation or function receives an argument
that has the right type but an inappropriate value, and the
situation is not described by a more precise exception such as
\code{IndexError}.
\end{excdesc}
\begin{excdesc}{ZeroDivisionError}
Raised when the second argument of a division or modulo operation is
zero. The associated value is a string indicating the type of the
operands and the operation.
\end{excdesc}
This diff is collapsed.
\section{Built-in Module \sectcode{fm}}
\bimodindex{fm}
This module provides access to the IRIS {\em 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:
\renewcommand{\indexsubitem}{(in module fm)}
\begin{funcdesc}{init}{}
Initialization function.
Calls \code{fminit()}.
It is normally not necessary to call this function, since it is called
automatically the first time the \code{fm} module is imported.
\end{funcdesc}
\begin{funcdesc}{findfont}{fontname}
Return a font handle object.
Calls \code{fmfindfont(\var{fontname})}.
\end{funcdesc}
\begin{funcdesc}{enumerate}{}
Returns a list of available font names.
This is an interface to \code{fmenumerate()}.
\end{funcdesc}
\begin{funcdesc}{prstr}{string}
Render a string using the current font (see the \code{setfont()} font
handle method below).
Calls \code{fmprstr(\var{string})}.
\end{funcdesc}
\begin{funcdesc}{setpath}{string}
Sets the font search path.
Calls \code{fmsetpath(string)}.
(XXX Does not work!?!)
\end{funcdesc}
\begin{funcdesc}{fontpath}{}
Returns the current font search path.
\end{funcdesc}
Font handle objects support the following operations:
\renewcommand{\indexsubitem}{(font handle method)}
\begin{funcdesc}{scalefont}{factor}
Returns a handle for a scaled version of this font.
Calls \code{fmscalefont(\var{fh}, \var{factor})}.
\end{funcdesc}
\begin{funcdesc}{setfont}{}
Makes this font the current font.
Note: the effect is undone silently when the font handle object is
deleted.
Calls \code{fmsetfont(\var{fh})}.
\end{funcdesc}
\begin{funcdesc}{getfontname}{}
Returns this font's name.
Calls \code{fmgetfontname(\var{fh})}.
\end{funcdesc}
\begin{funcdesc}{getcomment}{}
Returns the comment string associated with this font.
Raises an exception if there is none.
Calls \code{fmgetcomment(\var{fh})}.
\end{funcdesc}
\begin{funcdesc}{getfontinfo}{}
Returns a tuple giving some pertinent data about this font.
This is an interface to \code{fmgetfontinfo()}.
The returned tuple contains the following numbers:
\code{(\var{printermatched}, \var{fixed_width}, \var{xorig}, \var{yorig}, \var{xsize}, \var{ysize}, \var{height}, \var{nglyphs})}.
\end{funcdesc}
\begin{funcdesc}{getstrwidth}{string}
Returns the width, in pixels, of the string when drawn in this font.
Calls \code{fmgetstrwidth(\var{fh}, \var{string})}.
\end{funcdesc}
This diff is collapsed.
\section{Standard Module \sectcode{getopt}}
\stmodindex{getopt}
This module helps scripts to parse the command line arguments in
\code{sys.argv}.
It uses the same conventions as the \UNIX{}
\code{getopt()}
function.
It defines the function
\code{getopt.getopt(args, options)}
and the exception
\code{getopt.error}.
The first argument to
\code{getopt()}
is the argument list passed to the script with its first element
chopped off (i.e.,
\code{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{}
\code{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.,
\code{'-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:
\bcode\begin{verbatim}
>>> 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']
>>>
\end{verbatim}\ecode
The exception
\code{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.
\section{Built-in Module \sectcode{gl}}
\bimodindex{gl}
This module provides access to the Silicon Graphics
{\em Graphics Library}.
It is available only on Silicon Graphics machines.
\strong{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:
\begin{itemize}
\item
All (short, long, unsigned) int values are represented by Python
integers.
\item
All float and double values are represented by Python floating point
numbers.
In most cases, Python integers are also allowed.
\item
All arrays are represented by one-dimensional Python lists.
In most cases, tuples are also allowed.
\item
\begin{sloppypar}
All string and character arguments are represented by Python strings,
for instance,
\code{winopen('Hi There!')}
and
\code{rotate(900, 'z')}.
\end{sloppypar}
\item
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
\bcode\begin{verbatim}
lmdef(deftype, index, np, props)
\end{verbatim}\ecode
is translated to Python as
\bcode\begin{verbatim}
lmdef(deftype, index, props)
\end{verbatim}\ecode
\item
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
\bcode\begin{verbatim}
getmcolor(i, &red, &green, &blue)
\end{verbatim}\ecode
is translated to Python as
\bcode\begin{verbatim}
red, green, blue = getmcolor(i)
\end{verbatim}\ecode
\end{itemize}
The following functions are non-standard or have special argument
conventions:
\renewcommand{\indexsubitem}{(in module gl)}
\begin{funcdesc}{varray}{argument}
%JHXXX the argument-argument added
Equivalent to but faster than a number of
\code{v3d()}
calls.
The \var{argument} is a list (or tuple) of points.
Each point must be a tuple of coordinates
\code{(\var{x}, \var{y}, \var{z})} or \code{(\var{x}, \var{y})}.
The points may be 2- or 3-dimensional but must all have the
same dimension.
Float and int values may be mixed however.
The points are always converted to 3D double precision points
by assuming \code{\var{z} = 0.0} if necessary (as indicated in the man page),
and for each point
\code{v3d()}
is called.
\end{funcdesc}
\begin{funcdesc}{nvarray}{}
Equivalent to but faster than a number of
\code{n3f}
and
\code{v3f}
calls.
The argument is an array (list or tuple) of pairs of normals and points.
Each pair is a tuple of a point and a normal for that point.
Each point or normal must be a tuple of coordinates
\code{(\var{x}, \var{y}, \var{z})}.
Three coordinates must be given.
Float and int values may be mixed.
For each pair,
\code{n3f()}
is called for the normal, and then
\code{v3f()}
is called for the point.
\end{funcdesc}
\begin{funcdesc}{vnarray}{}
Similar to
\code{nvarray()}
but the pairs have the point first and the normal second.
\end{funcdesc}
\begin{funcdesc}{nurbssurface}{s_k\, t_k\, ctl\, s_ord\, t_ord\, type}
% XXX s_k[], t_k[], ctl[][]
%\itembreak
Defines a nurbs surface.
The dimensions of
\code{\var{ctl}[][]}
are computed as follows:
\code{[len(\var{s_k}) - \var{s_ord}]},
\code{[len(\var{t_k}) - \var{t_ord}]}.
\end{funcdesc}
\begin{funcdesc}{nurbscurve}{knots\, ctlpoints\, order\, type}
Defines a nurbs curve.
The length of ctlpoints is
\code{len(\var{knots}) - \var{order}}.
\end{funcdesc}
\begin{funcdesc}{pwlcurve}{points\, type}
Defines a piecewise-linear curve.
\var{points}
is a list of points.
\var{type}
must be
\code{N_ST}.
\end{funcdesc}
\begin{funcdesc}{pick}{n}
\funcline{select}{n}
The only argument to these functions specifies the desired size of the
pick or select buffer.
\end{funcdesc}
\begin{funcdesc}{endpick}{}
\funcline{endselect}{}
These functions have no arguments.
They return a list of integers representing the used part of the
pick/select buffer.
No method is provided to detect buffer overrun.
\end{funcdesc}
Here is a tiny but complete example GL program in Python:
\bcode\begin{verbatim}
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()
\end{verbatim}\ecode
\section{Standard Modules \sectcode{GL} and \sectcode{DEVICE}}
\stmodindex{GL}
\stmodindex{DEVICE}
These modules define the constants used by the Silicon Graphics
{\em Graphics Library}
that C programmers find in the header files
\file{<gl/gl.h>}
and
\file{<gl/device.h>}.
Read the module source files for details.
\section{Built-in Module \sectcode{grp}}
\bimodindex{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 \file{<grp.h>}), in order:
\code{gr_name},
\code{gr_passwd},
\code{gr_gid},
\code{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(s) they are in.)
An exception is raised if the entry asked for cannot be found.
It defines the following items:
\renewcommand{\indexsubitem}{(in module grp)}
\begin{funcdesc}{getgrgid}{gid}
Return the group database entry for the given numeric group ID.
\end{funcdesc}
\begin{funcdesc}{getgrnam}{name}
Return the group database entry for the given group name.
\end{funcdesc}
\begin{funcdesc}{getgrall}{}
Return a list of all available group entries entries, in arbitrary order.
\end{funcdesc}
\section{Built-in module \sectcode{imageop}}
\bimodindex{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 \code{gl.lrectwrite} and the \code{imgfile} module.
The module defines the following variables and functions:
\renewcommand{\indexsubitem}{(in module imageop)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unknown number of bits
per pixel, etc.
\end{excdesc}
\begin{funcdesc}{crop}{image\, psize\, width\, height\, x0\, y0\, x1\, y1}
This function takes the image in \code{image}, which should by
\code{width} by \code{height} in size and consist of pixels of
\code{psize} bytes, and returns the selected part of that image. \code{X0},
\code{y0}, \code{x1} and \code{y1} are like the \code{lrectread}
parameters, i.e. the boundary is included in the new image.
The new boundaries need not be inside the picture. Pixels that fall
outside the old image will have their value set to zero.
If \code{x0} is bigger than \code{x1} the new image is mirrored. The
same holds for the y coordinates.
\end{funcdesc}
\begin{funcdesc}{scale}{image\, psize\, width\, height\, newwidth\, newheight}
This function returns a \code{image} scaled to size \code{newwidth} by
\code{newheight}. No interpolation is done, scaling is done by
simple-minded pixel duplication or removal. Therefore, computer-generated
images or dithered images will not look nice after scaling.
\end{funcdesc}
\begin{funcdesc}{tovideo}{image\, psize\, width\, height}
This function runs a vertical low-pass filter over an image. It does
so by computing each destination pixel as the average of two
vertically-aligned source pixels. The main use of this routine is to
forestall excessive flicker if the image is displayed on a video
device that uses interlacing, hence the name.
\end{funcdesc}
\begin{funcdesc}{grey2mono}{image\, width\, height\, threshold}
This function converts a 8-bit deep greyscale image to a 1-bit deep
image by tresholding all the pixels. The resulting image is tightly
packed and is probably only useful as an argument to \code{mono2grey}.
\end{funcdesc}
\begin{funcdesc}{dither2mono}{image\, width\, height}
This function also converts an 8-bit greyscale image to a 1-bit
monochrome image but it uses a (simple-minded) dithering algorithm.
\end{funcdesc}
\begin{funcdesc}{mono2grey}{image\, width\, height\, p0\, p1}
This function converts a 1-bit monochrome image to an 8 bit greyscale
or color image. All pixels that are zero-valued on input get value
\code{p0} on output and all one-value input pixels get value \code{p1}
on output. To convert a monochrome black-and-white image to greyscale
pass the values \code{0} and \code{255} respectively.
\end{funcdesc}
\begin{funcdesc}{grey2grey4}{image\, width\, height}
Convert an 8-bit greyscale image to a 4-bit greyscale image without
dithering.
\end{funcdesc}
\begin{funcdesc}{grey2grey2}{image\, width\, height}
Convert an 8-bit greyscale image to a 2-bit greyscale image without
dithering.
\end{funcdesc}
\begin{funcdesc}{dither2grey2}{image\, width\, height}
Convert an 8-bit greyscale image to a 2-bit greyscale image with
dithering. As for \code{dither2mono}, the dithering algorithm is
currently very simple.
\end{funcdesc}
\begin{funcdesc}{grey42grey}{image\, width\, height}
Convert a 4-bit greyscale image to an 8-bit greyscale image.
\end{funcdesc}
\begin{funcdesc}{grey22grey}{image\, width\, height}
Convert a 2-bit greyscale image to an 8-bit greyscale image.
\end{funcdesc}
\section{Built-in module \sectcode{imgfile}}
\bimodindex{imgfile}
The imgfile module allows python programs to access SGI imglib image
files (also known as \file{.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:
\renewcommand{\indexsubitem}{(in module imgfile)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unsupported file type, etc.
\end{excdesc}
\begin{funcdesc}{getsizes}{file}
This function returns a tuple \code{(\var{x}, \var{y}, \var{z})} where
\var{x} and \var{y} are the size of the image in pixels and
\var{z} is the number of
bytes per pixel. Only 3 byte RGB pixels and 1 byte greyscale pixels
are currently supported.
\end{funcdesc}
\begin{funcdesc}{read}{file}
This function reads and decodes the image on the specified file, and
returns it as a python string. The string has either 1 byte greyscale
pixels or 4 byte RGBA pixels. The bottom left pixel is the first in
the string. This format is suitable to pass to \code{gl.lrectwrite},
for instance.
\end{funcdesc}
\begin{funcdesc}{readscaled}{file\, x\, y\, filter\, blur}
This function is identical to read but it returns an image that is
scaled to the given \var{x} and \var{y} sizes. If the \var{filter} and
\var{blur} parameters are omitted scaling is done by
simply dropping or duplicating pixels, so the result will be less than
perfect, especially for computer-generated images.
Alternatively, you can specify a filter to use to smoothen the image
after scaling. The filter forms supported are \code{'impulse'},
\code{'box'}, \code{'triangle'}, \code{'quadratic'} and
\code{'gaussian'}. If a filter is specified \var{blur} is an optional
parameter specifying the blurriness of the filter. It defaults to \code{1.0}.
Readscaled makes no
attempt to keep the aspect ratio correct, so that is the users'
responsibility.
\end{funcdesc}
\begin{funcdesc}{ttob}{flag}
This function sets a global flag which defines whether the scan lines
of the image are read or written from bottom to top (flag is zero,
compatible with SGI GL) or from top to bottom(flag is one,
compatible with X). The default is zero.
\end{funcdesc}
\begin{funcdesc}{write}{file\, data\, x\, y\, z}
This function writes the RGB or greyscale data in \var{data} to image
file \var{file}. \var{x} and \var{y} give the size of the image,
\var{z} is 1 for 1 byte greyscale images or 3 for RGB images (which are
stored as 4 byte values of which only the lower three bytes are used).
These are the formats returned by \code{gl.lrectread}.
\end{funcdesc}
\chapter{Introduction}
The Python library consists of three parts, with different levels of
integration with the interpreter.
Closest to the interpreter are built-in types, exceptions and functions.
Next are built-in modules, which are written in \C{} and linked statically
with the interpreter.
Finally there are standard modules that are implemented entirely in
Python, but are always available.
For efficiency, some standard modules may become built-in modules in
future versions of the interpreter.
\indexii{built-in}{types}
\indexii{built-in}{exceptions}
\indexii{built-in}{functions}
\indexii{built-in}{modules}
\indexii{standard}{modules}
\indexii{\C{}}{language}
\section{Built-in Module \sectcode{jpeg}}
\bimodindex{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
Indepent JPEG Group software refer to the JPEG standard or the
documentation provided with the software.
The jpeg module defines these functions:
\renewcommand{\indexsubitem}{(in module jpeg)}
\begin{funcdesc}{compress}{data\, w\, h\, b}
Treat data as a pixmap of width w and height h, with b bytes per
pixel. The data is in sgi gl order, so the first pixel is in the
lower-left corner. This means that lrectread return data can
immedeately be passed to compress. Currently only 1 byte and 4 byte
pixels are allowed, the former being treaded as greyscale and the
latter as RGB color. Compress returns a string that contains the
compressed picture, in JFIF format.
\end{funcdesc}
\begin{funcdesc}{decompress}{data}
Data is a string containing a picture in JFIF format. It returns a
tuple
\code{(\var{data}, \var{width}, \var{height}, \var{bytesperpixel})}.
Again, the data is suitable to pass to lrectwrite.
\end{funcdesc}
\begin{funcdesc}{setoption}{name\, value}
Set various options. Subsequent compress and decompress calls
will use these options. The following options are available:
\begin{description}
\item[\code{'forcegray'}]
Force output to be grayscale, even if input is RGB.
\item[\code{'quality'}]
Set the quality of the compressed image to a
value between \code{0} and \code{100} (default is \code{75}). Compress only.
\item[\code{'optimize'}]
Perform huffman table optimization. Takes longer, but results in
smaller compressed image. Compress only.
\item[\code{'smooth'}]
Perform inter-block smoothing on uncompressed image. Only useful for
low-quality images. Decompress only.
\end{description}
\end{funcdesc}
Compress and uncompress raise the error jpeg.error in case of errors.
\section{Built-in Module \sectcode{__main__}}
\bimodindex{__main__}
This module represents the (otherwise anonymous) scope in which the
interpreter's main program executes --- commands read either from
standard input or from a script file.
\section{Built-in Module \sectcode{marshal}}
\bimodindex{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 VAX, transport the file to a Mac, and read
it back there). Details of the format not explained here; read the
source if you're interested.%
\footnote{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.}
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:
\code{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 an infinite loop).
There are functions that read/write files as well as functions
operating on strings.
The module defines these functions:
\renewcommand{\indexsubitem}{(in module marshal)}
\begin{funcdesc}{dump}{value\, file}
Write the value on the open file. The value must be a supported
type. The file must be an open file object such as
\code{sys.stdout} or returned by \code{open()} or
\code{posix.popen()}.
If the value has an unsupported type, garbage is written which cannot
be read back by \code{load()}.
\end{funcdesc}
\begin{funcdesc}{load}{file}
Read one value from the open file and return it. If no valid value
is read, raise \code{EOFError}, \code{ValueError} or
\code{TypeError}. The file must be an open file object.
\end{funcdesc}
\begin{funcdesc}{dumps}{value}
Return the string that would be written to a file by
\code{dump(value, file)}. The value must be a supported type.
\end{funcdesc}
\begin{funcdesc}{loads}{string}
Convert the string to a value. If no valid value is found, raise
\code{EOFError}, \code{ValueError} or \code{TypeError}. Extra
characters in the string are ignored.
\end{funcdesc}
\section{Built-in Module \sectcode{math}}
\bimodindex{math}
\renewcommand{\indexsubitem}{(in module math)}
This module is always available.
It provides access to the mathematical functions defined by the C
standard.
They are:
\iftexi
\begin{funcdesc}{acos}{x}
\funcline{asin}{x}
\funcline{atan}{x}
\funcline{atan2}{x, y}
\funcline{ceil}{x}
\funcline{cos}{x}
\funcline{cosh}{x}
\funcline{exp}{x}
\funcline{fabs}{x}
\funcline{floor}{x}
\funcline{fmod}{x, y}
\funcline{frexp}{x}
\funcline{ldexp}{x, y}
\funcline{log}{x}
\funcline{log10}{x}
\funcline{modf}{x}
\funcline{pow}{x, y}
\funcline{sin}{x}
\funcline{sinh}{x}
\funcline{sqrt}{x}
\funcline{tan}{x}
\funcline{tanh}{x}
\end{funcdesc}
\else
\code{acos(\varvars{x})},
\code{asin(\varvars{x})},
\code{atan(\varvars{x})},
\code{atan2(\varvars{x\, y})},
\code{ceil(\varvars{x})},
\code{cos(\varvars{x})},
\code{cosh(\varvars{x})},
\code{exp(\varvars{x})},
\code{fabs(\varvars{x})},
\code{floor(\varvars{x})},
\code{fmod(\varvars{x\, y})},
\code{frexp(\varvars{x})},
\code{ldexp(\varvars{x\, y})},
\code{log(\varvars{x})},
\code{log10(\varvars{x})},
\code{modf(\varvars{x})},
\code{pow(\varvars{x\, y})},
\code{sin(\varvars{x})},
\code{sinh(\varvars{x})},
\code{sqrt(\varvars{x})},
\code{tan(\varvars{x})},
\code{tanh(\varvars{x})}.
\fi
Note that \code{frexp} and \code{modf} have a different call/return
pattern than their C equivalents: they take a single argument and
return a pair of values, rather than returning their second return
value through an `output parameter' (there is no such thing in Python).
The module also defines two mathematical constants:
\iftexi
\begin{datadesc}{pi}
\dataline{e}
\end{datadesc}
\else
\code{pi} and \code{e}.
\fi
\section{Built-in module \sectcode{md5}}
\bimodindex{md5}
This module implements the interface to RSA's MD5 message digest
algorithm (see also the file \file{md5.doc}). It's use is very
straightforward: use the function \code{md5} to create an
\dfn{md5}-object. You can now ``feed'' this object with arbitrary
strings.
At any time you can ask the ``final'' digest of the object. Internally,
a temorary copy of the object is made and the digest is computed and
returned. Because of the copy, the digest operation is not desctructive
for the object. Before a more exact description of the use, a small
example: to obtain the digest of the string \code{'abc'}, use \ldots
\bcode\begin{verbatim}
>>> from md5 import md5
>>> m = md5()
>>> m.update('abc')
>>> m.digest()
'\220\001P\230<\322O\260\326\226?}(\341\177r'
\end{verbatim}\ecode
More condensed:
\bcode\begin{verbatim}
>>> md5('abc').digest()
'\220\001P\230<\322O\260\326\226?}(\341\177r'
\end{verbatim}\ecode
\renewcommand{\indexsubitem}{(in module md5)}
\begin{funcdesc}{md5}{arg}
Create a new md5-object. \var{arg} is optional: if present, an initial
\code{update} method is called with \var{arg} as argument.
\end{funcdesc}
An md5-object has the following methods:
\renewcommand{\indexsubitem}{(md5 method)}
\begin{funcdesc}{update}{arg}
Update this md5-object with the string \var{arg}.
\end{funcdesc}
\begin{funcdesc}{digest}{}
Return the \dfn{digest} of this md5-object. Internally, a copy is made
and the \C-function \code{MD5Final} is called. Finally the digest is
returned.
\end{funcdesc}
\begin{funcdesc}{copy}{}
Return a separate copy of this md5-object. An \code{update} to this
copy won't affect the original object.
\end{funcdesc}
\chapter{MULTIMEDIA EXTENSIONS}
The modules described in this chapter implement various algorithms
that are mainly useful for multimedia applications. They are
available at the discretion of the installation.
\section{Built-in module \sectcode{mpz}}
\bimodindex{mpz}
This module implements the interface to part of the GNU MP library.
This library contains arbitrary precision integer and rational number
arithmetic routines. Only the interfaces to the \emph{integer}
(\samp{mpz_{\rm \ldots}}) routines are provided. If not stated
otherwise, the description in the GNU MP documentation can be applied.
In general, \dfn{mpz}-numbers can be used just like other standard
Python numbers, e.g. you can use the built-in operators like \code{+},
\code{*}, etc., as well as the standard built-in functions like
\code{abs}, \code{int}, \ldots, \code{divmod}, \code{pow}.
\strong{Please note:} the {\it bitwise-xor} operation has been implemented as
a bunch of {\it and}s, {\it invert}s and {\it or}s, because the library
lacks an \code{mpz_xor} function, and I didn't need one.
You create an mpz-number, by calling the function called \code{mpz} (see
below for an excact description). An mpz-number is printed like this:
\code{mpz(\var{value})}.
\renewcommand{\indexsubitem}{(in module mpz)}
\begin{funcdesc}{mpz}{value}
Create a new mpz-number. \var{value} can be an integer, a long,
another mpz-number, or even a string. If it is a string, it is
interpreted as an array of radix-256 digits, least significant digit
first, resulting in a positive number. See also the \code{binary}
method, described below.
\end{funcdesc}
A number of {\em extra} functions are defined in this module. Non
mpz-arguments are converted to mpz-values first, and the functions
return mpz-numbers.
\begin{funcdesc}{powm}{base\, exponent\, modulus}
Return \code{pow(\var{base}, \var{exponent}) \%{} \var{modulus}}. If
\code{\var{exponent} == 0}, return \code{mpz(1)}. In contrast to the
\C-library function, this version can handle negative exponents.
\end{funcdesc}
\begin{funcdesc}{gcd}{op1\, op2}
Return the greatest common divisor of \var{op1} and \var{op2}.
\end{funcdesc}
\begin{funcdesc}{gcdext}{a\, b}
Return a tuple \code{(\var{g}, \var{s}, \var{t})}, such that
\code{\var{a}*\var{s} + \var{b}*\var{t} == \var{g} == gcd(\var{a}, \var{b})}.
\end{funcdesc}
\begin{funcdesc}{sqrt}{op}
Return the square root of \var{op}. The result is rounded towards zero.
\end{funcdesc}
\begin{funcdesc}{sqrtrem}{op}
Return a tuple \code{(\var{root}, \var{remainder})}, such that
\code{\var{root}*\var{root} + \var{remainder} == \var{op}}.
\end{funcdesc}
\begin{funcdesc}{divm}{numerator\, denominator\, modulus}
Returns a number \var{q}. such that
\code{\var{q} * \var{denominator} \%{} \var{modulus} == \var{numerator}}.
One could also implement this function in python, using \code{gcdext}.
\end{funcdesc}
An mpz-number has one method:
\renewcommand{\indexsubitem}{(mpz method)}
\begin{funcdesc}{binary}{}
Convert this mpz-number to a binary string, where the number has been
stored as an array of radix-256 digits, least significant digit first.
The mpz-number must have a value greater than- or equal to zero,
otherwise a \code{ValueError}-exception will be raised.
\end{funcdesc}
\chapter{Built-in Types, Exceptions and Functions}
\nodename{Built-in Objects}
Names for built-in exceptions and functions are found in a separate
symbol table. This table is searched last, so local and global
user-defined names can override built-in names. Built-in types have
no names but are created easily by constructing an object of the
desired type (e.g., using a literal) and applying the built-in
function \code{type()} to it. They are described together here for
easy reference.%
\footnote{Some descriptions sorely lack explanations of the exceptions
that may be raised --- this will be fixed in a future version of
this document.}
\indexii{built-in}{types}
\indexii{built-in}{exceptions}
\indexii{built-in}{functions}
\index{symbol table}
\bifuncindex{type}
\section{Standard Module \sectcode{os}}
\stmodindex{os}
This module provides a more portable way of using operating system
(OS) dependent functionality than importing an OS dependent built-in
module like \code{posix}.
When the optional built-in module \code{posix} is available, this
module exports the same functions and data as \code{posix}; otherwise,
it searches for an OS dependent built-in module like \code{mac} and
exports the same functions and data as found there. The design of all
Python's built-in OS dependen modules is such that as long as the same
functionality is available, it uses the same interface; e.g., the
function \code{os.stat(\var{file})} returns stat info about a \var{file} in a
format compatible with the POSIX interface.
Extensions peculiar to a particular OS are also available through the
\code{os} module, but using them is of course a threat to portability!
Note that after the first time \code{os} is imported, there is \emph{no}
performance penalty in using functions from \code{os} instead of
directly from the OS dependent built-in module, so there should be
\emph{no} reason not to use \code{os}!
In addition to whatever the correct OS dependent module exports, the
following variables and functions are always exported by \code{os}:
\renewcommand{\indexsubitem}{(in module os)}
\begin{datadesc}{name}
The name of the OS dependent module imported, e.g. \code{'posix'} or
\code{'mac'}.
\end{datadesc}
\begin{datadesc}{path}
The corresponding OS dependent standard module for pathname
operations, e.g., \code{posixpath} or \code{macpath}. Thus, (given
the proper imports), \code{os.path.split(\var{file})} is equivalent to but
more portable than \code{posixpath.split(\var{file})}.
\end{datadesc}
\begin{datadesc}{curdir}
The constant string used by the OS to refer to the current directory,
e.g. \code{'.'} for POSIX or \code{':'} for the Mac.
\end{datadesc}
\begin{datadesc}{pardir}
The constant string used by the OS to refer to the parent directory,
e.g. \code{'..'} for POSIX or \code{'::'} for the Mac.
\end{datadesc}
\begin{datadesc}{sep}
The character used by the OS to separate pathname components, e.g.
\code{'/'} for POSIX or \code{':'} for the Mac. Note that knowing this
is not sufficient to be able to parse or concatenate pathnames---better
use \code{os.path.split()} and \code{os.path.join()}---but it is
occasionally useful.
\end{datadesc}
\begin{funcdesc}{execl}{path\, arg0\, arg1\, ...}
This is equivalent to a call to \code{os.execv} with an \var{argv}
of \code{[\var{arg0}, \var{arg1}, ...]}.
\end{funcdesc}
\begin{funcdesc}{execle}{path\, arg0\, arg1\, ...\, env}
This is equivalent to a call to \code{os.execve} with an \var{argv}
of \code{[\var{arg0}, \var{arg1}, ...]}.
\end{funcdesc}
\begin{funcdesc}{execlp}{path\, arg0\, arg1\, ...}
This is like \code{execl} but duplicates the shell's actions in
searching for an executable file in a list of directories. The
directory list is obtained from \code{environ['PATH']}.
\end{funcdesc}
\begin{funcdesc}{execvp}{path\, arg0\, arg1\, ...}
\code{execvp} is for \code{execv} what \code{execlp} is for \code{execl}.
\end{funcdesc}
\section{Standard Module \sectcode{panel}}
\stmodindex{panel}
\strong{Please note:} The FORMS library, to which the \code{fl} module described
above interfaces, is a simpler and more accessible user interface
library for use with GL than the Panel Module (besides also being by a
Dutch author).
This module should be used instead of the built-in module
\code{pnl}
to interface with the
{\em Panel Library}.
The module is too large to document here in its entirety.
One interesting function:
\renewcommand{\indexsubitem}{(in module panel)}
\begin{funcdesc}{defpanellist}{filename}
Parses a panel description file containing S-expressions written by the
{\em Panel Editor}
that accompanies the Panel Library and creates the described panels.
It returns a list of panel objects.
\end{funcdesc}
\strong{Warning:}
the Python interpreter will dump core if you don't create a GL window
before calling
\code{panel.mkpanel()}
or
\code{panel.defpanellist()}.
\section{Standard Module \sectcode{panelparser}}
\stmodindex{panelparser}
This module defines a self-contained parser for S-expressions as output
by the Panel Editor (which is written in Scheme so it can't help writing
S-expressions).
The relevant function is
\code{panelparser.parse_file(\var{file})}
which has a file object (not a filename!) as argument and returns a list
of parsed S-expressions.
Each S-expression is converted into a Python list, with atoms converted
to Python strings and sub-expressions (recursively) to Python lists.
For more details, read the module file.
% XXXXJH should be funcdesc, I think
\section{Built-in Module \sectcode{pnl}}
\bimodindex{pnl}
This module provides access to the
{\em Panel Library}
built by NASA Ames (to get it, send e-mail to
{\tt panel-request@nas.nasa.gov}).
All access to it should be done through the standard module
\code{panel},
which transparantly exports most functions from
\code{pnl}
but redefines
\code{pnl.dopanel()}.
\strong{Warning:}
the Python interpreter will dump core if you don't create a GL window
before calling
\code{pnl.mkpanel()}.
The module is too large to document here in its entirety.
\section{Built-in Module \sectcode{posix}}
\bimodindex{posix}
This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly diguised
\UNIX{} interface).
It is available in all Python versions except on the Macintosh;
the MS-DOS version does not support certain functions.
The descriptions below are very terse; refer to the
corresponding \UNIX{} manual entry for more information.
Errors are reported as exceptions; the usual exceptions are given
for type errors, while errors reported by the system calls raise
\code{posix.error}, described below.
Module \code{posix} defines the following data items:
\renewcommand{\indexsubitem}{(data in module posix)}
\begin{datadesc}{environ}
A dictionary representing the string environment at the time
the interpreter was started.
(Modifying this dictionary does not affect the string environment of the
interpreter.)
For example,
\code{posix.environ['HOME']}
is the pathname of your home directory, equivalent to
\code{getenv("HOME")}
in C.
\end{datadesc}
\renewcommand{\indexsubitem}{(exception in module posix)}
\begin{excdesc}{error}
This exception is raised when an POSIX function returns a
POSIX-related error (e.g., not for illegal argument types). Its
string value is \code{'posix.error'}. The accompanying value is a
pair containing the numeric error code from \code{errno} and the
corresponding string, as would be printed by the C function
\code{perror()}.
\end{excdesc}
It defines the following functions:
\renewcommand{\indexsubitem}{(in module posix)}
\begin{funcdesc}{chdir}{path}
Change the current working directory to \var{path}.
\end{funcdesc}
\begin{funcdesc}{chmod}{path\, mode}
Change the mode of \var{path} to the numeric \var{mode}.
\end{funcdesc}
\begin{funcdesc}{close}{fd}
Close file descriptor \var{fd}.
\end{funcdesc}
\begin{funcdesc}{dup}{fd}
Return a duplicate of file descriptor \var{fd}.
\end{funcdesc}
\begin{funcdesc}{dup2}{fd\, fd2}
Duplicate file descriptor \var{fd} to \var{fd2}, closing the latter
first if necessary. Return \code{None}.
\end{funcdesc}
\begin{funcdesc}{execv}{path\, args}
Execute the executable \var{path} with argument list \var{args},
replacing the current process (i.e., the Python interpreter).
The argument list may be a tuple or list of strings.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{execve}{path\, args\, env}
Execute the executable \var{path} with argument list \var{args},
and environment \var{env},
replacing the current process (i.e., the Python interpreter).
The argument list may be a tuple or list of strings.
The environment must be a dictionary mapping strings to strings.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{_exit}{n}
Exit to the system with status \var{n}, without calling cleanup
handlers, flushing stdio buffers, etc.
(Not on MS-DOS.)
Note: the standard way to exit is \code{sys.exit(\var{n})}.
\code{posix._exit()} should normally only be used in the child process
after a \code{fork()}.
\end{funcdesc}
\begin{funcdesc}{fork}{}
Fork a child process. Return 0 in the child, the child's process id
in the parent.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{fstat}{fd}
Return status for file descriptor \var{fd}, like \code{stat()}.
\end{funcdesc}
\begin{funcdesc}{getcwd}{}
Return a string representing the current working directory.
\end{funcdesc}
\begin{funcdesc}{getegid}{}
Return the current process's effective group id.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{geteuid}{}
Return the current process's effective user id.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{getgid}{}
Return the current process's group id.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{getpid}{}
Return the current process id.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{getppid}{}
Return the parent's process id.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{getuid}{}
Return the current process's user id.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{kill}{pid\, sig}
Kill the process \var{pid} with signal \var{sig}.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{link}{src\, dst}
Create a hard link pointing to \var{src} named \var{dst}.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{listdir}{path}
Return a list containing the names of the entries in the directory.
The list is in arbitrary order. It includes the special entries
\code{'.'} and \code{'..'} if they are present in the directory.
\end{funcdesc}
\begin{funcdesc}{lseek}{fd\, pos\, how}
Set the current position of file descriptor \var{fd} to position
\var{pos}, modified by \var{how}: 0 to set the position relative to
the beginning of the file; 1 to set it relative to the current
position; 2 to set it relative to the end of the file.
\end{funcdesc}
\begin{funcdesc}{lstat}{path}
Like \code{stat()}, but do not follow symbolic links. (On systems
without symbolic links, this is identical to \code{posix.stat}.)
\end{funcdesc}
\begin{funcdesc}{mkdir}{path\, mode}
Create a directory named \var{path} with numeric mode \var{mode}.
\end{funcdesc}
\begin{funcdesc}{nice}{increment}
Add \var{incr} to the process' ``niceness''. Return the new niceness.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{open}{file\, flags\, mode}
Open the file \var{file} and set various flags according to
\var{flags} and possibly its mode according to \var{mode}.
Return the file descriptor for the newly opened file.
\end{funcdesc}
\begin{funcdesc}{pipe}{}
Create a pipe. Return a pair of file descriptors \code{(r, w)}
usable for reading and writing, respectively.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{popen}{command\, mode}
Open a pipe to or from \var{command}. The return value is an open
file object connected to the pipe, which can be read or written
depending on whether \var{mode} is \code{'r'} or \code{'w'}.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{read}{fd\, n}
Read at most \var{n} bytes from file descriptor \var{fd}.
Return a string containing the bytes read.
\end{funcdesc}
\begin{funcdesc}{readlink}{path}
Return a string representing the path to which the symbolic link
points. (On systems without symbolic links, this always raises
\code{posix.error}.)
\end{funcdesc}
\begin{funcdesc}{rename}{src\, dst}
Rename the file or directory \var{src} to \var{dst}.
\end{funcdesc}
\begin{funcdesc}{rmdir}{path}
Remove the directory \var{path}.
\end{funcdesc}
\begin{funcdesc}{setgid}{gid}
Set the current process's group id.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{setuid}{uid}
Set the current process's user id.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{stat}{path}
Perform a {\em stat} system call on the given path. The return value
is a tuple of at least 10 integers giving the most important (and
portable) members of the {\em stat} structure, in the order
\code{st_mode},
\code{st_ino},
\code{st_dev},
\code{st_nlink},
\code{st_uid},
\code{st_gid},
\code{st_size},
\code{st_atime},
\code{st_mtime},
\code{st_ctime}.
More items may be added at the end by some implementations.
(On MS-DOS, some items are filled with dummy values.)
Note: The standard module \code{stat} defines functions and constants
that are useful for extracting information from a stat structure.
\end{funcdesc}
\begin{funcdesc}{symlink}{src\, dst}
Create a symbolic link pointing to \var{src} named \var{dst}. (On
systems without symbolic links, this always raises
\code{posix.error}.)
\end{funcdesc}
\begin{funcdesc}{system}{command}
Execute the command (a string) in a subshell. This is implemented by
calling the Standard C function \code{system()}, and has the same
limitations. Changes to \code{posix.environ}, \code{sys.stdin} etc. are
not reflected in the environment of the executed command. The return
value is the exit status of the process as returned by Standard C
\code{system()}.
\end{funcdesc}
\begin{funcdesc}{times}{}
Return a 4-tuple of floating point numbers indicating accumulated CPU
times, in seconds. The items are: user time, system time, children's
user time, and children's system time, in that order. See the \UNIX{}
manual page {\it times}(2). (Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{umask}{mask}
Set the current numeric umask and returns the previous umask.
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{uname}{}
Return a 5-tuple containing information identifying the current
operating system. The tuple contains 5 strings:
\code{(\var{sysname}, \var{nodename}, \var{release}, \var{version}, \var{machine})}.
Some systems truncate the nodename to 8
characters or to the leading component; an better way to get the
hostname is \code{socket.gethostname()}. (Not on MS-DOS, nor on older
\UNIX{} systems.)
\end{funcdesc}
\begin{funcdesc}{unlink}{path}
Unlink \var{path}.
\end{funcdesc}
\begin{funcdesc}{utime}{path\, \(atime\, mtime\)}
Set the access and modified time of the file to the given values.
(The second argument is a tuple of two items.)
\end{funcdesc}
\begin{funcdesc}{wait}{}
Wait for completion of a child process, and return a tuple containing
its pid and exit status indication (encoded as by \UNIX{}).
(Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{waitpid}{pid\, options}
Wait for completion of a child process given by proces id, and return
a tuple containing its pid and exit status indication (encoded as by
\UNIX{}). The semantics of the call are affected by the value of
the integer options, which should be 0 for normal operation. (If the
system does not support waitpid(), this always raises
\code{posix.error}. Not on MS-DOS.)
\end{funcdesc}
\begin{funcdesc}{write}{fd\, str}
Write the string \var{str} to file descriptor \var{fd}.
Return the number of bytes actually written.
\end{funcdesc}
\section{Standard Module \sectcode{posixpath}}
\stmodindex{posixpath}
This module implements some useful functions on POSIX pathnames.
\renewcommand{\indexsubitem}{(in module posixpath)}
\begin{funcdesc}{basename}{p}
Return the base name of pathname
\var{p}.
This is the second half of the pair returned by
\code{posixpath.split(\var{p})}.
\end{funcdesc}
\begin{funcdesc}{commonprefix}{list}
Return the longest string that is a prefix of all strings in
\var{list}.
If
\var{list}
is empty, return the empty string (\code{''}).
\end{funcdesc}
\begin{funcdesc}{exists}{p}
Return true if
\var{p}
refers to an existing path.
\end{funcdesc}
\begin{funcdesc}{expanduser}{p}
Return the argument with an initial component of \samp{\~} or
\samp{\~\var{user}} replaced by that \var{user}'s home directory. An
initial \samp{\~{}} is replaced by the environment variable \code{\${}HOME};
an initial \samp{\~\var{user}} is looked up in the password directory through
the built-in module \code{pwd}. If the expansion fails, or if the
path does not begin with a tilde, the path is returned unchanged.
\end{funcdesc}
\begin{funcdesc}{isabs}{p}
Return true if \var{p} is an absolute pathname (begins with a slash).
\end{funcdesc}
\begin{funcdesc}{isfile}{p}
Return true if \var{p} is an existing regular file. This follows
symbolic links, so both islink() and isfile() can be true for the same
path.
\end{funcdesc}
\begin{funcdesc}{isdir}{p}
Return true if \var{p} is an existing directory. This follows
symbolic links, so both islink() and isdir() can be true for the same
path.
\end{funcdesc}
\begin{funcdesc}{islink}{p}
Return true if
\var{p}
refers to a directory entry that is a symbolic link.
Always false if symbolic links are not supported.
\end{funcdesc}
\begin{funcdesc}{ismount}{p}
Return true if \var{p} is a mount point. (This currently checks whether
\code{\var{p}/..} is on a different device from \var{p} or whether
\code{\var{p}/..} and \var{p} point to the same i-node on the same
device --- is this test correct for all \UNIX{} and POSIX variants?)
\end{funcdesc}
\begin{funcdesc}{join}{p\, q}
Join the paths
\var{p}
and
\var{q} intelligently:
If
\var{q}
is an absolute path, the return value is
\var{q}.
Otherwise, the concatenation of
\var{p}
and
\var{q}
is returned, with a slash (\code{'/'}) inserted unless
\var{p}
is empty or ends in a slash.
\end{funcdesc}
\begin{funcdesc}{normcase}{p}
Normalize the case of a pathname. This returns the path unchanged;
however, a similar function in \code{macpath} converts upper case to
lower case.
\end{funcdesc}
\begin{funcdesc}{samefile}{p\, q}
Return true if both pathname arguments refer to the same file or directory
(as indicated by device number and i-node number).
Raise an exception if a stat call on either pathname fails.
\end{funcdesc}
\begin{funcdesc}{split}{p}
Split the pathname \var{p} in a pair \code{(\var{head}, \var{tail})}, where
\var{tail} is the last pathname component and \var{head} is
everything leading up to that. If \var{p} ends in a slash (except if
it is the root), the trailing slash is removed and the operation
applied to the result; otherwise, \code{join(\var{head}, \var{tail})} equals
\var{p}. The \var{tail} part never contains a slash. Some boundary
cases: if \var{p} is the root, \var{head} equals \var{p} and
\var{tail} is empty; if \var{p} is empty, both \var{head} and
\var{tail} are empty; if \var{p} contains no slash, \var{head} is
empty and \var{tail} equals \var{p}.
\end{funcdesc}
\begin{funcdesc}{splitext}{p}
Split the pathname \var{p} in a pair \code{(\var{root}, \var{ext})}
such that \code{\var{root} + \var{ext} == \var{p}},
the last component of \var{root} contains no periods,
and \var{ext} is empty or begins with a period.
\end{funcdesc}
\begin{funcdesc}{walk}{p\, visit\, arg}
Calls the function \var{visit} with arguments
\code{(\var{arg}, \var{dirname}, \var{names})} for each directory in the
directory tree rooted at \var{p} (including \var{p} itself, if it is a
directory). The argument \var{dirname} specifies the visited directory,
the argument \var{names} lists the files in the directory (gotten from
\code{posix.listdir(\var{dirname})}). The \var{visit} function may
modify \var{names} to influence the set of directories visited below
\var{dirname}, e.g., to avoid visiting certain parts of the tree. (The
object referred to by \var{names} must be modified in place, using
\code{del} or slice assignment.)
\end{funcdesc}
\section{Built-in Module \sectcode{pwd}}
\bimodindex{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 \file{<pwd.h>}), in order:
\code{pw_name},
\code{pw_passwd},
\code{pw_uid},
\code{pw_gid},
\code{pw_gecos},
\code{pw_dir},
\code{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:
\renewcommand{\indexsubitem}{(in module pwd)}
\begin{funcdesc}{getpwuid}{uid}
Return the password database entry for the given numeric user ID.
\end{funcdesc}
\begin{funcdesc}{getpwnam}{name}
Return the password database entry for the given user name.
\end{funcdesc}
\begin{funcdesc}{getpwall}{}
Return a list of all available password database entries, in arbitrary order.
\end{funcdesc}
\section{Standard Module \sectcode{rand}}
\stmodindex{rand} This module implements a pseudo-random number
generator with an interface similar to \code{rand()} in C. It defines
the following functions:
\renewcommand{\indexsubitem}{(in module rand)}
\begin{funcdesc}{rand}{}
Returns an integer random number in the range [0 ... 32768).
\end{funcdesc}
\begin{funcdesc}{choice}{s}
Returns a random element from the sequence (string, tuple or list)
\var{s}.
\end{funcdesc}
\begin{funcdesc}{srand}{seed}
Initializes the random number generator with the given integral seed.
When the module is first imported, the random number is initialized with
the current time.
\end{funcdesc}
\section{Built-in Module \sectcode{regex}}
\bimodindex{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; there is
a way to change the syntax to match that of several well-known
\UNIX{} utilities.
This module is 8-bit clean: both patterns and strings may contain null
bytes and characters whose high bit is set.
\strong{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. \emph{However}, if you
want to include a literal \dfn{backslash} in a regular expression
represented as a string literal, you have to \emph{quadruple} it. E.g.
to extract LaTeX \samp{\e section\{{\rm \ldots}\}} headers from a document, you can
use this pattern: \code{'\e \e \e\e section\{\e (.*\e )\}'}.
The module defines these functions, and an exception:
\renewcommand{\indexsubitem}{(in module regex)}
\begin{funcdesc}{match}{pattern\, string}
Return how many characters at the beginning of \var{string} match
the regular expression \var{pattern}. Return \code{-1} if the
string does not match the pattern (this is different from a
zero-length match!).
\end{funcdesc}
\begin{funcdesc}{search}{pattern\, string}
Return the first position in \var{string} that matches the regular
expression \var{pattern}. Return -1 if no position in the string
matches the pattern (this is different from a zero-length match
anywhere!).
\end{funcdesc}
\begin{funcdesc}{compile}{pattern\, translate}
Compile a regular expression pattern into a regular expression
object, which can be used for matching using its \code{match} and
\code{search} methods, described below. The optional
\var{translate}, if present, must be a 256-character string
indicating how characters (both of the pattern and of the strings to
be matched) are translated before comparing them; the \code{i}-th
element of the string gives the translation for the character with
ASCII code \code{i}.
The sequence
\bcode\begin{verbatim}
prog = regex.compile(pat)
result = prog.match(str)
\end{verbatim}\ecode
is equivalent to
\bcode\begin{verbatim}
result = regex.match(pat, str)
\end{verbatim}\ecode
but the version using \code{compile()} is more efficient when multiple
regular expressions are used concurrently in a single program. (The
compiled version of the last pattern passed to \code{regex.match()} or
\code{regex.search()} is cached, so programs that use only a single
regular expression at a time needn't worry about compiling regular
expressions.)
\end{funcdesc}
\begin{funcdesc}{set_syntax}{flags}
Set the syntax to be used by future calls to \code{compile},
\code{match} and \code{search}. (Already compiled expression objects
are not affected.) The argument is an integer which is the OR of
several flag bits. The return value is the previous value of
the syntax flags. Names for the flags are defined in the standard
module \code{regex_syntax}; read the file \file{regex_syntax.py} for
more information.
\end{funcdesc}
\begin{excdesc}{error}
Exception raised when a string passed to one of the functions here
is not a valid regular expression (e.g., unmatched parentheses) or
when some other error occurs during compilation or matching. (It is
never an error if a string contains no match for a pattern.)
\end{excdesc}
\begin{datadesc}{casefold}
A string suitable to pass as \var{translate} argument to
\code{compile} to map all upper case characters to their lowercase
equivalents.
\end{datadesc}
\noindent
Compiled regular expression objects support these methods:
\renewcommand{\indexsubitem}{(regex method)}
\begin{funcdesc}{match}{string\, pos}
Return how many characters at the beginning of \var{string} match
the compiled regular expression. Return \code{-1} if the string
does not match the pattern (this is different from a zero-length
match!).
The optional second parameter \var{pos} gives an index in the string
where the search is to start; it defaults to \code{0}. This is not
completely equivalent to slicing the string; the \code{'\^'} pattern
character matches at the real begin of the string and at positions
just after a newline, not necessarily at the index where the search
is to start.
\end{funcdesc}
\begin{funcdesc}{search}{string\, pos}
Return the first position in \var{string} that matches the regular
expression \code{pattern}. Return \code{-1} if no position in the
string matches the pattern (this is different from a zero-length
match anywhere!).
The optional second parameter has the same meaning as for the
\code{match} method.
\end{funcdesc}
\begin{funcdesc}{group}{index\, index\, ...}
This method is only valid when the last call to the \code{match}
or \code{search} method found a match. It returns one or more
groups of the match. If there is a single \var{index} argument,
the result is a single string; if there are multiple arguments, the
result is a tuple with one item per argument. If the \var{index} is
zero, the corresponding return value is the entire matching string; if
it is in the inclusive range [1..9], it is the string matching the
the corresponding parenthesized group (using the default syntax,
groups are parenthesized using \code{\\(} and \code{\\)}). If no
such group exists, the corresponding result is \code{None}.
\end{funcdesc}
\noindent
Compiled regular expressions support these data attributes:
\renewcommand{\indexsubitem}{(regex attribute)}
\begin{datadesc}{regs}
When the last call to the \code{match} or \code{search} method found a
match, this is a tuple of pairs of indices corresponding to the
beginning and end of all parenthesized groups in the pattern. Indices
are relative to the string argument passed to \code{match} or
\code{search}. The 0-th tuple gives the beginning and end or the
whole pattern. When the last match or search failed, this is
\code{None}.
\end{datadesc}
\begin{datadesc}{last}
When the last call to the \code{match} or \code{search} method found a
match, this is the string argument passed to that method. When the
last match or search failed, this is \code{None}.
\end{datadesc}
\begin{datadesc}{translate}
This is the value of the \var{translate} argument to
\code{regex.compile} that created this regular expression object. If
the \var{translate} argument was omitted in the \code{regex.compile}
call, this is \code{None}.
\end{datadesc}
\section{Standard Module \sectcode{regsub}}
\stmodindex{regsub}
This module defines a number of functions useful for working with
regular expressions (see built-in module \code{regex}).
\renewcommand{\indexsubitem}{(in module regsub)}
\begin{funcdesc}{sub}{pat\, repl\, str}
Replace the first occurrence of pattern \var{pat} in string
\var{str} by replacement \var{repl}. If the pattern isn't found,
the string is returned unchanged. The pattern may be a string or an
already compiled pattern. The replacement may contain references
\samp{\e \var{digit}} to subpatterns and escaped backslashes.
\end{funcdesc}
\begin{funcdesc}{gsub}{pat\, repl\, str}
Replace all (non-overlapping) occurrences of pattern \var{pat} in
string \var{str} by replacement \var{repl}. The same rules as for
\code{sub()} apply. Empty matches for the pattern are replaced only
when not adjacent to a previous match, so e.g.
\code{gsub('', '-', 'abc')} returns \code{'-a-b-c-'}.
\end{funcdesc}
\begin{funcdesc}{split}{str\, pat}
Split the string \var{str} in fields separated by delimiters matching
the pattern \var{pat}, and return a list containing the fields. Only
non-empty matches for the pattern are considered, so e.g.
\code{split('a:b', ':*')} returns \code{['a', 'b']} and
\code{split('abc', '')} returns \code{['abc']}.
\end{funcdesc}
\section{Built-in module \sectcode{rgbimg}}
\bimodindex{rgbimg}
The rgbimg module allows python programs to access SGI imglib image
files (also known as \file{.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:
\renewcommand{\indexsubitem}{(in module rgbimg)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unsupported file type, etc.
\end{excdesc}
\begin{funcdesc}{sizeofimage}{file}
This function returns a tuple \code{(\var{x}, \var{y})} where
\var{x} and \var{y} are the size of the image in pixels.
Only 4 byte RGBA pixels, 3 byte RGB pixels, and 1 byte greyscale pixels
are currently supported.
\end{funcdesc}
\begin{funcdesc}{longimagedata}{file}
This function reads and decodes the image on the specified file, and
returns it as a python string. The string has 4 byte RGBA pixels.
The bottom left pixel is the first in
the string. This format is suitable to pass to \code{gl.lrectwrite},
for instance.
\end{funcdesc}
\begin{funcdesc}{longstoimage}{data\, x\, y\, z\, file}
This function writes the RGBA data in \var{data} to image
file \var{file}. \var{x} and \var{y} give the size of the image.
\var{z} is 1 if the saved image should be 1 byte greyscale, 3 if the
saved image should be 3 byte RGB data, or 4 if the saved images should
be 4 byte RGBA data. The input data always contains 4 bytes per pixel.
These are the formats returned by \code{gl.lrectread}.
\end{funcdesc}
\begin{funcdesc}{ttob}{flag}
This function sets a global flag which defines whether the scan lines
of the image are read or written from bottom to top (flag is zero,
compatible with SGI GL) or from top to bottom(flag is one,
compatible with X). The default is zero.
\end{funcdesc}
\section{Built-in module \sectcode{rotor}}
\bimodindex{rotor}
This module implements a rotor-based encryption algorithm, contributed
by Lance Ellinghouse. Currently no further documentation is available
--- you are kindly advised to read the source...
\section{Built-in module \sectcode{select}}
\bimodindex{select}
This module provides access to the function \code{select} available in
most \UNIX{} versions. It defines the following:
\renewcommand{\indexsubitem}{(in module select)}
\begin{excdesc}{error}
The exception raised when an error occurs. The accompanying value is
a pair containing the numeric error code from \code{errno} and the
corresponding string, as would be printed by the C function
\code{perror()}.
\end{excdesc}
\begin{funcdesc}{select}{iwtd\, owtd\, ewtd\, timeout}
This is a straightforward interface to the \UNIX{} \code{select()}
system call. The first three arguments are lists of `waitable
objects': either integers representing \UNIX{} file descriptors or
objects with a parameterless method named \code{fileno()} returning
such an integer. The three lists of waitable objects are for input,
output and `exceptional conditions', respectively. Empty lists are
allowed. The optional last argument is a time-out specified as a
floating point number in seconds. When the \var{timeout} argument
is omitted the function blocks until at least one file descriptor is
ready. A time-out value of zero specifies a poll and never blocks.
The return value is a triple of lists of objects that are ready:
subsets of the first three arguments. When the time-out is reached
without a file descriptor becoming ready, three empty lists are
returned.
Amongst the acceptable object types in the lists are Python file
objects (e.g. \code{sys.stdin}, or objects returned by \code{open()}
or \code{posix.popen()}), socket objects returned by
\code{socket.socket()}, and the module \code{stdwin} which happens to
define a function \code{fileno()} for just this purpose. You may
also define a \dfn{wrapper} class yourself, as long as it has an
appropriate \code{fileno()} method (that really returns a \UNIX{} file
descriptor, not just a random integer).
\end{funcdesc}
\ttindex{socket}
\ttindex{stdwin}
\chapter{SGI IRIX ONLY}
The modules described in this chapter provide interfaces to features
that are unique to SGI's IRIX operating system (versions 4 and 5).
This diff is collapsed.
This diff is collapsed.
\section{Standard Module \sectcode{string}}
\stmodindex{string}
This module defines some constants useful for checking character
classes, some exceptions, and some useful string functions.
The constants are:
\renewcommand{\indexsubitem}{(data in module string)}
\begin{datadesc}{digits}
The string \code{'0123456789'}.
\end{datadesc}
\begin{datadesc}{hexdigits}
The string \code{'0123456789abcdefABCDEF'}.
\end{datadesc}
\begin{datadesc}{letters}
The concatenation of the strings \code{lowercase} and
\code{uppercase} described below.
\end{datadesc}
\begin{datadesc}{lowercase}
A string containing all the characters that are considered lowercase
letters. On most systems this is the string
\code{'abcdefghijklmnopqrstuvwxyz'}. Do not change its definition --
the effect on the routines \code{upper} and \code{swapcase} is
undefined.
\end{datadesc}
\begin{datadesc}{octdigits}
The string \code{'01234567'}.
\end{datadesc}
\begin{datadesc}{uppercase}
A string containing all the characters that are considered uppercase
letters. On most systems this is the string
\code{'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}. Do not change its definition --
the effect on the routines \code{lower} and \code{swapcase} is
undefined.
\end{datadesc}
\begin{datadesc}{whitespace}
A string containing all characters that are considered whitespace.
On most systems this includes the characters space, tab, linefeed,
return, formfeed, and vertical tab. Do not change its definition --
the effect on the routines \code{strip} and \code{split} is
undefined.
\end{datadesc}
The exceptions are:
\renewcommand{\indexsubitem}{(exception in module string)}
\begin{excdesc}{atof_error}
Exception raised by
\code{atof}
when a non-float string argument is detected.
The exception argument is the offending string.
\end{excdesc}
\begin{excdesc}{atoi_error}
Exception raised by
\code{atoi}
when a non-integer string argument is detected.
The exception argument is the offending string.
\end{excdesc}
\begin{excdesc}{atol_error}
Exception raised by
\code{atol}
when a non-integer string argument is detected.
The exception argument is the offending string.
\end{excdesc}
\begin{excdesc}{index_error}
Exception raised by \code{index} when \var{sub} is not found.
The exception argument is undefined (it may be a tuple containing the
offending arguments to \code{index} or it may be the constant string
\code{'substring not found'}).
\end{excdesc}
The functions are:
\renewcommand{\indexsubitem}{(in module string)}
\begin{funcdesc}{atof}{s}
Convert a string to a floating point number. The string must have
the standard syntax for a floating point literal in Python, optionally
preceded by a sign (\samp{+} or \samp{-}).
\end{funcdesc}
\begin{funcdesc}{atoi}{s}
Convert a string to an integer. The string must consist of one or more
digits, optionally preceded by a sign (\samp{+} or \samp{-}).
\end{funcdesc}
\begin{funcdesc}{atol}{s}
Convert a string to a long integer. The string must consist of one
or more digits, optionally preceded by a sign (\samp{+} or \samp{-}).
\end{funcdesc}
\begin{funcdesc}{expandtabs}{s\, tabsize}
Expand tabs in a string, i.e. replace them by one or more spaces,
depending on the current column and the given tab size. The column
number is reset to zero after each newline occurring in the string.
This doesn't understand other non-printing characters or escape
sequences.
\end{funcdesc}
\begin{funcdesc}{find}{s\, sub\, i}
Return the lowest index in \var{s} not smaller than \var{i} where the
substring \var{sub} is found. Return \code{-1} when \var{sub}
does not occur as a substring of \var{s} with index at least \var{i}.
If \var{i} is omitted, it defaults to \code{0}. If \var{i} is
negative, \code{len(\var{s})} is added.
\end{funcdesc}
\begin{funcdesc}{rfind}{s\, sub\, i}
Like \code{find} but finds the highest index.
\end{funcdesc}
\begin{funcdesc}{index}{s\, sub\, i}
Like \code{find} but raise \code{index_error} when the substring is
not found.
\end{funcdesc}
\begin{funcdesc}{rindex}{s\, sub\, i}
Like \code{rfind} but raise \code{index_error} when the substring is
not found.
\end{funcdesc}
\begin{funcdesc}{lower}{s}
Convert letters to lower case.
\end{funcdesc}
\begin{funcdesc}{split}{s}
Returns a list of the whitespace-delimited words of the string
\var{s}.
\end{funcdesc}
\begin{funcdesc}{splitfields}{s\, sep}
Returns a list containing the fields of the string \var{s}, using
the string \var{sep} as a separator. The list will have one more
items than the number of non-overlapping occurrences of the
separator in the string. Thus, \code{string.splitfields(\var{s}, '
')} is not the same as \code{string.split(\var{s})}, as the latter
only returns non-empty words. As a special case,
\code{splitfields(\var{s}, '')} returns \code{[\var{s}]}, for any string
\var{s}. (See also \code{regsub.split()}.)
\end{funcdesc}
\begin{funcdesc}{join}{words}
Concatenate a list or tuple of words with intervening spaces.
\end{funcdesc}
\begin{funcdesc}{joinfields}{words\, sep}
Concatenate a list or tuple of words with intervening separators.
It is always true that
\code{string.joinfields(string.splitfields(\var{t}, \var{sep}), \var{sep})}
equals \var{t}.
\end{funcdesc}
\begin{funcdesc}{strip}{s}
Removes leading and trailing whitespace from the string
\var{s}.
\end{funcdesc}
\begin{funcdesc}{swapcase}{s}
Converts lower case letters to upper case and vice versa.
\end{funcdesc}
\begin{funcdesc}{upper}{s}
Convert letters to upper case.
\end{funcdesc}
\begin{funcdesc}{ljust}{s\, width}
\funcline{rjust}{s\, width}
\funcline{center}{s\, width}
These functions respectively left-justify, right-justify and center a
string in a field of given width.
They return a string that is at least
\var{width}
characters wide, created by padding the string
\var{s}
with spaces until the given width on the right, left or both sides.
The string is never truncated.
\end{funcdesc}
\begin{funcdesc}{zfill}{s\, width}
Pad a numeric string on the left with zero digits until the given
width is reached. Strings starting with a sign are handled correctly.
\end{funcdesc}
\section{Built-in module \sectcode{struct}}
\bimodindex{struct}
\indexii{C}{structures}
This module performs conversions between Python values and C
structs represented as Python strings. It uses \dfn{format strings}
(explained below) as compact descriptions of the lay-out of the C
structs and the intended conversion to/from Python values.
The module defines the following exception and functions:
\renewcommand{\indexsubitem}{(in module struct)}
\begin{excdesc}{error}
Exception raised on various occasions; argument is a string
describing what is wrong.
\end{excdesc}
\begin{funcdesc}{pack}{fmt\, v1\, v2\, {\rm \ldots}}
Return a string containing the values
\code{\var{v1}, \var{v2}, {\rm \ldots}} packed according to the given
format. The arguments must match the values required by the format
exactly.
\end{funcdesc}
\begin{funcdesc}{unpack}{fmt\, string}
Unpack the string (presumably packed by \code{pack(\var{fmt}, {\rm \ldots})})
according to the given format. The result is a tuple even if it
contains exactly one item. The string must contain exactly the
amount of data required by the format (i.e. \code{len(\var{string})} must
equal \code{calcsize(\var{fmt})}).
\end{funcdesc}
\begin{funcdesc}{calcsize}{fmt}
Return the size of the struct (and hence of the string)
corresponding to the given format.
\end{funcdesc}
Format characters have the following meaning; the conversion between C
and Python values should be obvious given their types:
\begin{tableiii}{|c|l|l|}{samp}{Format}{C}{Python}
\lineiii{x}{pad byte}{no value}
\lineiii{c}{char}{string of length 1}
\lineiii{b}{signed char}{integer}
\lineiii{h}{short}{integer}
\lineiii{i}{int}{integer}
\lineiii{l}{long}{integer}
\lineiii{f}{float}{float}
\lineiii{d}{double}{float}
\end{tableiii}
A format character may be preceded by an integral repeat count; e.g.
the format string \code{'4h'} means exactly the same as \code{'hhhh'}.
C numbers are represented in the machine's native format and byte
order, and properly aligned by skipping pad bytes if necessary
(according to the rules used by the C compiler).
Examples (all on a big-endian machine):
\bcode\begin{verbatim}
pack('hhl', 1, 2, 3) == '\000\001\000\002\000\000\000\003'
unpack('hhl', '\000\001\000\002\000\000\000\003') == (1, 2, 3)
calcsize('hhl') == 8
\end{verbatim}\ecode
Hint: to align the end of a structure to the alignment requirement of
a particular type, end the format with the code for that type with a
repeat count of zero, e.g. the format \code{'llh0l'} specifies two
pad bytes at the end, assuming longs are aligned on 4-byte boundaries.
(More format characters are planned, e.g. \code{'s'} for character
arrays, upper case for unsigned variants, and a way to specify the
byte order, which is useful for [de]constructing network packets and
reading/writing portable binary file formats like TIFF and AIFF.)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
\chapter{UNIX ONLY}
The modules described in this chapter provide interfaces to features
that are unique to the UNIX operating system, or in some cases to
some or many variants of it.
\section{Standard Module \sectcode{whrandom}}
\stmodindex{whrandom}
This module implements a Wichmann-Hill pseudo-random number generator.
It defines the following functions:
\renewcommand{\indexsubitem}{(in module whrandom)}
\begin{funcdesc}{random}{}
Returns the next random floating point number in the range [0.0 ... 1.0).
\end{funcdesc}
\begin{funcdesc}{seed}{x\, y\, z}
Initializes the random number generator from the integers
\var{x},
\var{y}
and
\var{z}.
When the module is first imported, the random number is initialized
using values derived from the current time.
\end{funcdesc}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
\section{Built-in Module \sectcode{__builtin__}}
\bimodindex{__builtin__}
This module provides direct access to all `built-in' identifier of
Python; e.g. \code{__builtin__.open} is the full name for the built-in
function \code{open}.
\chapter{CRYPTOGRAPHIC EXTENSIONS}
The modules described in this chapter implement various algorithms of
a cryptographic nature. They are available at the discretion of the
installation.
\section{Built-in Module \sectcode{dbm}}
\bimodindex{dbm}
Dbm provides python programs with an interface to the unix \code{ndbm}
database library. Dbm objects are of the mapping type, so they can be
handled just like objects of the built-in \dfn{dictionary} type,
except that keys and values are always strings, and printing a dbm
object doesn't print the keys and values.
The module defines the following constant and functions:
\renewcommand{\indexsubitem}{(in module dbm)}
\begin{excdesc}{error}
Raised on dbm-specific errors, such as I/O errors. \code{KeyError} is
raised for general mapping errors like specifying an incorrect key.
\end{excdesc}
\begin{funcdesc}{open}{filename\, rwmode\, filemode}
Open a dbm database and return a mapping object. \var{filename} is
the name of the database file (without the \file{.dir} or \file{.pag}
extensions), \var{rwmode} is \code{'r'}, \code{'w'} or \code{'rw'} as for
\code{open}, and \var{filemode} is the unix mode of the file, used only
when the database has to be created.
\end{funcdesc}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
\chapter{Introduction}
The Python library consists of three parts, with different levels of
integration with the interpreter.
Closest to the interpreter are built-in types, exceptions and functions.
Next are built-in modules, which are written in \C{} and linked statically
with the interpreter.
Finally there are standard modules that are implemented entirely in
Python, but are always available.
For efficiency, some standard modules may become built-in modules in
future versions of the interpreter.
\indexii{built-in}{types}
\indexii{built-in}{exceptions}
\indexii{built-in}{functions}
\indexii{built-in}{modules}
\indexii{standard}{modules}
\indexii{\C{}}{language}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment