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
\section{Built-in module \sectcode{audioop}}
\bimodindex{audioop}
The audioop module contains some useful operations on sound fragments.
It operates on sound fragments consisting of signed integer samples of
8, 16 or 32 bits wide, stored in Python strings. This is the same
format as used by the \code{al} and \code{sunaudiodev} modules. All
scalar items are integers, unless specified otherwise.
A few of the more complicated operations only take 16-bit samples,
otherwise the sample size (in bytes) is always a parameter of the operation.
The module defines the following variables and functions:
\renewcommand{\indexsubitem}{(in module audioop)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unknown number of bytes
per sample, etc.
\end{excdesc}
\begin{funcdesc}{add}{fragment1\, fragment2\, width}
This function returns a fragment that is the addition of the two samples
passed as parameters. \var{width} is the sample width in bytes, either
\code{1}, \code{2} or \code{4}. Both fragments should have the same length.
\end{funcdesc}
\begin{funcdesc}{adpcm2lin}{adpcmfragment\, width\, state}
This routine decodes an Intel/DVI ADPCM coded fragment to a linear
fragment. See the description of \code{lin2adpcm} for details on ADPCM
coding. The routine returns a tuple
\code{(\var{sample}, \var{newstate})}
where the sample has the width specified in \var{width}.
\end{funcdesc}
\begin{funcdesc}{adpcm32lin}{adpcmfragment\, width\, state}
This routine decodes an alternative 3-bit ADPCM code. See
\code{lin2adpcm3} for details.
\end{funcdesc}
\begin{funcdesc}{avg}{fragment\, width}
This function returns the average over all samples in the fragment.
\end{funcdesc}
\begin{funcdesc}{avgpp}{fragment\, width}
This function returns the average peak-peak value over all samples in
the fragment. No filtering is done, so the useability of this routine
is questionable.
\end{funcdesc}
\begin{funcdesc}{bias}{fragment\, width\, bias}
This function returns a fragment that is the original fragment with a
bias added to each sample.
\end{funcdesc}
\begin{funcdesc}{cross}{fragment\, width}
This function returns the number of zero crossings in the fragment
passed as an argument.
\end{funcdesc}
\begin{funcdesc}{findfactor}{fragment\, reference}
This routine (which only accepts 2-byte sample fragments) calculates a
factor \var{F} such that \code{rms(add(fragment, mul(reference, -F)))}
is minimal, i.e. it calculates the factor with which you should
multiply \var{reference} to make it match as good as possible to
\var{fragment}. The fragments should be the same size.
The time taken by this routine is proportional to \code{len(fragment)}.
\end{funcdesc}
\begin{funcdesc}{findfit}{fragment\, reference}
This routine (which only accepts 2-byte sample fragments) tries to
match \var{reference} as good as possible to a portion of
\var{fragment} (which should be the longer fragment). It
(conceptually) does this by taking slices out of \var{fragment}, using
\code{findfactor} to compute the best match, and minimizing the
result.
It returns a tuple \code{(\var{offset}, \var{factor})} with offset the
(integer) offset into \var{fragment} where the optimal match started
and \var{factor} the floating-point factor as per findfactor.
\end{funcdesc}
\begin{funcdesc}{findmax}{fragment\, length}
This routine (which only accepts 2-byte sample fragments) searches
\var{fragment} for a slice of length \var{length} samples (not bytes!)
with maximum energy, i.e. it returns \var{i} for which
\code{rms(fragment[i*2:(i+length)*2])} is maximal.
The routine takes time proportional to \code{len(fragment)}.
\end{funcdesc}
\begin{funcdesc}{getsample}{fragment\, width\, index}
This function returns the value of sample \var{index} from the
fragment.
\end{funcdesc}
\begin{funcdesc}{lin2lin}{fragment\, width\, newwidth}
This function converts samples between 1-, 2- and 4-byte formats.
\end{funcdesc}
\begin{funcdesc}{lin2adpcm}{fragment\, width\, state}
This function converts samples to 4 bit Intel/DVI ADPCM encoding.
ADPCM coding is an adaptive coding scheme, whereby each 4 bit number
is the difference between one sample and the next, divided by a
(varying) step. The Intel/DVI ADPCM algorythm has been selected for
use by the IMA, so may well become a standard.
\code{State} is a tuple containing the state of the coder. The coder
returns a tuple \code{(\var{adpcmfrag}, \var{newstate})}, and the
\var{newstate} should be passed to the next call of lin2adpcm. In the
initial call \code{None} can be passed as the state. \var{adpcmfrag} is
the ADPCM coded fragment packed 2 4-bit values per byte.
\end{funcdesc}
\begin{funcdesc}{lin2adpcm3}{fragment\, width\, state}
This is an alternative ADPCM coder that uses only 3 bits per sample.
It is not compatible with the Intel/DVI ADPCM coder and its output is
not packed (due to laziness on the side of the author). Its use is
discouraged.
\end{funcdesc}
\begin{funcdesc}{lin2ulaw}{fragment\, width}
This function converts samples in the audio fragment to U-LAW encoding
and returns this as a python string. U-LAW is an audio encoding format
whereby you get a dynamic range of about 14 bits using only 8 bit
samples. It is used by the Sun audio hardware, among others.
\end{funcdesc}
\begin{funcdesc}{minmax}{fragment\, width}
This function returns a tuple consisting of the minimum and maximum
values of all samples in the sound fragment.
\end{funcdesc}
\begin{funcdesc}{max}{fragment\, width}
This function returns the maximum of the {\em absolute value} of all
samples in a fragment.
\end{funcdesc}
\begin{funcdesc}{maxpp}{fragment\, width}
This function returns the maximum peak-peak value in the sound fragment.
\end{funcdesc}
\begin{funcdesc}{mul}{fragment\, width\, factor}
Mul returns a fragment that has all samples in the original framgent
multiplied by the floating-point value \var{factor}. Overflow is
silently ignored.
\end{funcdesc}
\begin{funcdesc}{reverse}{fragment\, width}
This function reverses the samples in a fragment and returns the
modified fragment.
\end{funcdesc}
\begin{funcdesc}{tomono}{fragment\, width\, lfactor\, rfactor}
This function converts a stereo fragment to a mono fragment. The left
channel is multiplied by \var{lfactor} and the right channel by
\var{rfactor} before adding the two channels to give a mono signal.
\end{funcdesc}
\begin{funcdesc}{tostereo}{fragment\, width\, lfactor\, rfactor}
This function generates a stereo fragment from a mono fragment. Each
pair of samples in the stereo fragment are computed from the mono
sample, whereby left channel samples are multiplied by \var{lfactor}
and right channel samples by \var{rfactor}.
\end{funcdesc}
\begin{funcdesc}{mul}{fragment\, width\, factor}
Mul returns a fragment that has all samples in the original framgent
multiplied by the floating-point value \var{factor}. Overflow is
silently ignored.
\end{funcdesc}
\begin{funcdesc}{rms}{fragment\, width\, factor}
Returns the root-mean-square of the fragment, i.e.
\iftexi
the square root of the quotient of the sum of all squared sample value,
divided by the sumber of samples.
\else
% in eqn: sqrt { sum S sub i sup 2 over n }
\begin{displaymath}
\catcode`_=8
\sqrt{\frac{\sum{{S_{i}}^{2}}}{n}}
\end{displaymath}
\fi
This is a measure of the power in an audio signal.
\end{funcdesc}
\begin{funcdesc}{ulaw2lin}{fragment\, width}
This function converts sound fragments in ULAW encoding to linearly
encoded sound fragments. ULAW encoding always uses 8 bits samples, so
\var{width} refers only to the sample width of the output fragment here.
\end{funcdesc}
Note that operations such as \code{mul} or \code{max} make no
distinction between mono and stereo fragments, i.e. all samples are
treated equal. If this is a problem the stereo fragment should be split
into two mono fragments first and recombined later. Here is an example
of how to do that:
\bcode\begin{verbatim}
def mul_stereo(sample, width, lfactor, rfactor):
lsample = audioop.tomono(sample, width, 1, 0)
rsample = audioop.tomono(sample, width, 0, 1)
lsample = audioop.mul(sample, width, lfactor)
rsample = audioop.mul(sample, width, rfactor)
lsample = audioop.tostereo(lsample, width, 1, 0)
rsample = audioop.tostereo(rsample, width, 0, 1)
return audioop.add(lsample, rsample, width)
\end{verbatim}\ecode
If you use the ADPCM coder to build network packets and you want your
protocol to be stateless (i.e. to be able to tolerate packet loss)
you should not only transmit the data but also the state. Note that
you should send the \var{initial} state (the one you passed to
lin2adpcm) along to the decoder, not the final state (as returned by
the coder). If you want to use \code{struct} to store the state in
binary you can code the first element (the predicted value) in 16 bits
and the second (the delta index) in 8.
The ADPCM coders have never been tried against other ADPCM coders,
only against themselves. It could well be that I misinterpreted the
standards in which case they will not be interoperable with the
respective standards.
The \code{find...} routines might look a bit funny at first sight.
They are primarily meant for doing echo cancellation. A reasonably
fast way to do this is to pick the most energetic piece of the output
sample, locate that in the input sample and subtract the whole output
sample from the input sample:
\bcode\begin{verbatim}
def echocancel(outputdata, inputdata):
pos = audioop.findmax(outputdata, 800) # one tenth second
out_test = outputdata[pos*2:]
in_test = inputdata[pos*2:]
ipos, factor = audioop.findfit(in_test, out_test)
# Optional (for better cancellation):
# factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
# out_test)
prefill = '\0'*(pos+ipos)*2
postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
return audioop.add(inputdata, outputdata, 2)
\end{verbatim}\ecode
\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}
\section{Built-in Module \sectcode{fl}}
\bimodindex{fl}
This module provides an interface to the FORMS Library by Mark
Overmars, version 2.0b. For more info about FORMS, write to
{\tt markov@cs.ruu.nl}.
Most functions are literal translations of their C equivalents,
dropping the initial \samp{fl_} from their name. Constants used by the
library are defined in module \code{FL} described below.
The creation of objects is a little different in Python than in C:
instead of the `current form' maintained by the library to which new
FORMS objects are added, all functions that add a FORMS object to a
button are methods of the Python object representing the form.
Consequently, there are no Python equivalents for the C functions
\code{fl_addto_form} and \code{fl_end_form}, and the equivalent of
\code{fl_bgn_form} is called \code{fl.make_form}.
Watch out for the somewhat confusing terminology: FORMS uses the word
\dfn{object} for the buttons, sliders etc. that you can place in a form.
In Python, `object' means any value. The Python interface to FORMS
introduces two new Python object types: form objects (representing an
entire form) and FORMS objects (representing one button, slider etc.).
Hopefully this isn't too confusing...
There are no `free objects' in the Python interface to FORMS, nor is
there an easy way to add object classes written in Python. The FORMS
interface to GL event handling is avaiable, though, so you can mix
FORMS with pure GL windows.
\strong{Please note:} importing \code{fl} implies a call to the GL function
\code{foreground()} and to the FORMS routine \code{fl_init()}.
\subsection{Functions defined in module \sectcode{fl}}
Module \code{fl} defines the following functions. For more information
about what they do, see the description of the equivalent C function
in the FORMS documentation:
\renewcommand{\indexsubitem}{(in module fl)}
\begin{funcdesc}{make_form}{type\, width\, height}
Create a form with given type, width and height. This returns a
\dfn{form} object, whose methods are described below.
\end{funcdesc}
\begin{funcdesc}{do_forms}{}
The standard FORMS main loop. Returns a Python object representing
the FORMS object needing interaction, or the special value
\code{FL.EVENT}.
\end{funcdesc}
\begin{funcdesc}{check_forms}{}
Check for FORMS events. Returns what \code{do_forms} above returns,
or \code{None} if there is no event that immediately needs
interaction.
\end{funcdesc}
\begin{funcdesc}{set_event_call_back}{function}
Set the event callback function.
\end{funcdesc}
\begin{funcdesc}{set_graphics_mode}{rgbmode\, doublebuffering}
Set the graphics modes.
\end{funcdesc}
\begin{funcdesc}{get_rgbmode}{}
Return the current rgb mode. This is the value of the C global
variable \code{fl_rgbmode}.
\end{funcdesc}
\begin{funcdesc}{show_message}{str1\, str2\, str3}
Show a dialog box with a three-line message and an OK button.
\end{funcdesc}
\begin{funcdesc}{show_question}{str1\, str2\, str3}
Show a dialog box with a three-line message and YES and NO buttons.
It returns \code{1} if the user pressed YES, \code{0} if NO.
\end{funcdesc}
\begin{funcdesc}{show_choice}{str1\, str2\, str3\, but1\, but2\, but3}
Show a dialog box with a three-line message and up to three buttons.
It returns the number of the button clicked by the user
(\code{1}, \code{2} or \code{3}).
The \var{but2} and \var{but3} arguments are optional.
\end{funcdesc}
\begin{funcdesc}{show_input}{prompt\, default}
Show a dialog box with a one-line prompt message and text field in
which the user can enter a string. The second argument is the default
input string. It returns the string value as edited by the user.
\end{funcdesc}
\begin{funcdesc}{show_file_selector}{message\, directory\, pattern\, default}
Show a dialog box inm which the user can select a file. It returns
the absolute filename selected by the user, or \code{None} if the user
presses Cancel.
\end{funcdesc}
\begin{funcdesc}{get_directory}{}
\funcline{get_pattern}{}
\funcline{get_filename}{}
These functions return the directory, pattern and filename (the tail
part only) selected by the user in the last \code{show_file_selector}
call.
\end{funcdesc}
\begin{funcdesc}{qdevice}{dev}
\funcline{unqdevice}{dev}
\funcline{isqueued}{dev}
\funcline{qtest}{}
\funcline{qread}{}
%\funcline{blkqread}{?}
\funcline{qreset}{}
\funcline{qenter}{dev\, val}
\funcline{get_mouse}{}
\funcline{tie}{button\, valuator1\, valuator2}
These functions are the FORMS interfaces to the corresponding GL
functions. Use these if you want to handle some GL events yourself
when using \code{fl.do_events}. When a GL event is detected that
FORMS cannot handle, \code{fl.do_forms()} returns the special value
\code{FL.EVENT} and you should call \code{fl.qread()} to read the
event from the queue. Don't use the equivalent GL functions!
\end{funcdesc}
\begin{funcdesc}{color}{}
\funcline{mapcolor}{}
\funcline{getmcolor}{}
See the description in the FORMS documentation of \code{fl_color},
\code{fl_mapcolor} and \code{fl_getmcolor}.
\end{funcdesc}
\subsection{Form object methods and data attributes}
Form objects (returned by \code{fl.make_form()} above) have the
following methods. Each method corresponds to a C function whose name
is prefixed with \samp{fl_}; and whose first argument is a form
pointer; please refer to the official FORMS documentation for
descriptions.
All the \samp{add_{\rm \ldots}} functions return a Python object representing
the FORMS object. Methods of FORMS objects are described below. Most
kinds of FORMS object also have some methods specific to that kind;
these methods are listed here.
\begin{flushleft}
\renewcommand{\indexsubitem}{(form object method)}
\begin{funcdesc}{show_form}{placement\, bordertype\, name}
Show the form.
\end{funcdesc}
\begin{funcdesc}{hide_form}{}
Hide the form.
\end{funcdesc}
\begin{funcdesc}{redraw_form}{}
Redraw the form.
\end{funcdesc}
\begin{funcdesc}{set_form_position}{x\, y}
Set the form's position.
\end{funcdesc}
\begin{funcdesc}{freeze_form}{}
Freeze the form.
\end{funcdesc}
\begin{funcdesc}{unfreeze_form}{}
Unfreeze the form.
\end{funcdesc}
\begin{funcdesc}{activate_form}{}
Activate the form.
\end{funcdesc}
\begin{funcdesc}{deactivate_form}{}
Deactivate the form.
\end{funcdesc}
\begin{funcdesc}{bgn_group}{}
Begin a new group of objects; return a group object.
\end{funcdesc}
\begin{funcdesc}{end_group}{}
End the current group of objects.
\end{funcdesc}
\begin{funcdesc}{find_first}{}
Find the first object in the form.
\end{funcdesc}
\begin{funcdesc}{find_last}{}
Find the last object in the form.
\end{funcdesc}
%---
\begin{funcdesc}{add_box}{type\, x\, y\, w\, h\, name}
Add a box object to the form.
No extra methods.
\end{funcdesc}
\begin{funcdesc}{add_text}{type\, x\, y\, w\, h\, name}
Add a text object to the form.
No extra methods.
\end{funcdesc}
%\begin{funcdesc}{add_bitmap}{type\, x\, y\, w\, h\, name}
%Add a bitmap object to the form.
%\end{funcdesc}
\begin{funcdesc}{add_clock}{type\, x\, y\, w\, h\, name}
Add a clock object to the form. \\
Method:
\code{get_clock}.
\end{funcdesc}
%---
\begin{funcdesc}{add_button}{type\, x\, y\, w\, h\, name}
Add a button object to the form. \\
Methods:
\code{get_button},
\code{set_button}.
\end{funcdesc}
\begin{funcdesc}{add_lightbutton}{type\, x\, y\, w\, h\, name}
Add a lightbutton object to the form. \\
Methods:
\code{get_button},
\code{set_button}.
\end{funcdesc}
\begin{funcdesc}{add_roundbutton}{type\, x\, y\, w\, h\, name}
Add a roundbutton object to the form. \\
Methods:
\code{get_button},
\code{set_button}.
\end{funcdesc}
%---
\begin{funcdesc}{add_slider}{type\, x\, y\, w\, h\, name}
Add a slider object to the form. \\
Methods:
\code{set_slider_value},
\code{get_slider_value},
\code{set_slider_bounds},
\code{get_slider_bounds},
\code{set_slider_return},
\code{set_slider_size},
\code{set_slider_precision},
\code{set_slider_step}.
\end{funcdesc}
\begin{funcdesc}{add_valslider}{type\, x\, y\, w\, h\, name}
Add a valslider object to the form. \\
Methods:
\code{set_slider_value},
\code{get_slider_value},
\code{set_slider_bounds},
\code{get_slider_bounds},
\code{set_slider_return},
\code{set_slider_size},
\code{set_slider_precision},
\code{set_slider_step}.
\end{funcdesc}
\begin{funcdesc}{add_dial}{type\, x\, y\, w\, h\, name}
Add a dial object to the form. \\
Methods:
\code{set_dial_value},
\code{get_dial_value},
\code{set_dial_bounds},
\code{get_dial_bounds}.
\end{funcdesc}
\begin{funcdesc}{add_positioner}{type\, x\, y\, w\, h\, name}
Add a positioner object to the form. \\
Methods:
\code{set_positioner_xvalue},
\code{set_positioner_yvalue},
\code{set_positioner_xbounds},
\code{set_positioner_ybounds},
\code{get_positioner_xvalue},
\code{get_positioner_yvalue},
\code{get_positioner_xbounds},
\code{get_positioner_ybounds}.
\end{funcdesc}
\begin{funcdesc}{add_counter}{type\, x\, y\, w\, h\, name}
Add a counter object to the form. \\
Methods:
\code{set_counter_value},
\code{get_counter_value},
\code{set_counter_bounds},
\code{set_counter_step},
\code{set_counter_precision},
\code{set_counter_return}.
\end{funcdesc}
%---
\begin{funcdesc}{add_input}{type\, x\, y\, w\, h\, name}
Add a input object to the form. \\
Methods:
\code{set_input},
\code{get_input},
\code{set_input_color},
\code{set_input_return}.
\end{funcdesc}
%---
\begin{funcdesc}{add_menu}{type\, x\, y\, w\, h\, name}
Add a menu object to the form. \\
Methods:
\code{set_menu},
\code{get_menu},
\code{addto_menu}.
\end{funcdesc}
\begin{funcdesc}{add_choice}{type\, x\, y\, w\, h\, name}
Add a choice object to the form. \\
Methods:
\code{set_choice},
\code{get_choice},
\code{clear_choice},
\code{addto_choice},
\code{replace_choice},
\code{delete_choice},
\code{get_choice_text},
\code{set_choice_fontsize},
\code{set_choice_fontstyle}.
\end{funcdesc}
\begin{funcdesc}{add_browser}{type\, x\, y\, w\, h\, name}
Add a browser object to the form. \\
Methods:
\code{set_browser_topline},
\code{clear_browser},
\code{add_browser_line},
\code{addto_browser},
\code{insert_browser_line},
\code{delete_browser_line},
\code{replace_browser_line},
\code{get_browser_line},
\code{load_browser},
\code{get_browser_maxline},
\code{select_browser_line},
\code{deselect_browser_line},
\code{deselect_browser},
\code{isselected_browser_line},
\code{get_browser},
\code{set_browser_fontsize},
\code{set_browser_fontstyle},
\code{set_browser_specialkey}.
\end{funcdesc}
%---
\begin{funcdesc}{add_timer}{type\, x\, y\, w\, h\, name}
Add a timer object to the form. \\
Methods:
\code{set_timer},
\code{get_timer}.
\end{funcdesc}
\end{flushleft}
Form objects have the following data attributes; see the FORMS
documentation:
\begin{tableiii}{|l|c|l|}{code}{Name}{Type}{Meaning}
\lineiii{window}{int (read-only)}{GL window id}
\lineiii{w}{float}{form width}
\lineiii{h}{float}{form height}
\lineiii{x}{float}{form x origin}
\lineiii{y}{float}{form y origin}
\lineiii{deactivated}{int}{nonzero if form is deactivated}
\lineiii{visible}{int}{nonzero if form is visible}
\lineiii{frozen}{int}{nonzero if form is frozen}
\lineiii{doublebuf}{int}{nonzero if double buffering on}
\end{tableiii}
\subsection{FORMS object methods and data attributes}
Besides methods specific to particular kinds of FORMS objects, all
FORMS objects also have the following methods:
\renewcommand{\indexsubitem}{(FORMS object method)}
\begin{funcdesc}{set_call_back}{function\, argument}
Set the object's callback function and argument. When the object
needs interaction, the callback function will be called with two
arguments: the object, and the callback argument. (FORMS objects
without a callback function are returned by \code{fl.do_forms()} or
\code{fl.check_forms()} when they need interaction.) Call this method
without arguments to remove the callback function.
\end{funcdesc}
\begin{funcdesc}{delete_object}{}
Delete the object.
\end{funcdesc}
\begin{funcdesc}{show_object}{}
Show the object.
\end{funcdesc}
\begin{funcdesc}{hide_object}{}
Hide the object.
\end{funcdesc}
\begin{funcdesc}{redraw_object}{}
Redraw the object.
\end{funcdesc}
\begin{funcdesc}{freeze_object}{}
Freeze the object.
\end{funcdesc}
\begin{funcdesc}{unfreeze_object}{}
Unfreeze the object.
\end{funcdesc}
%\begin{funcdesc}{handle_object}{} XXX
%\end{funcdesc}
%\begin{funcdesc}{handle_object_direct}{} XXX
%\end{funcdesc}
FORMS objects have these data attributes; see the FORMS documentation:
\begin{tableiii}{|l|c|l|}{code}{Name}{Type}{Meaning}
\lineiii{objclass}{int (read-only)}{object class}
\lineiii{type}{int (read-only)}{object type}
\lineiii{boxtype}{int}{box type}
\lineiii{x}{float}{x origin}
\lineiii{y}{float}{y origin}
\lineiii{w}{float}{width}
\lineiii{h}{float}{height}
\lineiii{col1}{int}{primary color}
\lineiii{col2}{int}{secondary color}
\lineiii{align}{int}{alignment}
\lineiii{lcol}{int}{label color}
\lineiii{lsize}{float}{label font size}
\lineiii{label}{string}{label string}
\lineiii{lstyle}{int}{label style}
\lineiii{pushed}{int (read-only)}{(see FORMS docs)}
\lineiii{focus}{int (read-only)}{(see FORMS docs)}
\lineiii{belowmouse}{int (read-only)}{(see FORMS docs)}
\lineiii{frozen}{int (read-only)}{(see FORMS docs)}
\lineiii{active}{int (read-only)}{(see FORMS docs)}
\lineiii{input}{int (read-only)}{(see FORMS docs)}
\lineiii{visible}{int (read-only)}{(see FORMS docs)}
\lineiii{radio}{int (read-only)}{(see FORMS docs)}
\lineiii{automatic}{int (read-only)}{(see FORMS docs)}
\end{tableiii}
\section{Standard Module \sectcode{FL}}
\nodename{FL (uppercase)}
\stmodindex{FL}
This module defines symbolic constants needed to use the built-in
module \code{fl} (see above); they are equivalent to those defined in
the C header file \file{<forms.h>} except that the name prefix
\samp{FL_} is omitted. Read the module source for a complete list of
the defined names. Suggested use:
\bcode\begin{verbatim}
import fl
from FL import *
\end{verbatim}\ecode
\section{Standard Module \sectcode{flp}}
\stmodindex{flp}
This module defines functions that can read form definitions created
by the `form designer' (\code{fdesign}) program that comes with the
FORMS library (see module \code{fl} above).
For now, see the file \file{flp.doc} in the Python library source
directory for a description.
XXX A complete description should be inserted here!
\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}
\section{Built-in Functions}
The Python interpreter has a number of functions built into it that
are always available. They are listed here in alphabetical order.
\renewcommand{\indexsubitem}{(built-in function)}
\begin{funcdesc}{abs}{x}
Return the absolute value of a number. The argument may be a plain
or long integer or a floating point number.
\end{funcdesc}
\begin{funcdesc}{apply}{function\, args}
The \var{function} argument must be a callable object (a user-defined or
built-in function or method, or a class object) and the \var{args}
argument must be a tuple. The \var{function} is called with
\var{args} as argument list; the number of arguments is the the length
of the tuple. (This is different from just calling
\code{\var{func}(\var{args})}, since in that case there is always
exactly one argument.)
\end{funcdesc}
\begin{funcdesc}{chr}{i}
Return a string of one character whose \ASCII{} code is the integer
\var{i}, e.g., \code{chr(97)} returns the string \code{'a'}. This is the
inverse of \code{ord()}. The argument must be in the range [0..255],
inclusive.
\end{funcdesc}
\begin{funcdesc}{cmp}{x\, y}
Compare the two objects \var{x} and \var{y} and return an integer
according to the outcome. The return value is negative if \code{\var{x}
< \var{y}}, zero if \code{\var{x} == \var{y}} and strictly positive if
\code{\var{x} > \var{y}}.
\end{funcdesc}
\begin{funcdesc}{coerce}{x\, y}
Return a tuple consisting of the two numeric arguments converted to
a common type, using the same rules as used by arithmetic
operations.
\end{funcdesc}
\begin{funcdesc}{compile}{string\, filename\, kind}
Compile the \var{string} into a code object. Code objects can be
executed by a \code{exec()} statement or evaluated by a call to
\code{eval()}. The \var{filename} argument should
give the file from which the code was read; pass e.g. \code{'<string>'}
if it wasn't read from a file. The \var{kind} argument specifies
what kind of code must be compiled; it can be \code{'exec'} if
\var{string} consists of a sequence of statements, or \code{'eval'}
if it consists of a single expression.
\end{funcdesc}
\begin{funcdesc}{dir}{}
Without arguments, return the list of names in the current local
symbol table. With a module, class or class instance object as
argument (or anything else that has a \code{__dict__} attribute),
returns the list of names in that object's attribute dictionary.
The resulting list is sorted. For example:
\bcode\begin{verbatim}
>>> import sys
>>> dir()
['sys']
>>> dir(sys)
['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
>>>
\end{verbatim}\ecode
\end{funcdesc}
\begin{funcdesc}{divmod}{a\, b}
Take two numbers as arguments and return a pair of integers
consisting of their integer quotient and remainder. With mixed
operand types, the rules for binary arithmetic operators apply. For
plain and long integers, the result is the same as
\code{(\var{a} / \var{b}, \var{a} \%{} \var{b})}.
For floating point numbers the result is the same as
\code{(math.floor(\var{a} / \var{b}), \var{a} \%{} \var{b})}.
\end{funcdesc}
\begin{funcdesc}{eval}{s\, globals\, locals}
The arguments are a string and two optional dictionaries. The
string argument is parsed and evaluated as a Python expression
(technically speaking, a condition list) using the dictionaries as
global and local name space. The string must not contain null bytes
or newline characters. The return value is the
result of the expression. If the third argument is omitted it
defaults to the second. If both dictionaries are omitted, the
expression is executed in the environment where \code{eval} is
called. Syntax errors are reported as exceptions. Example:
\bcode\begin{verbatim}
>>> x = 1
>>> print eval('x+1')
2
>>>
\end{verbatim}\ecode
This function can also be used to execute arbitrary code objects
(e.g. created by \code{compile()}). In this case pass a code
object instead of a string. The code object must have been compiled
passing \code{'eval'} to the \var{kind} argument.
Note: dynamic execution of statements is supported by the
\code{exec} statement.
\end{funcdesc}
\begin{funcdesc}{filter}{function\, list}
Construct a list from those elements of \var{list} for which
\var{function} returns true. If \var{list} is a string or a tuple,
the result also has that type; otherwise it is always a list. If
\var{function} is \code{None}, the identity function is assumed,
i.e. all elements of \var{list} that are false (zero or empty) are
removed.
\end{funcdesc}
\begin{funcdesc}{float}{x}
Convert a number to floating point. The argument may be a plain or
long integer or a floating point number.
\end{funcdesc}
\begin{funcdesc}{getattr}{object\, name}
The arguments are an object and a string. The string must be the
name
of one of the object's attributes. The result is the value of that
attribute. For example, \code{getattr(\var{x}, '\var{foobar}')} is equivalent to
\code{\var{x}.\var{foobar}}.
\end{funcdesc}
\begin{funcdesc}{hasattr}{object\, name}
The arguments are an object and a string. The result is 1 if the
string is the name of one of the object's attributes, 0 if not.
(This is implemented by calling \code{getattr(object, name)} and
seeing whether it raises an exception or not.)
\end{funcdesc}
\begin{funcdesc}{hash}{object}
Return the hash value of the object (if it has one). Hash values
are 32-bit integers. They are used to quickly compare dictionary
keys during a dictionary lookup. Numeric values that compare equal
have the same hash value (even if they are of different types, e.g.
1 and 1.0).
\end{funcdesc}
\begin{funcdesc}{hex}{x}
Convert a number to a hexadecimal string. The result is a valid
Python expression.
\end{funcdesc}
\begin{funcdesc}{id}{object}
Return the `identity' of an object. This is an integer which is
guaranteed to be unique and constant for this object during its
lifetime. (Two objects whose lifetimes are disjunct may have the
same id() value.) (Implementation note: this is the address of the
object.)
\end{funcdesc}
\begin{funcdesc}{input}{prompt}
Almost equivalent to \code{eval(raw_input(\var{prompt}))}. As for
\code{raw_input()}, the prompt argument is optional. The difference is
that a long input expression may be broken over multiple lines using the
backslash convention.
\end{funcdesc}
\begin{funcdesc}{int}{x}
Convert a number to a plain integer. The argument may be a plain or
long integer or a floating point number.
\end{funcdesc}
\begin{funcdesc}{len}{s}
Return the length (the number of items) of an object. The argument
may be a sequence (string, tuple or list) or a mapping (dictionary).
\end{funcdesc}
\begin{funcdesc}{long}{x}
Convert a number to a long integer. The argument may be a plain or
long integer or a floating point number.
\end{funcdesc}
\begin{funcdesc}{map}{function\, list\, ...}
Apply \var{function} to every item of \var{list} and return a list
of the results. If additional \var{list} arguments are passed,
\var{function} must take that many arguments and is applied to
the items of all lists in parallel; if a list is shorter than another
it is assumed to be extended with \code{None} items. If
\var{function} is \code{None}, the identity function is assumed; if
there are multiple list arguments, \code{map} returns a list
consisting of tuples containing the corresponding items from all lists
(i.e. a kind of transpose operation). The \var{list} arguments may be
any kind of sequence; the result is always a list.
\end{funcdesc}
\begin{funcdesc}{max}{s}
Return the largest item of a non-empty sequence (string, tuple or
list).
\end{funcdesc}
\begin{funcdesc}{min}{s}
Return the smallest item of a non-empty sequence (string, tuple or
list).
\end{funcdesc}
\begin{funcdesc}{oct}{x}
Convert a number to an octal string. The result is a valid Python
expression.
\end{funcdesc}
\begin{funcdesc}{open}{filename\, mode}
% XXXJH xrefs here to Built-in types?
Return a new file object (described earlier under Built-in Types).
The string arguments are the same as for \code{stdio}'s
\code{fopen()}: \var{filename} is the file name to be opened,
\var{mode} indicates how the file is to be opened: \code{'r'} for
reading, \code{'w'} for writing (truncating an existing file), and
\code{'a'} opens it for appending. Modes \code{'r+'}, \code{'w+'} and
\code{'a+'} open the file for updating, provided the underlying
\code{stdio} library understands this. On systems that differentiate
between binary and text files, \code{'b'} appended to the mode opens
the file in binary mode. If the file cannot be opened, \code{IOError}
is raised.
\end{funcdesc}
\begin{funcdesc}{ord}{c}
Return the \ASCII{} value of a string of one character. E.g.,
\code{ord('a')} returns the integer \code{97}. This is the inverse of
\code{chr()}.
\end{funcdesc}
\begin{funcdesc}{pow}{x\, y}
Return \var{x} to the power \var{y}. The arguments must have
numeric types. With mixed operand types, the rules for binary
arithmetic operators apply. The effective operand type is also the
type of the result; if the result is not expressible in this type, the
function raises an exception; e.g., \code{pow(2, -1)} is not allowed.
\end{funcdesc}
\begin{funcdesc}{range}{start\, end\, step}
This is a versatile function to create lists containing arithmetic
progressions. It is most often used in \code{for} loops. The
arguments must be plain integers. If the \var{step} argument is
omitted, it defaults to \code{1}. If the \var{start} argument is
omitted, it defaults to \code{0}. The full form returns a list of
plain integers \code{[\var{start}, \var{start} + \var{step},
\var{start} + 2 * \var{step}, \ldots]}. If \var{step} is positive,
the last element is the largest \code{\var{start} + \var{i} *
\var{step}} less than \var{end}; if \var{step} is negative, the last
element is the largest \code{\var{start} + \var{i} * \var{step}}
greater than \var{end}. \var{step} must not be zero. Example:
\bcode\begin{verbatim}
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
>>>
\end{verbatim}\ecode
\end{funcdesc}
\begin{funcdesc}{raw_input}{prompt}
The string argument is optional; if present, it is written to
standard
output without a trailing newline. The function then reads a line
from input, converts it to a string (stripping a trailing newline),
and returns that. When \EOF{} is read, \code{EOFError} is raised.
Example:
\bcode\begin{verbatim}
>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
'Monty Python\'s Flying Circus'
>>>
\end{verbatim}\ecode
\end{funcdesc}
\begin{funcdesc}{reduce}{function\, list\, initializer}
Apply the binary \var{function} to the items of \var{list} so as to
reduce the list to a single value. E.g.,
\code{reduce(lambda x, y: x*y, \var{list}, 1)} returns the product of
the elements of \var{list}. The optional \var{initializer} can be
thought of as being prepended to \var{list} so as to allow reduction
of an empty \var{list}. The \var{list} arguments may be any kind of
sequence.
\end{funcdesc}
\begin{funcdesc}{reload}{module}
Re-parse and re-initialize an already imported \var{module}. The
argument must be a module object, so it must have been successfully
imported before. This is useful if you have edited the module source
file using an external editor and want to try out the new version
without leaving the Python interpreter. Note that if a module is
syntactically correct but its initialization fails, the first
\code{import} statement for it does not import the name, but does
create a (partially initialized) module object; to reload the module
you must first \code{import} it again (this will just make the
partially initialized module object available) before you can
\code{reload()} it.
\end{funcdesc}
\begin{funcdesc}{repr}{object}
Return a string containing a printable representation of an object.
This is the same value yielded by conversions (reverse quotes).
It is sometimes useful to be able to access this operation as an
ordinary function. For many types, this function makes an attempt
to return a string that would yield an object with the same value
when passed to \code{eval()}.
\end{funcdesc}
\begin{funcdesc}{round}{x\, n}
Return the floating point value \var{x} rounded to \var{n} digits
after the decimal point. If \var{n} is omitted, it defaults to zero.
The result is a floating point number. Values are rounded to the
closest multiple of 10 to the power minus \var{n}; if two multiples
are equally close, rounding is done away from 0 (so e.g.
\code{round(0.5)} is \code{1.0} and \code{round(-0.5)} is \code{-1.0}).
\end{funcdesc}
\begin{funcdesc}{setattr}{object\, name\, value}
This is the counterpart of \code{getattr}. The arguments are an
object, a string and an arbitrary value. The string must be the name
of one of the object's attributes. The function assigns the value to
the attribute, provided the object allows it. For example,
\code{setattr(\var{x}, '\var{foobar}', 123)} is equivalent to
\code{\var{x}.\var{foobar} = 123}.
\end{funcdesc}
\begin{funcdesc}{str}{object}
Return a string containing a nicely printable representation of an
object. For strings, this returns the string itself. The difference
with \code{repr(\var{object}} is that \code{str(\var{object}} does not
always attempt to return a string that is acceptable to \code{eval()};
its goal is to return a printable string.
\end{funcdesc}
\begin{funcdesc}{type}{object}
% XXXJH xref to buil-in objects here?
Return the type of an \var{object}. The return value is a type
object. There is not much you can do with type objects except compare
them to other type objects; e.g., the following checks if a variable
is a string:
\bcode\begin{verbatim}
>>> if type(x) == type(''): print 'It is a string'
\end{verbatim}\ecode
\end{funcdesc}
\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).
\section{Built-in Module \sectcode{socket}}
\bimodindex{socket}
This module provides access to the BSD {\em socket} interface.
It is available on \UNIX{} systems that support this interface.
For an introduction to socket programming (in C), see the following
papers: \emph{An Introductory 4.3BSD Interprocess Communication
Tutorial}, by Stuart Sechrest and \emph{An Advanced 4.3BSD Interprocess
Communication Tutorial}, by Samuel J. Leffler et al, both in the
\UNIX{} Programmer's Manual, Supplementary Documents 1 (sections PS1:7
and PS1:8). The \UNIX{} manual pages for the various socket-related
system calls also a valuable source of information on the details of
socket semantics.
The Python interface is a straightforward transliteration of the
\UNIX{} system call and library interface for sockets to Python's
object-oriented style: the \code{socket()} function returns a
\dfn{socket object} whose methods implement the various socket system
calls. Parameter types are somewhat higer-level than in the C
interface: as with \code{read()} and \code{write()} operations on Python
files, buffer allocation on receive operations is automatic, and
buffer length is implicit on send operations.
Socket addresses are represented as a single string for the
\code{AF_UNIX} address family and as a pair
\code{(\var{host}, \var{port})} for the \code{AF_INET} address family,
where \var{host} is a string representing
either a hostname in Internet domain notation like
\code{'daring.cwi.nl'} or an IP address like \code{'100.50.200.5'},
and \var{port} is an integral port number. Other address families are
currently not supported. The address format required by a particular
socket object is automatically selected based on the address family
specified when the socket object was created.
All errors raise exceptions. The normal exceptions for invalid
argument types and out-of-memory conditions can be raised; errors
related to socket or address semantics raise the error \code{socket.error}.
Non-blocking and asynchronous mode are not supported; see module
\code{select} for a way to do non-blocking socket I/O.
The module \code{socket} exports the following constants and functions:
\renewcommand{\indexsubitem}{(in module socket)}
\begin{excdesc}{error}
This exception is raised for socket- or address-related errors.
The accompanying value is either a string telling what went wrong or a
pair \code{(\var{errno}, \var{string})}
representing an error returned by a system
call, similar to the value accompanying \code{posix.error}.
\end{excdesc}
\begin{datadesc}{AF_UNIX}
\dataline{AF_INET}
These constants represent the address (and protocol) families,
used for the first argument to \code{socket()}.
\end{datadesc}
\begin{datadesc}{SOCK_STREAM}
\dataline{SOCK_DGRAM}
These constants represent the socket types,
used for the second argument to \code{socket()}.
(There are other types, but only \code{SOCK_STREAM} and
\code{SOCK_DGRAM} appear to be generally useful.)
\end{datadesc}
\begin{funcdesc}{gethostbyname}{hostname}
Translate a host name to IP address format. The IP address is
returned as a string, e.g., \code{'100.50.200.5'}. If the host name
is an IP address itself it is returned unchanged.
\end{funcdesc}
\begin{funcdesc}{getservbyname}{servicename\, protocolname}
Translate an Internet service name and protocol name to a port number
for that service. The protocol name should be \code{'tcp'} or
\code{'udp'}.
\end{funcdesc}
\begin{funcdesc}{socket}{family\, type\, proto}
Create a new socket using the given address family, socket type and
protocol number. The address family should be \code{AF_INET} or
\code{AF_UNIX}. The socket type should be \code{SOCK_STREAM},
\code{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants.
The protocol number is usually zero and may be omitted in that case.
\end{funcdesc}
\begin{funcdesc}{fromfd}{fd\, family\, type\, proto}
Build a socket object from an existing file descriptor (an integer as
returned by a file object's \code{fileno} method). Address family,
socket type and protocol number are as for the \code{socket} function
above. The file descriptor should refer to a socket, but this is not
checked --- subsequent operations on the object may fail if the file
descriptor is invalid. This function is rarely needed, but can be
used to get or set socket options on a socket passed to a program as
standard input or output (e.g. a server started by the \UNIX{} inet
daemon).
\end{funcdesc}
\subsection{Socket Object Methods}
\noindent
Socket objects have the following methods. Except for
\code{makefile()} these correspond to \UNIX{} system calls applicable to
sockets.
\renewcommand{\indexsubitem}{(socket method)}
\begin{funcdesc}{accept}{}
Accept a connection.
The socket must be bound to an address and listening for connections.
The return value is a pair \code{(\var{conn}, \var{address})}
where \var{conn} is a \emph{new} socket object usable to send and
receive data on the connection, and \var{address} is the address bound
to the socket on the other end of the connection.
\end{funcdesc}
\begin{funcdesc}{avail}{}
Return true (nonzero) if at least one byte of data can be received
from the socket without blocking, false (zero) if not. There is no
indication of how many bytes are available. (\strong{This function is
obsolete --- see module \code{select} for a more general solution.})
\end{funcdesc}
\begin{funcdesc}{bind}{address}
Bind the socket to an address. The socket must not already be bound.
\end{funcdesc}
\begin{funcdesc}{close}{}
Close the socket. All future operations on the socket object will fail.
The remote end will receive no more data (after queued data is flushed).
Sockets are automatically closed when they are garbage-collected.
\end{funcdesc}
\begin{funcdesc}{connect}{address}
Connect to a remote socket.
\end{funcdesc}
\begin{funcdesc}{fileno}{}
Return the socket's file descriptor (a small integer). This is useful
with \code{select}.
\end{funcdesc}
\begin{funcdesc}{getpeername}{}
Return the remote address to which the socket is connected. This is
useful to find out the port number of a remote IP socket, for instance.
\end{funcdesc}
\begin{funcdesc}{getsockname}{}
Return the socket's own address. This is useful to find out the port
number of an IP socket, for instance.
\end{funcdesc}
\begin{funcdesc}{getsockopt}{level\, optname\, buflen}
Return the value of the given socket option (see the \UNIX{} man page
{\it getsockopt}(2)). The needed symbolic constants are defined in module
SOCKET. If the optional third argument is absent, an integer option
is assumed and its integer value is returned by the function. If
\var{buflen} is present, it specifies the maximum length of the buffer used
to receive the option in, and this buffer is returned as a string.
It's up to the caller to decode the contents of the buffer (see the
optional built-in module \code{struct} for a way to decode C structures
encoded as strings).
\end{funcdesc}
\begin{funcdesc}{listen}{backlog}
Listen for connections made to the socket.
The argument (in the range 0-5) specifies the maximum number of
queued connections.
\end{funcdesc}
\begin{funcdesc}{makefile}{mode}
Return a \dfn{file object} associated with the socket.
(File objects were described earlier under Built-in Types.)
The file object references a \code{dup}ped version of the socket file
descriptor, so the file object and socket object may be closed or
garbage-collected independently.
\end{funcdesc}
\begin{funcdesc}{recv}{bufsize\, flags}
Receive data from the socket. The return value is a string representing
the data received. The maximum amount of data to be received
at once is specified by \var{bufsize}. See the \UNIX{} manual page
for the meaning of the optional argument \var{flags}; it defaults to
zero.
\end{funcdesc}
\begin{funcdesc}{recvfrom}{bufsize}
Receive data from the socket. The return value is a pair
\code{(\var{string}, \var{address})} where \var{string} is a string
representing the data received and \var{address} is the address of the
socket sending the data.
\end{funcdesc}
\begin{funcdesc}{send}{string}
Send data to the socket. The socket must be connected to a remote
socket.
\end{funcdesc}
\begin{funcdesc}{sendto}{string\, address}
Send data to the socket. The socket should not be connected to a
remote socket, since the destination socket is specified by
\code{address}.
\end{funcdesc}
\begin{funcdesc}{setsockopt}{level\, optname\, value}
Set the value of the given socket option (see the \UNIX{} man page
{\it setsockopt}(2)). The needed symbolic constants are defined in module
\code{SOCKET}. The value can be an integer or a string representing a
buffer. In the latter case it is up to the caller to ensure that the
string contains the proper bits (see the optional built-in module
\code{struct} for a way to encode C structures as strings).
\end{funcdesc}
\begin{funcdesc}{shutdown}{how}
Shut down one or both halves of the connection. If \var{how} is \code{0},
further receives are disallowed. If \var{how} is \code{1}, further sends are
disallowed. If \var{how} is \code{2}, further sends and receives are
disallowed.
\end{funcdesc}
Note that there are no methods \code{read()} or \code{write()}; use
\code{recv()} and \code{send()} without \var{flags} argument instead.
\subsection{Example}
\nodename{Socket Example}
Here are two minimal example programs using the TCP/IP protocol: a
server that echoes all data that it receives back (servicing only one
client), and a client using it. Note that a server must perform the
sequence \code{socket}, \code{bind}, \code{listen}, \code{accept}
(possibly repeating the \code{accept} to service more than one client),
while a client only needs the sequence \code{socket}, \code{connect}.
Also note that the server does not \code{send}/\code{receive} on the
socket it is listening on but on the new socket returned by
\code{accept}.
\bcode\begin{verbatim}
# Echo server program
from socket import *
HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged server
s = socket(AF_INET, SOCK_STREAM)
s.bind(HOST, PORT)
s.listen(0)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
\end{verbatim}\ecode
\bcode\begin{verbatim}
# Echo client program
from socket import *
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket(AF_INET, SOCK_STREAM)
s.connect(HOST, PORT)
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', `data`
\end{verbatim}\ecode
\chapter{STDWIN ONLY}
\section{Built-in Module \sectcode{stdwin}}
\bimodindex{stdwin}
This module defines several new object types and functions that
provide access to the functionality of the Standard Window System
Interface, STDWIN [CWI report CR-R8817].
It is available on systems to which STDWIN has been ported (which is
most systems).
It is only available if the \code{DISPLAY} environment variable is set
or an explicit \samp{-display \var{displayname}} argument is passed to
the interpreter.
Functions have names that usually resemble their C STDWIN counterparts
with the initial `w' dropped.
Points are represented by pairs of integers; rectangles
by pairs of points.
For a complete description of STDWIN please refer to the documentation
of STDWIN for C programmers (aforementioned CWI report).
\subsection{Functions Defined in Module \sectcode{stdwin}}
The following functions are defined in the \code{stdwin} module:
\renewcommand{\indexsubitem}{(in module stdwin)}
\begin{funcdesc}{open}{title}
Open a new window whose initial title is given by the string argument.
Return a window object; window object methods are described below.%
\footnote{The Python version of STDWIN does not support draw procedures; all
drawing requests are reported as draw events.}
\end{funcdesc}
\begin{funcdesc}{getevent}{}
Wait for and return the next event.
An event is returned as a triple: the first element is the event
type, a small integer; the second element is the window object to which
the event applies, or
\code{None}
if it applies to no window in particular;
the third element is type-dependent.
Names for event types and command codes are defined in the standard
module
\code{stdwinevent}.
\end{funcdesc}
\begin{funcdesc}{pollevent}{}
Return the next event, if one is immediately available.
If no event is available, return \code{()}.
\end{funcdesc}
\begin{funcdesc}{getactive}{}
Return the window that is currently active, or \code{None} if no
window is currently active. (This can be emulated by monitoring
WE_ACTIVATE and WE_DEACTIVATE events.)
\end{funcdesc}
\begin{funcdesc}{listfontnames}{pattern}
Return the list of font names in the system that match the pattern (a
string). The pattern should normally be \code{'*'}; returns all
available fonts. If the underlying window system is X11, other
patterns follow the standard X11 font selection syntax (as used e.g.
in resource definitions), i.e. the wildcard character \code{'*'}
matches any sequence of characters (including none) and \code{'?'}
matches any single character.
\end{funcdesc}
\begin{funcdesc}{setdefscrollbars}{hflag\, vflag}
Set the flags controlling whether subsequently opened windows will
have horizontal and/or vertical scroll bars.
\end{funcdesc}
\begin{funcdesc}{setdefwinpos}{h\, v}
Set the default window position for windows opened subsequently.
\end{funcdesc}
\begin{funcdesc}{setdefwinsize}{width\, height}
Set the default window size for windows opened subsequently.
\end{funcdesc}
\begin{funcdesc}{getdefscrollbars}{}
Return the flags controlling whether subsequently opened windows will
have horizontal and/or vertical scroll bars.
\end{funcdesc}
\begin{funcdesc}{getdefwinpos}{}
Return the default window position for windows opened subsequently.
\end{funcdesc}
\begin{funcdesc}{getdefwinsize}{}
Return the default window size for windows opened subsequently.
\end{funcdesc}
\begin{funcdesc}{getscrsize}{}
Return the screen size in pixels.
\end{funcdesc}
\begin{funcdesc}{getscrmm}{}
Return the screen size in millimeters.
\end{funcdesc}
\begin{funcdesc}{fetchcolor}{colorname}
Return the pixel value corresponding to the given color name.
Return the default foreground color for unknown color names.
Hint: the following code tests wheter you are on a machine that
supports more than two colors:
\bcode\begin{verbatim}
if stdwin.fetchcolor('black') <> \
stdwin.fetchcolor('red') <> \
stdwin.fetchcolor('white'):
print 'color machine'
else:
print 'monochrome machine'
\end{verbatim}\ecode
\end{funcdesc}
\begin{funcdesc}{setfgcolor}{pixel}
Set the default foreground color.
This will become the default foreground color of windows opened
subsequently, including dialogs.
\end{funcdesc}
\begin{funcdesc}{setbgcolor}{pixel}
Set the default background color.
This will become the default background color of windows opened
subsequently, including dialogs.
\end{funcdesc}
\begin{funcdesc}{getfgcolor}{}
Return the pixel value of the current default foreground color.
\end{funcdesc}
\begin{funcdesc}{getbgcolor}{}
Return the pixel value of the current default background color.
\end{funcdesc}
\begin{funcdesc}{setfont}{fontname}
Set the current default font.
This will become the default font for windows opened subsequently,
and is also used by the text measuring functions \code{textwidth},
\code{textbreak}, \code{lineheight} and \code{baseline} below.
This accepts two more optional parameters, size and style:
Size is the font size (in `points').
Style is a single character specifying the style, as follows:
\code{'b'} = bold,
\code{'i'} = italic,
\code{'o'} = bold + italic,
\code{'u'} = underline;
default style is roman.
Size and style are ignored under X11 but used on the Macintosh.
(Sorry for all this complexity --- a more uniform interface is being designed.)
\end{funcdesc}
\begin{funcdesc}{menucreate}{title}
Create a menu object referring to a global menu (a menu that appears in
all windows).
Methods of menu objects are described below.
Note: normally, menus are created locally; see the window method
\code{menucreate} below.
\strong{Warning:} the menu only appears in a window as long as the object
returned by this call exists.
\end{funcdesc}
\begin{funcdesc}{newbitmap}{width\, height}
Create a new bitmap object of the given dimensions.
Methods of bitmap objects are described below.
\end{funcdesc}
\begin{funcdesc}{fleep}{}
Cause a beep or bell (or perhaps a `visual bell' or flash, hence the
name).
\end{funcdesc}
\begin{funcdesc}{message}{string}
Display a dialog box containing the string.
The user must click OK before the function returns.
\end{funcdesc}
\begin{funcdesc}{askync}{prompt\, default}
Display a dialog that prompts the user to answer a question with yes or
no.
Return 0 for no, 1 for yes.
If the user hits the Return key, the default (which must be 0 or 1) is
returned.
If the user cancels the dialog, the
\code{KeyboardInterrupt}
exception is raised.
\end{funcdesc}
\begin{funcdesc}{askstr}{prompt\, default}
Display a dialog that prompts the user for a string.
If the user hits the Return key, the default string is returned.
If the user cancels the dialog, the
\code{KeyboardInterrupt}
exception is raised.
\end{funcdesc}
\begin{funcdesc}{askfile}{prompt\, default\, new}
Ask the user to specify a filename.
If
\var{new}
is zero it must be an existing file; otherwise, it must be a new file.
If the user cancels the dialog, the
\code{KeyboardInterrupt}
exception is raised.
\end{funcdesc}
\begin{funcdesc}{setcutbuffer}{i\, string}
Store the string in the system's cut buffer number
\var{i},
where it can be found (for pasting) by other applications.
On X11, there are 8 cut buffers (numbered 0..7).
Cut buffer number 0 is the `clipboard' on the Macintosh.
\end{funcdesc}
\begin{funcdesc}{getcutbuffer}{i}
Return the contents of the system's cut buffer number
\var{i}.
\end{funcdesc}
\begin{funcdesc}{rotatecutbuffers}{n}
On X11, rotate the 8 cut buffers by
\var{n}.
Ignored on the Macintosh.
\end{funcdesc}
\begin{funcdesc}{getselection}{i}
Return X11 selection number
\var{i.}
Selections are not cut buffers.
Selection numbers are defined in module
\code{stdwinevents}.
Selection \code{WS_PRIMARY} is the
\dfn{primary}
selection (used by
xterm,
for instance);
selection \code{WS_SECONDARY} is the
\dfn{secondary}
selection; selection \code{WS_CLIPBOARD} is the
\dfn{clipboard}
selection (used by
xclipboard).
On the Macintosh, this always returns an empty string.
\end{funcdesc}
\begin{funcdesc}{resetselection}{i}
Reset selection number
\var{i},
if this process owns it.
(See window method
\code{setselection()}).
\end{funcdesc}
\begin{funcdesc}{baseline}{}
Return the baseline of the current font (defined by STDWIN as the
vertical distance between the baseline and the top of the
characters).
\end{funcdesc}
\begin{funcdesc}{lineheight}{}
Return the total line height of the current font.
\end{funcdesc}
\begin{funcdesc}{textbreak}{str\, width}
Return the number of characters of the string that fit into a space of
\var{width}
bits wide when drawn in the curent font.
\end{funcdesc}
\begin{funcdesc}{textwidth}{str}
Return the width in bits of the string when drawn in the current font.
\end{funcdesc}
\begin{funcdesc}{connectionnumber}{}
\funcline{fileno}{}
(X11 under \UNIX{} only) Return the ``connection number'' used by the
underlying X11 implementation. (This is normally the file number of
the socket.) Both functions return the same value;
\code{connectionnumber()} is named after the corresponding function in
X11 and STDWIN, while \code{fileno()} makes it possible to use the
\code{stdwin} module as a ``file'' object parameter to
\code{select.select()}. Note that if \code{select()} implies that
input is possible on \code{stdwin}, this does not guarantee that an
event is ready --- it may be some internal communication going on
between the X server and the client library. Thus, you should call
\code{stdwin.pollevent()} until it returns \code{None} to check for
events if you don't want your program to block. Because of internal
buffering in X11, it is also possible that \code{stdwin.pollevent()}
returns an event while \code{select()} does not find \code{stdwin} to
be ready, so you should read any pending events with
\code{stdwin.pollevent()} until it returns \code{None} before entering
a blocking \code{select()} call.
\ttindex{select}
\end{funcdesc}
\subsection{Window Object Methods}
Window objects are created by \code{stdwin.open()}. They are closed
by their \code{close()} method or when they are garbage-collected.
Window objects have the following methods:
\renewcommand{\indexsubitem}{(window method)}
\begin{funcdesc}{begindrawing}{}
Return a drawing object, whose methods (described below) allow drawing
in the window.
\end{funcdesc}
\begin{funcdesc}{change}{rect}
Invalidate the given rectangle; this may cause a draw event.
\end{funcdesc}
\begin{funcdesc}{gettitle}{}
Returns the window's title string.
\end{funcdesc}
\begin{funcdesc}{getdocsize}{}
\begin{sloppypar}
Return a pair of integers giving the size of the document as set by
\code{setdocsize()}.
\end{sloppypar}
\end{funcdesc}
\begin{funcdesc}{getorigin}{}
Return a pair of integers giving the origin of the window with respect
to the document.
\end{funcdesc}
\begin{funcdesc}{gettitle}{}
Return the window's title string.
\end{funcdesc}
\begin{funcdesc}{getwinsize}{}
Return a pair of integers giving the size of the window.
\end{funcdesc}
\begin{funcdesc}{getwinpos}{}
Return a pair of integers giving the position of the window's upper
left corner (relative to the upper left corner of the screen).
\end{funcdesc}
\begin{funcdesc}{menucreate}{title}
Create a menu object referring to a local menu (a menu that appears
only in this window).
Methods of menu objects are described below.
{\bf Warning:} the menu only appears as long as the object
returned by this call exists.
\end{funcdesc}
\begin{funcdesc}{scroll}{rect\, point}
Scroll the given rectangle by the vector given by the point.
\end{funcdesc}
\begin{funcdesc}{setdocsize}{point}
Set the size of the drawing document.
\end{funcdesc}
\begin{funcdesc}{setorigin}{point}
Move the origin of the window (its upper left corner)
to the given point in the document.
\end{funcdesc}
\begin{funcdesc}{setselection}{i\, str}
Attempt to set X11 selection number
\var{i}
to the string
\var{str}.
(See stdwin method
\code{getselection()}
for the meaning of
\var{i}.)
Return true if it succeeds.
If succeeds, the window ``owns'' the selection until
(a) another applications takes ownership of the selection; or
(b) the window is deleted; or
(c) the application clears ownership by calling
\code{stdwin.resetselection(\var{i})}.
When another application takes ownership of the selection, a
\code{WE_LOST_SEL}
event is received for no particular window and with the selection number
as detail.
Ignored on the Macintosh.
\end{funcdesc}
\begin{funcdesc}{settimer}{dsecs}
Schedule a timer event for the window in
\code{\var{dsecs}/10}
seconds.
\end{funcdesc}
\begin{funcdesc}{settitle}{title}
Set the window's title string.
\end{funcdesc}
\begin{funcdesc}{setwincursor}{name}
\begin{sloppypar}
Set the window cursor to a cursor of the given name.
It raises the
\code{RuntimeError}
exception if no cursor of the given name exists.
Suitable names include
\code{'ibeam'},
\code{'arrow'},
\code{'cross'},
\code{'watch'}
and
\code{'plus'}.
On X11, there are many more (see
\file{<X11/cursorfont.h>}).
\end{sloppypar}
\end{funcdesc}
\begin{funcdesc}{setwinpos}{h\, v}
Set the the position of the window's upper left corner (relative to
the upper left corner of the screen).
\end{funcdesc}
\begin{funcdesc}{setwinsize}{width\, height}
Set the window's size.
\end{funcdesc}
\begin{funcdesc}{show}{rect}
Try to ensure that the given rectangle of the document is visible in
the window.
\end{funcdesc}
\begin{funcdesc}{textcreate}{rect}
Create a text-edit object in the document at the given rectangle.
Methods of text-edit objects are described below.
\end{funcdesc}
\begin{funcdesc}{setactive}{}
Attempt to make this window the active window. If successful, this
will generate a WE_ACTIVATE event (and a WE_DEACTIVATE event in case
another window in this application became inactive).
\end{funcdesc}
\begin{funcdesc}{close}{}
Discard the window object. It should not be used again.
\end{funcdesc}
\subsection{Drawing Object Methods}
Drawing objects are created exclusively by the window method
\code{begindrawing()}.
Only one drawing object can exist at any given time; the drawing object
must be deleted to finish drawing.
No drawing object may exist when
\code{stdwin.getevent()}
is called.
Drawing objects have the following methods:
\renewcommand{\indexsubitem}{(drawing method)}
\begin{funcdesc}{box}{rect}
Draw a box just inside a rectangle.
\end{funcdesc}
\begin{funcdesc}{circle}{center\, radius}
Draw a circle with given center point and radius.
\end{funcdesc}
\begin{funcdesc}{elarc}{center\, \(rh\, rv\)\, \(a1\, a2\)}
Draw an elliptical arc with given center point.
\code{(\var{rh}, \var{rv})}
gives the half sizes of the horizontal and vertical radii.
\code{(\var{a1}, \var{a2})}
gives the angles (in degrees) of the begin and end points.
0 degrees is at 3 o'clock, 90 degrees is at 12 o'clock.
\end{funcdesc}
\begin{funcdesc}{erase}{rect}
Erase a rectangle.
\end{funcdesc}
\begin{funcdesc}{fillcircle}{center\, radius}
Draw a filled circle with given center point and radius.
\end{funcdesc}
\begin{funcdesc}{fillelarc}{center\, \(rh\, rv\)\, \(a1\, a2\)}
Draw a filled elliptical arc; arguments as for \code{elarc}.
\end{funcdesc}
\begin{funcdesc}{fillpoly}{points}
Draw a filled polygon given by a list (or tuple) of points.
\end{funcdesc}
\begin{funcdesc}{invert}{rect}
Invert a rectangle.
\end{funcdesc}
\begin{funcdesc}{line}{p1\, p2}
Draw a line from point
\var{p1}
to
\var{p2}.
\end{funcdesc}
\begin{funcdesc}{paint}{rect}
Fill a rectangle.
\end{funcdesc}
\begin{funcdesc}{poly}{points}
Draw the lines connecting the given list (or tuple) of points.
\end{funcdesc}
\begin{funcdesc}{shade}{rect\, percent}
Fill a rectangle with a shading pattern that is about
\var{percent}
percent filled.
\end{funcdesc}
\begin{funcdesc}{text}{p\, str}
Draw a string starting at point p (the point specifies the
top left coordinate of the string).
\end{funcdesc}
\begin{funcdesc}{xorcircle}{center\, radius}
\funcline{xorelarc}{center\, \(rh\, rv\)\, \(a1\, a2\)}
\funcline{xorline}{p1\, p2}
\funcline{xorpoly}{points}
Draw a circle, an elliptical arc, a line or a polygon, respectively,
in XOR mode.
\end{funcdesc}
\begin{funcdesc}{setfgcolor}{}
\funcline{setbgcolor}{}
\funcline{getfgcolor}{}
\funcline{getbgcolor}{}
These functions are similar to the corresponding functions described
above for the
\code{stdwin}
module, but affect or return the colors currently used for drawing
instead of the global default colors.
When a drawing object is created, its colors are set to the window's
default colors, which are in turn initialized from the global default
colors when the window is created.
\end{funcdesc}
\begin{funcdesc}{setfont}{}
\funcline{baseline}{}
\funcline{lineheight}{}
\funcline{textbreak}{}
\funcline{textwidth}{}
These functions are similar to the corresponding functions described
above for the
\code{stdwin}
module, but affect or use the current drawing font instead of
the global default font.
When a drawing object is created, its font is set to the window's
default font, which is in turn initialized from the global default
font when the window is created.
\end{funcdesc}
\begin{funcdesc}{bitmap}{point\, bitmap\, mask}
Draw the \var{bitmap} with its top left corner at \var{point}.
If the optional \var{mask} argument is present, it should be either
the same object as \var{bitmap}, to draw only those bits that are set
in the bitmap, in the foreground color, or \code{None}, to draw all
bits (ones are drawn in the foreground color, zeros in the background
color).
\end{funcdesc}
\begin{funcdesc}{cliprect}{rect}
Set the ``clipping region'' to a rectangle.
The clipping region limits the effect of all drawing operations, until
it is changed again or until the drawing object is closed. When a
drawing object is created the clipping region is set to the entire
window. When an object to be drawn falls partly outside the clipping
region, the set of pixels drawn is the intersection of the clipping
region and the set of pixels that would be drawn by the same operation
in the absence of a clipping region.
clipping region
\end{funcdesc}
\begin{funcdesc}{noclip}{}
Reset the clipping region to the entire window.
\end{funcdesc}
\begin{funcdesc}{close}{}
\funcline{enddrawing}{}
Discard the drawing object. It should not be used again.
\end{funcdesc}
\subsection{Menu Object Methods}
A menu object represents a menu.
The menu is destroyed when the menu object is deleted.
The following methods are defined:
\renewcommand{\indexsubitem}{(menu method)}
\begin{funcdesc}{additem}{text\, shortcut}
Add a menu item with given text.
The shortcut must be a string of length 1, or omitted (to specify no
shortcut).
\end{funcdesc}
\begin{funcdesc}{setitem}{i\, text}
Set the text of item number
\var{i}.
\end{funcdesc}
\begin{funcdesc}{enable}{i\, flag}
Enable or disables item
\var{i}.
\end{funcdesc}
\begin{funcdesc}{check}{i\, flag}
Set or clear the
\dfn{check mark}
for item
\var{i}.
\end{funcdesc}
\begin{funcdesc}{close}{}
Discard the menu object. It should not be used again.
\end{funcdesc}
\subsection{Bitmap Object Methods}
A bitmap represents a rectangular array of bits.
The top left bit has coordinate (0, 0).
A bitmap can be drawn with the \code{bitmap} method of a drawing object.
The following methods are defined:
\renewcommand{\indexsubitem}{(bitmap method)}
\begin{funcdesc}{getsize}{}
Return a tuple representing the width and height of the bitmap.
(This returns the values that have been passed to the \code{newbitmap}
function.)
\end{funcdesc}
\begin{funcdesc}{setbit}{point\, bit}
Set the value of the bit indicated by \var{point} to \var{bit}.
\end{funcdesc}
\begin{funcdesc}{getbit}{point}
Return the value of the bit indicated by \var{point}.
\end{funcdesc}
\begin{funcdesc}{close}{}
Discard the bitmap object. It should not be used again.
\end{funcdesc}
\subsection{Text-edit Object Methods}
A text-edit object represents a text-edit block.
For semantics, see the STDWIN documentation for C programmers.
The following methods exist:
\renewcommand{\indexsubitem}{(text-edit method)}
\begin{funcdesc}{arrow}{code}
Pass an arrow event to the text-edit block.
The
\var{code}
must be one of
\code{WC_LEFT},
\code{WC_RIGHT},
\code{WC_UP}
or
\code{WC_DOWN}
(see module
\code{stdwinevents}).
\end{funcdesc}
\begin{funcdesc}{draw}{rect}
Pass a draw event to the text-edit block.
The rectangle specifies the redraw area.
\end{funcdesc}
\begin{funcdesc}{event}{type\, window\, detail}
Pass an event gotten from
\code{stdwin.getevent()}
to the text-edit block.
Return true if the event was handled.
\end{funcdesc}
\begin{funcdesc}{getfocus}{}
Return 2 integers representing the start and end positions of the
focus, usable as slice indices on the string returned by
\code{gettext()}.
\end{funcdesc}
\begin{funcdesc}{getfocustext}{}
Return the text in the focus.
\end{funcdesc}
\begin{funcdesc}{getrect}{}
Return a rectangle giving the actual position of the text-edit block.
(The bottom coordinate may differ from the initial position because
the block automatically shrinks or grows to fit.)
\end{funcdesc}
\begin{funcdesc}{gettext}{}
Return the entire text buffer.
\end{funcdesc}
\begin{funcdesc}{move}{rect}
Specify a new position for the text-edit block in the document.
\end{funcdesc}
\begin{funcdesc}{replace}{str}
Replace the text in the focus by the given string.
The new focus is an insert point at the end of the string.
\end{funcdesc}
\begin{funcdesc}{setfocus}{i\, j}
Specify the new focus.
Out-of-bounds values are silently clipped.
\end{funcdesc}
\begin{funcdesc}{settext}{str}
Replace the entire text buffer by the given string and set the focus
to \code{(0, 0)}.
\end{funcdesc}
\begin{funcdesc}{setview}{rect}
Set the view rectangle to \var{rect}. If \var{rect} is \code{None},
viewing mode is reset. In viewing mode, all output from the text-edit
object is clipped to the viewing rectangle. This may be useful to
implement your own scrolling text subwindow.
\end{funcdesc}
\begin{funcdesc}{close}{}
Discard the text-edit object. It should not be used again.
\end{funcdesc}
\subsection{Example}
\nodename{Stdwin Example}
Here is a minimal example of using STDWIN in Python.
It creates a window and draws the string ``Hello world'' in the top
left corner of the window.
The window will be correctly redrawn when covered and re-exposed.
The program quits when the close icon or menu item is requested.
\bcode\begin{verbatim}
import stdwin
from stdwinevents import *
def main():
mywin = stdwin.open('Hello')
#
while 1:
(type, win, detail) = stdwin.getevent()
if type == WE_DRAW:
draw = win.begindrawing()
draw.text((0, 0), 'Hello, world')
del draw
elif type == WE_CLOSE:
break
main()
\end{verbatim}\ecode
\section{Standard Module \sectcode{stdwinevents}}
\stmodindex{stdwinevents}
This module defines constants used by STDWIN for event types
(\code{WE_ACTIVATE} etc.), command codes (\code{WC_LEFT} etc.)
and selection types (\code{WS_PRIMARY} etc.).
Read the file for details.
Suggested usage is
\bcode\begin{verbatim}
>>> from stdwinevents import *
>>>
\end{verbatim}\ecode
\section{Standard Module \sectcode{rect}}
\stmodindex{rect}
This module contains useful operations on rectangles.
A rectangle is defined as in module
\code{stdwin}:
a pair of points, where a point is a pair of integers.
For example, the rectangle
\bcode\begin{verbatim}
(10, 20), (90, 80)
\end{verbatim}\ecode
is a rectangle whose left, top, right and bottom edges are 10, 20, 90
and 80, respectively.
Note that the positive vertical axis points down (as in
\code{stdwin}).
The module defines the following objects:
\renewcommand{\indexsubitem}{(in module rect)}
\begin{excdesc}{error}
The exception raised by functions in this module when they detect an
error.
The exception argument is a string describing the problem in more
detail.
\end{excdesc}
\begin{datadesc}{empty}
The rectangle returned when some operations return an empty result.
This makes it possible to quickly check whether a result is empty:
\bcode\begin{verbatim}
>>> import rect
>>> r1 = (10, 20), (90, 80)
>>> r2 = (0, 0), (10, 20)
>>> r3 = rect.intersect([r1, r2])
>>> if r3 is rect.empty: print 'Empty intersection'
Empty intersection
>>>
\end{verbatim}\ecode
\end{datadesc}
\begin{funcdesc}{is_empty}{r}
Returns true if the given rectangle is empty.
A rectangle
\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})}
is empty if
\iftexi
\code{\var{left} >= \var{right}} or \code{\var{top} => \var{bottom}}.
\else
$\var{left} \geq \var{right}$ or $\var{top} \geq \var{bottom}$.
%%JHXXX{\em left~$\geq$~right} or {\em top~$\leq$~bottom}.
\fi
\end{funcdesc}
\begin{funcdesc}{intersect}{list}
Returns the intersection of all rectangles in the list argument.
It may also be called with a tuple argument.
Raises
\code{rect.error}
if the list is empty.
Returns
\code{rect.empty}
if the intersection of the rectangles is empty.
\end{funcdesc}
\begin{funcdesc}{union}{list}
Returns the smallest rectangle that contains all non-empty rectangles in
the list argument.
It may also be called with a tuple argument or with two or more
rectangles as arguments.
Returns
\code{rect.empty}
if the list is empty or all its rectangles are empty.
\end{funcdesc}
\begin{funcdesc}{pointinrect}{point\, rect}
Returns true if the point is inside the rectangle.
By definition, a point
\code{(\var{h}, \var{v})}
is inside a rectangle
\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})} if
\iftexi
\code{\var{left} <= \var{h} < \var{right}} and
\code{\var{top} <= \var{v} < \var{bottom}}.
\else
$\var{left} \leq \var{h} < \var{right}$ and
$\var{top} \leq \var{v} < \var{bottom}$.
\fi
\end{funcdesc}
\begin{funcdesc}{inset}{rect\, \(dh\, dv\)}
Returns a rectangle that lies inside the
\code{rect}
argument by
\var{dh}
pixels horizontally
and
\var{dv}
pixels
vertically.
If
\var{dh}
or
\var{dv}
is negative, the result lies outside
\var{rect}.
\end{funcdesc}
\begin{funcdesc}{rect2geom}{rect}
Converts a rectangle to geometry representation:
\code{(\var{left}, \var{top}), (\var{width}, \var{height})}.
\end{funcdesc}
\begin{funcdesc}{geom2rect}{geom}
Converts a rectangle given in geometry representation back to the
standard rectangle representation
\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})}.
\end{funcdesc}
\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.)
\chapter{SUNOS ONLY}
The modules described in this chapter provide interfaces to features
that are unique to the SunOS operating system (versions 4 and 5; the
latter is also known as SOLARIS version 2).
\section{Built-in module \sectcode{sunaudiodev}}
\bimodindex{sunaudiodev}
This module allows you to access the sun audio interface. The sun
audio hardware is capable of recording and playing back audio data
in U-LAW format with a sample rate of 8K per second. A full
description can be gotten with \samp{man audio}.
The module defines the following variables and functions:
\renewcommand{\indexsubitem}{(in module sunaudiodev)}
\begin{excdesc}{error}
This exception is raised on all errors. The argument is a string
describing what went wrong.
\end{excdesc}
\begin{funcdesc}{open}{mode}
This function opens the audio device and returns a sun audio device
object. This object can then be used to do I/O on. The \var{mode} parameter
is one of \code{'r'} for record-only access, \code{'w'} for play-only
access, \code{'rw'} for both and \code{'control'} for access to the
control device. Since only one process is allowed to have the recorder
or player open at the same time it is a good idea to open the device
only for the activity needed. See the audio manpage for details.
\end{funcdesc}
\subsection{Audio device object methods}
The audio device objects are returned by \code{open} define the
following methods (except \code{control} objects which only provide
getinfo, setinfo and drain):
\renewcommand{\indexsubitem}{(audio device method)}
\begin{funcdesc}{close}{}
This method explicitly closes the device. It is useful in situations
where deleting the object does not immediately close it since there
are other references to it. A closed device should not be used again.
\end{funcdesc}
\begin{funcdesc}{drain}{}
This method waits until all pending output is processed and then returns.
Calling this method is often not necessary: destroying the object will
automatically close the audio device and this will do an implicit drain.
\end{funcdesc}
\begin{funcdesc}{flush}{}
This method discards all pending output. It can be used avoid the
slow response to a user's stop request (due to buffering of up to one
second of sound).
\end{funcdesc}
\begin{funcdesc}{getinfo}{}
This method retrieves status information like input and output volume,
etc. and returns it in the form of
an audio status object. This object has no methods but it contains a
number of attributes describing the current device status. The names
and meanings of the attributes are described in
\file{/usr/include/sun/audioio.h} and in the audio man page. Member names
are slightly different from their C counterparts: a status object is
only a single structure. Members of the \code{play} substructure have
\samp{o_} prepended to their name and members of the \code{record}
structure have \samp{i_}. So, the C member \code{play.sample_rate} is
accessed as \code{o_sample_rate}, \code{record.gain} as \code{i_gain}
and \code{monitor_gain} plainly as \code{monitor_gain}.
\end{funcdesc}
\begin{funcdesc}{ibufcount}{}
This method returns the number of samples that are buffered on the
recording side, i.e.
the program will not block on a \code{read} call of so many samples.
\end{funcdesc}
\begin{funcdesc}{obufcount}{}
This method returns the number of samples buffered on the playback
side. Unfortunately, this number cannot be used to determine a number
of samples that can be written without blocking since the kernel
output queue length seems to be variable.
\end{funcdesc}
\begin{funcdesc}{read}{size}
This method reads \var{size} samples from the audio input and returns
them as a python string. The function blocks until enough data is available.
\end{funcdesc}
\begin{funcdesc}{setinfo}{status}
This method sets the audio device status parameters. The \var{status}
parameter is an device status object as returned by \code{getinfo} and
possibly modified by the program.
\end{funcdesc}
\begin{funcdesc}{write}{samples}
Write is passed a python string containing audio samples to be played.
If there is enough buffer space free it will immedeately return,
otherwise it will block.
\end{funcdesc}
There is a companion module, \code{SUNAUDIODEV}, which defines useful
symbolic constants like \code{MIN_GAIN}, \code{MAX_GAIN},
\code{SPEAKER}, etc. The names of
the constants are the same names as used in the C include file
\file{<sun/audioio.h>}, with the leading string \samp{AUDIO_} stripped.
Useability of the control device is limited at the moment, since there
is no way to use the 'wait for something to happen' feature the device
provides. This is because that feature makes heavy use of signals, and
these do not map too well onto Python.
\section{Built-in Module \sectcode{sys}}
\bimodindex{sys}
This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
It is always available.
\renewcommand{\indexsubitem}{(in module sys)}
\begin{datadesc}{argv}
The list of command line arguments passed to a Python script.
\code{sys.argv[0]} is the script name.
If no script name was passed to the Python interpreter,
\code{sys.argv} is empty.
\end{datadesc}
\begin{datadesc}{builtin_module_names}
A list of strings giving the names of all modules that are compiled
into this Python interpreter. (This information is not available in
any other way --- \code{sys.modules.keys()} only lists the imported
modules.)
\end{datadesc}
\begin{datadesc}{exc_type}
\dataline{exc_value}
\dataline{exc_traceback}
These three variables are not always defined; they are set when an
exception handler (an \code{except} clause of a \code{try} statement) is
invoked. Their meaning is: \code{exc_type} gets the exception type of
the exception being handled; \code{exc_value} gets the exception
parameter (its \dfn{associated value} or the second argument to
\code{raise}); \code{exc_traceback} gets a traceback object which
encapsulates the call stack at the point where the exception
originally occurred.
\end{datadesc}
\begin{funcdesc}{exit}{n}
Exit from Python with numeric exit status \var{n}. This is
implemented by raising the \code{SystemExit} exception, so cleanup
actions specified by \code{finally} clauses of \code{try} statements
are honored, and it is possible to catch the exit attempt at an outer
level.
\end{funcdesc}
\begin{datadesc}{exitfunc}
This value is not actually defined by the module, but can be set by
the user (or by a program) to specify a clean-up action at program
exit. When set, it should be a parameterless function. This function
will be called when the interpreter exits in any way (but not when a
fatal error occurs: in that case the interpreter's internal state
cannot be trusted).
\end{datadesc}
\begin{datadesc}{last_type}
\dataline{last_value}
\dataline{last_traceback}
These three variables are not always defined; they are set when an
exception is not handled and the interpreter prints an error message
and a stack traceback. Their intended use is to allow an interactive
user to import a debugger module and engage in post-mortem debugging
without having to re-execute the command that cause the error (which
may be hard to reproduce). The meaning of the variables is the same
as that of \code{exc_type}, \code{exc_value} and \code{exc_tracaback},
respectively.
\end{datadesc}
\begin{datadesc}{modules}
Gives the list of modules that have already been loaded.
This can be manipulated to force reloading of modules and other tricks.
\end{datadesc}
\begin{datadesc}{path}
A list of strings that specifies the search path for modules.
Initialized from the environment variable \code{PYTHONPATH}, or an
installation-dependent default.
\end{datadesc}
\begin{datadesc}{ps1}
\dataline{ps2}
Strings specifying the primary and secondary prompt of the
interpreter. These are only defined if the interpreter is in
interactive mode. Their initial values in this case are
\code{'>>> '} and \code{'... '}.
\end{datadesc}
\begin{funcdesc}{settrace}{tracefunc}
Set the system's trace function, which allows you to implement a
Python source code debugger in Python. The standard modules
\code{pdb} and \code{wdb} are such debuggers; the difference is that
\code{wdb} uses windows and needs STDWIN, while \code{pdb} has a
line-oriented interface not unlike dbx. See the file \file{pdb.doc}
in the Python library source directory for more documentation (both
about \code{pdb} and \code{sys.trace}).
\end{funcdesc}
\ttindex{pdb}
\ttindex{wdb}
\index{trace function}
\begin{funcdesc}{setprofile}{profilefunc}
Set the system's profile function, which allows you to implement a
Python source code profiler in Python. The system's profile function
is called similarly to the system's trace function (see
\code{sys.settrace}), but it isn't called for each executed line of
code (only on call and return and when an exception occurs). Also,
its return value is not used, so it can just return \code{None}.
\end{funcdesc}
\index{profile function}
\begin{datadesc}{stdin}
\dataline{stdout}
\dataline{stderr}
File objects corresponding to the interpreter's standard input,
output and error streams. \code{sys.stdin} is used for all
interpreter input except for scripts but including calls to
\code{input()} and \code{raw_input()}. \code{sys.stdout} is used
for the output of \code{print} and expression statements and for the
prompts of \code{input()} and \code{raw_input()}. The interpreter's
own prompts and (almost all of) its error messages go to
\code{sys.stderr}. \code{sys.stdout} and \code{sys.stderr} needn't
be built-in file objects: any object is acceptable as long as it has
a \code{write} method that takes a string argument.
\end{datadesc}
\begin{datadesc}{tracebacklimit}
When this variable is set to an integer value, it determines the
maximum number of levels of traceback information printed when an
unhandled exception occurs. The default is 1000. When set to 0 or
less, all traceback information is suppressed and only the exception
type and value are printed.
\end{datadesc}
\section{Built-in Module \sectcode{thread}}
\bimodindex{thread}
This module provides low-level primitives for working with multiple
threads (a.k.a. \dfn{light-weight processes} or \dfn{tasks}) --- multiple
threads of control sharing their global data space. For
synchronization, simple locks (a.k.a. \dfn{mutexes} or \dfn{binary
semaphores}) are provided.
The module is optional and supported on SGI and Sun Sparc systems only.
It defines the following constant and functions:
\renewcommand{\indexsubitem}{(in module thread)}
\begin{excdesc}{error}
Raised on thread-specific errors.
\end{excdesc}
\begin{funcdesc}{start_new_thread}{func\, arg}
Start a new thread. The thread executes the function \var{func}
with the argument list \var{arg} (which must be a tuple). When the
function returns, the thread silently exits. When the function raises
terminates with an unhandled exception, a stack trace is printed and
then the thread exits (but other threads continue to run).
\end{funcdesc}
\begin{funcdesc}{exit_thread}{}
Exit the current thread silently. Other threads continue to run.
\strong{Caveat:} code in pending \code{finally} clauses is not executed.
\end{funcdesc}
\begin{funcdesc}{exit_prog}{status}
Exit all threads and report the value of the integer argument
\var{status} as the exit status of the entire program.
\strong{Caveat:} code in pending \code{finally} clauses, in this thread
or in other threads, is not executed.
\end{funcdesc}
\begin{funcdesc}{allocate_lock}{}
Return a new lock object. Methods of locks are described below. The
lock is initially unlocked.
\end{funcdesc}
Lock objects have the following methods:
\renewcommand{\indexsubitem}{(lock method)}
\begin{funcdesc}{acquire}{waitflag}
Without the optional argument, this method acquires the lock
unconditionally, if necessary waiting until it is released by another
thread (only one thread at a time can acquire a lock --- that's their
reason for existence), and returns \code{None}. If the integer
\var{waitflag} argument is present, the action depends on its value:
if it is zero, the lock is only acquired if it can be acquired
immediately without waiting, while if it is nonzero, the lock is
acquired unconditionally as before. If an argument is present, the
return value is 1 if the lock is acquired successfully, 0 if not.
\end{funcdesc}
\begin{funcdesc}{release}{}
Releases the lock. The lock must have been acquired earlier, but not
necessarily by the same thread.
\end{funcdesc}
\begin{funcdesc}{locked}{}
Return the status of the lock: 1 if it has been acquired by some
thread, 0 if not.
\end{funcdesc}
{\bf Caveats:}
\begin{itemize}
\item
Threads interact strangely with interrupts: the
\code{KeyboardInterrupt} exception will be received by an arbitrary
thread.
\item
Calling \code{sys.exit(\var{status})} or executing
\code{raise SystemExit, \var{status}} is almost equivalent to calling
\code{thread.exit_prog(\var{status})}, except that the former ways of
exiting the entire program do honor \code{finally} clauses in the
current thread (but not in other threads).
\item
Not all built-in functions that may block waiting for I/O allow other
threads to run, although the most popular ones (\code{sleep},
\code{read}, \code{select}) work as expected.
\end{itemize}
\section{Built-in Module \sectcode{time}}
\bimodindex{time}
This module provides various time-related functions.
It is always available. (On some systems, not all functions may
exist; e.g. the ``milli'' variants can't always be implemented.)
An explanation of some terminology and conventions is in order.
\begin{itemize}
\item
The ``epoch'' is the point where the time starts. On January 1st that
year, at 0 hours, the ``time since the epoch'' is zero. For UNIX, the
epoch is 1970. To find out what the epoch is, look at the first
element of \code{gmtime(0)}.
\item
UTC is Coordinated Universal Time (formerly known as Greenwich Mean
Time). The acronym UTC is not a mistake but a compromise between
English and French.
\item
DST is Daylight Saving Time, an adjustment of the timezone by
(usually) one hour during part of the year. DST rules are magic
(determined by local law) and can change from year to year. The C
library has a table containing the local rules (often it is read from
a system file for flexibility) and is the only source of True Wisdom
in this respect.
\item
The precision of the various real-time functions may be less than
suggested by the units in which their value or argument is expressed.
E.g. on most UNIX systems, the clock ``ticks'' only every 1/50th or
1/100th of a second, and on the Mac, it ticks 60 times a second.
\end{itemize}
Functions and data items are:
\renewcommand{\indexsubitem}{(in module time)}
\begin{datadesc}{altzone}
The offset of the local DST timezone, in seconds west of the 0th
meridian, if one is defined. Only use this if \code{daylight} is
nonzero.
\end{datadesc}
\begin{funcdesc}{asctime}{tuple}
Convert a tuple representing a time as returned by \code{gmtime()} or
\code{localtime()} to a 24-character string of the following form:
\code{'Sun Jun 20 23:21:05 1993'}. Note: unlike the C function of
the same name, there is no trailing newline.
\end{funcdesc}
\begin{funcdesc}{ctime}{secs}
Convert a time expressed in seconds since the epoch to a string
representing local time. \code{ctime(t)} is equivalent to
\code{asctime(localtime(t))}.
\end{funcdesc}
\begin{datadesc}{daylight}
Nonzero if a DST timezone is defined.
\end{datadesc}
\begin{funcdesc}{gmtime}{secs}
Convert a time expressed in seconds since the epoch to a tuple of 9
integers, in UTC: year (e.g. 1993), month (1-12), day (1-31), hour
(0-23), minute (0-59), second (0-59), weekday (0-6, monday is 0),
julian day (1-366), dst flag (always zero). Fractions of a second are
ignored. Note subtle differences with the C function of this name.
\end{funcdesc}
\begin{funcdesc}{localtime}{secs}
Like \code{gmtime} but converts to local time. The dst flag is set
to 1 when DST applies to the given time.
\end{funcdesc}
\begin{funcdesc}{millisleep}{msecs}
Suspend execution for the given number of milliseconds. (Obsolete,
you can now use use \code{sleep} with a floating point argument.)
\end{funcdesc}
\begin{funcdesc}{millitimer}{}
Return the number of milliseconds of real time elapsed since some
point in the past that is fixed per execution of the python
interpreter (but may change in each following run). The return value
may be negative, and it may wrap around.
\end{funcdesc}
\begin{funcdesc}{mktime}{tuple}
This is the inverse function of \code{localtime}. Its argument is the
full 9-tuple (since the dst flag is needed). It returns an integer.
\end{funcdesc}
\begin{funcdesc}{sleep}{secs}
Suspend execution for the given number of seconds. The argument may
be a floating point number to indicate a more precise sleep time.
\end{funcdesc}
\begin{funcdesc}{time}{}
Return the time as a floating point number expressed in seconds since
the epoch, in UTC. Note that even though the time is always returned
as a floating point number, not all systems provide time with a better
precision than 1 second. An alternative for measuring precise
intervals is \code{millitimer}.
\end{funcdesc}
\begin{datadesc}{timezone}
The offset of the local (non-DST) timezone, in seconds west of the 0th
meridian (i.e. negative in most of Western Europe, positive in the US,
zero in the UK).
\end{datadesc}
\begin{datadesc}{tzname}
A tuple of two strings: the first is the name of the local non-DST
timezone, the second is the name of the local DST timezone. If no DST
timezone is defined, the second string should not be used.
\end{datadesc}
\section{Built-in Types}
The following sections describe the standard types that are built into
the interpreter. These are the numeric types, sequence types, and
several others, including types themselves. There is no explicit
Boolean type; use integers instead.
\indexii{built-in}{types}
\indexii{Boolean}{type}
Some operations are supported by several object types; in particular,
all objects can be compared, tested for truth value, and converted to
a string (with the \code{`{\rm \ldots}`} notation). The latter conversion is
implicitly used when an object is written by the \code{print} statement.
\stindex{print}
\subsection{Truth Value Testing}
Any object can be tested for truth value, for use in an \code{if} or
\code{while} condition or as operand of the Boolean operations below.
The following values are false:
\stindex{if}
\stindex{while}
\indexii{truth}{value}
\indexii{Boolean}{operations}
\index{false}
\begin{itemize}
\renewcommand{\indexsubitem}{(Built-in object)}
\item \code{None}
\ttindex{None}
\item zero of any numeric type, e.g., \code{0}, \code{0L}, \code{0.0}.
\item any empty sequence, e.g., \code{''}, \code{()}, \code{[]}.
\item any empty mapping, e.g., \code{\{\}}.
\end{itemize}
\emph{All} other values are true --- so objects of many types are
always true.
\index{true}
\subsection{Boolean Operations}
These are the Boolean operations:
\indexii{Boolean}{operations}
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{\var{x} or \var{y}}{if \var{x} is false, then \var{y}, else \var{x}}{(1)}
\lineiii{\var{x} and \var{y}}{if \var{x} is false, then \var{x}, else \var{y}}{(1)}
\lineiii{not \var{x}}{if \var{x} is false, then \code{1}, else \code{0}}{}
\end{tableiii}
\opindex{and}
\opindex{or}
\opindex{not}
\noindent
Notes:
\begin{description}
\item[(1)]
These only evaluate their second argument if needed for their outcome.
\end{description}
\subsection{Comparisons}
Comparison operations are supported by all objects:
\begin{tableiii}{|c|l|c|}{code}{Operation}{Meaning}{Notes}
\lineiii{<}{strictly less than}{}
\lineiii{<=}{less than or equal}{}
\lineiii{>}{strictly greater than}{}
\lineiii{>=}{greater than or equal}{}
\lineiii{==}{equal}{}
\lineiii{<>}{not equal}{(1)}
\lineiii{!=}{not equal}{(1)}
\lineiii{is}{object identity}{}
\lineiii{is not}{negated object identity}{}
\end{tableiii}
\indexii{operator}{comparison}
\opindex{==} % XXX *All* others have funny characters < ! >
\opindex{is}
\opindex{is not}
\noindent
Notes:
\begin{description}
\item[(1)]
\code{<>} and \code{!=} are alternate spellings for the same operator.
(I couldn't choose between \ABC{} and \C{}! :-)
\indexii{\ABC{}}{language}
\indexii{\C{}}{language}
\end{description}
Objects of different types, except different numeric types, never
compare equal; such objects are ordered consistently but arbitrarily
(so that sorting a heterogeneous array yields a consistent result).
Furthermore, some types (e.g., windows) support only a degenerate
notion of comparison where any two objects of that type are unequal.
Again, such objects are ordered arbitrarily but consistently.
\indexii{types}{numeric}
\indexii{objects}{comparing}
(Implementation note: objects of different types except numbers are
ordered by their type names; objects of the same types that don't
support proper comparison are ordered by their address.)
Two more operations with the same syntactic priority, \code{in} and
\code{not in}, are supported only by sequence types (below).
\opindex{in}
\opindex{not in}
\subsection{Numeric Types}
There are three numeric types: \dfn{plain integers}, \dfn{long integers}, and
\dfn{floating point numbers}. Plain integers (also just called \dfn{integers})
are implemented using \code{long} in \C{}, which gives them at least 32
bits of precision. Long integers have unlimited precision. Floating
point numbers are implemented using \code{double} in \C{}. All bets on
their precision are off unless you happen to know the machine you are
working with.
\indexii{numeric}{types}
\indexii{integer}{types}
\indexii{integer}{type}
\indexiii{long}{integer}{type}
\indexii{floating point}{type}
\indexii{\C{}}{language}
Numbers are created by numeric literals or as the result of built-in
functions and operators. Unadorned integer literals (including hex
and octal numbers) yield plain integers. Integer literals with an \samp{L}
or \samp{l} suffix yield long integers
(\samp{L} is preferred because \code{1l} looks too much like eleven!).
Numeric literals containing a decimal point or an exponent sign yield
floating point numbers.
\indexii{numeric}{literals}
\indexii{integer}{literals}
\indexiii{long}{integer}{literals}
\indexii{floating point}{literals}
\indexii{hexadecimal}{literals}
\indexii{octal}{literals}
Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
``smaller'' type is converted to that of the other, where plain
integer is smaller than long integer is smaller than floating point.
Comparisons between numbers of mixed type use the same rule.%
\footnote{As a consequence, the list \code{[1, 2]} is considered equal
to \code{[1.0, 2.0]}, and similar for tuples.}
The functions \code{int()}, \code{long()} and \code{float()} can be used
to coerce numbers to a specific type.
\index{arithmetic}
\bifuncindex{int}
\bifuncindex{long}
\bifuncindex{float}
All numeric types support the following operations:
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{abs(\var{x})}{absolute value of \var{x}}{}
\lineiii{int(\var{x})}{\var{x} converted to integer}{(1)}
\lineiii{long(\var{x})}{\var{x} converted to long integer}{(1)}
\lineiii{float(\var{x})}{\var{x} converted to floating point}{}
\lineiii{-\var{x}}{\var{x} negated}{}
\lineiii{+\var{x}}{\var{x} unchanged}{}
\lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{}
\lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{}
\lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{}
\lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(2)}
\lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{}
\lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} / \var{y}, \var{x} \%{} \var{y})}}{(3)}
\lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{}
\end{tableiii}
\indexiii{operations on}{numeric}{types}
\noindent
Notes:
\begin{description}
\item[(1)]
Conversion from floating point to (long or plain) integer may round or
% XXXJH xref here
truncate as in \C{}; see functions \code{floor} and \code{ceil} in module
\code{math} for well-defined conversions.
\indexii{numeric}{conversions}
\ttindex{math}
\indexii{\C{}}{language}
\item[(2)]
For (plain or long) integer division, the result is an integer; it
always truncates towards zero.
% XXXJH integer division is better defined nowadays
\indexii{integer}{division}
\indexiii{long}{integer}{division}
\item[(3)]
See the section on built-in functions for an exact definition.
\end{description}
% XXXJH exceptions: overflow (when? what operations?) zerodivision
\subsubsection{Bit-string Operations on Integer Types.}
Plain and long integer types support additional operations that make
sense only for bit-strings. Negative numbers are treated as their 2's
complement value:
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{\~\var{x}}{the bits of \var{x} inverted}{}
\lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{}
\lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{}
\lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{}
\lineiii{\var{x} << \var{n}}{\var{x} shifted left by \var{n} bits}{}
\lineiii{\var{x} >> \var{n}}{\var{x} shifted right by \var{n} bits}{}
\end{tableiii}
% XXXJH what's `left'? `right'? maybe better use lsb or msb or something
\indexiii{operations on}{integer}{types}
\indexii{bit-string}{operations}
\indexii{shifting}{operations}
\indexii{masking}{operations}
\subsection{Sequence Types}
There are three sequence types: strings, lists and tuples.
Strings literals are written in single quotes: \code{'xyzzy'}.
Lists are constructed with square brackets,
separating items with commas:
\code{[a, b, c]}.
Tuples are constructed by the comma operator
(not within square brackets), with or without enclosing parentheses,
but an empty tuple must have the enclosing parentheses, e.g.,
\code{a, b, c} or \code{()}. A single item tuple must have a trailing comma,
e.g., \code{(d,)}.
\indexii{sequence}{types}
\indexii{string}{type}
\indexii{tuple}{type}
\indexii{list}{type}
Sequence types support the following operations (\var{s} and \var{t} are
sequences of the same type; \var{n}, \var{i} and \var{j} are integers):
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{len(\var{s})}{length of \var{s}}{}
\lineiii{min(\var{s})}{smallest item of \var{s}}{}
\lineiii{max(\var{s})}{largest item of \var{s}}{}
\lineiii{\var{x} in \var{s}}{\code{1} if an item of \var{s} is equal to \var{x}, else \code{0}}{}
\lineiii{\var{x} not in \var{s}}{\code{0} if an item of \var{s} is equal to \var{x}, else \code{1}}{}
\lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{}
\lineiii{\var{s} * \var{n}{\rm ,} \var{n} * \var{s}}{\var{n} copies of \var{s} concatenated}{}
\lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(1)}
\lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(1), (2)}
\end{tableiii}
\indexiii{operations on}{sequence}{types}
\bifuncindex{len}
\bifuncindex{min}
\bifuncindex{max}
\indexii{concatenation}{operation}
\indexii{repetition}{operation}
\indexii{subscript}{operation}
\indexii{slice}{operation}
\opindex{in}
\opindex{not in}
\noindent
Notes:
% XXXJH all TeX-math expressions replaced by python-syntax expressions
\begin{description}
\item[(1)] If \var{i} or \var{j} is negative, the index is relative to
the end of the string, i.e., \code{len(\var{s}) + \var{i}} or
\code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is
still \code{0}.
\item[(2)] The slice of \var{s} from \var{i} to \var{j} is defined as
the sequence of items with index \var{k} such that \code{\var{i} <=
\var{k} < \var{j}}. If \var{i} or \var{j} is greater than
\code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted,
use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If
\var{i} is greater than or equal to \var{j}, the slice is empty.
\end{description}
\subsubsection{More String Operations.}
String objects have one unique built-in operation: the \code{\%}
operator (modulo) with a string left argument interprets this string
as a C sprintf format string to be applied to the right argument, and
returns the string resulting from this formatting operation.
Unless the format string requires exactly one argument, the right
argument should be a tuple of the correct size. The following format
characters are understood: \%, c, s, i, d, u, o, x, X, e, E, f, g, G.
Width and precision may be a * to specify that an integer argument
specifies the actual width or precision. The flag characters -, +,
blank, \# and 0 are understood. The size specifiers h, l or L may be
present but are ignored. The ANSI features \code{\%p} and \code{\%n}
are not supported. Since Python strings have an explicit length,
\code{\%s} conversions don't assume that \code{'\\0'} is the end of
the string.
For safety reasons, huge floating point precisions are truncated;
\code{\%f} conversions for huge numbers are replaced by
\code{\%g} conversions. All other errors raise exceptions.
Additional string operations are defined in standard module
\code{string} and in built-in module \code{regex}.
\index{string}
\index{regex}
\subsubsection{Mutable Sequence Types.}
List objects support additional operations that allow in-place
modification of the object.
These operations would be supported by other mutable sequence types
(when added to the language) as well.
Strings and tuples are immutable sequence types and such objects cannot
be modified once created.
The following operations are defined on mutable sequence types (where
\var{x} is an arbitrary object):
\indexiii{mutable}{sequence}{types}
\indexii{list}{type}
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{\var{s}[\var{i}] = \var{x}}
{item \var{i} of \var{s} is replaced by \var{x}}{}
\lineiii{\var{s}[\var{i}:\var{j}] = \var{t}}
{slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{}
\lineiii{del \var{s}[\var{i}:\var{j}]}
{same as \code{\var{s}[\var{i}:\var{j}] = []}}{}
\lineiii{\var{s}.append(\var{x})}
{same as \code{\var{s}[len(\var{x}):len(\var{x})] = [\var{x}]}}{}
\lineiii{\var{s}.count(\var{x})}
{return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{}
\lineiii{\var{s}.index(\var{x})}
{return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(1)}
\lineiii{\var{s}.insert(\var{i}, \var{x})}
{same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]}}{}
\lineiii{\var{s}.remove(\var{x})}
{same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(1)}
\lineiii{\var{s}.reverse()}
{reverses the items of \var{s} in place}{}
\lineiii{\var{s}.sort()}
{permutes the items of \var{s} to satisfy
\code{\var{s}[\var{i}] <= \var{s}[\var{j}]},
for \code{\var{i} < \var{j}}}{(2)}
\end{tableiii}
\indexiv{operations on}{mutable}{sequence}{types}
\indexiii{operations on}{sequence}{types}
\indexiii{operations on}{list}{type}
\indexii{subscript}{assignment}
\indexii{slice}{assignment}
\stindex{del}
\renewcommand{\indexsubitem}{(list method)}
\ttindex{append}
\ttindex{count}
\ttindex{index}
\ttindex{insert}
\ttindex{remove}
\ttindex{reverse}
\ttindex{sort}
\noindent
Notes:
\begin{description}
\item[(1)] Raises an exception when \var{x} is not found in \var{s}.
\item[(2)] The \code{sort()} method takes an optional argument
specifying a comparison function of two arguments (list items) which
should return \code{-1}, \code{0} or \code{1} depending on whether the
first argument is considered smaller than, equal to, or larger than the
second argument. Note that this slows the sorting process down
considerably; e.g. to sort an array in reverse order it is much faster
to use calls to \code{sort()} and \code{reverse()} than to use
\code{sort()} with a comparison function that reverses the ordering of
the elements.
\end{description}
\subsection{Mapping Types}
A \dfn{mapping} object maps values of one type (the key type) to
arbitrary objects. Mappings are mutable objects. There is currently
only one mapping type, the \dfn{dictionary}. A dictionary's keys are
almost arbitrary values. The only types of values not acceptable as
keys are values containing lists or dictionaries or other mutable
types that are compared by value rather than by object identity.
Numeric types used for keys obey the normal rules for numeric
comparison: if two numbers compare equal (e.g. 1 and 1.0) then they
can be used interchangeably to index the same dictionary entry.
\indexii{mapping}{types}
\indexii{dictionary}{type}
Dictionaries are created by placing a comma-separated list of
\code{\var{key}: \var{value}} pairs within braces, for example:
\code{\{'jack': 4098, 'sjoerd: 4127\}} or
\code{\{4098: 'jack', 4127: 'sjoerd\}}.
The following operations are defined on mappings (where \var{a} is a
mapping, \var{k} is a key and \var{x} is an arbitrary object):
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{len(\var{a})}{the number of items in \var{a}}{}
\lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)}
\lineiii{\var{a}[\var{k}] = \var{x}}{set \code{\var{a}[\var{k}]} to \var{x}}{}
\lineiii{del \var{a}[\var{k}]}{remove \code{\var{a}[\var{k}]} from \var{a}}{(1)}
\lineiii{\var{a}.items()}{a copy of \var{a}'s list of (key, item) pairs}{(2)}
\lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(2)}
\lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(2)}
\lineiii{\var{a}.has_key(\var{k})}{\code{1} if \var{a} has a key \var{k}, else \code{0}}{}
\end{tableiii}
\indexiii{operations on}{mapping}{types}
\indexiii{operations on}{dictionary}{type}
\stindex{del}
\bifuncindex{len}
\renewcommand{\indexsubitem}{(dictionary method)}
\ttindex{keys}
\ttindex{has_key}
% XXXJH some lines above, you talk about `true', elsewhere you
% explicitely states \code{0} or \code{1}.
\noindent
Notes:
\begin{description}
\item[(1)] Raises an exception if \var{k} is not in the map.
\item[(2)] Keys and values are listed in random order, but at any
moment the ordering of the \code{keys()}, \code{values()} and
\code{items()} lists is the consistent with each other.
\end{description}
\subsection{Other Built-in Types}
The interpreter supports several other kinds of objects.
Most of these support only one or two operations.
\subsubsection{Modules.}
The only special operation on a module is attribute access:
\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name} accesses
a name defined in \var{m}'s symbol table. Module attributes can be
assigned to. (Note that the \code{import} statement is not, strictly
spoken, an operation on a module object; \code{import \var{foo}} does not
require a module object named \var{foo} to exist, rather it requires
an (external) \emph{definition} for a module named \var{foo}
somewhere.)
A special member of every module is \code{__dict__}.
This is the dictionary containing the module's symbol table.
Modifying this dictionary will actually change the module's symbol
table, but direct assignment to the \code{__dict__} attribute is not
possible (i.e., you can write \code{\var{m}.__dict__['a'] = 1}, which
defines \code{\var{m}.a} to be \code{1}, but you can't write \code{\var{m}.__dict__ = \{\}}.
Modules are written like this: \code{<module 'sys'>}.
\subsubsection{Classes and Class Instances.}
% XXXJH cross ref here
(See the Python Reference Manual for these.)
\subsubsection{Functions.}
Function objects are created by function definitions. The only
operation on a function object is to call it:
\code{\var{func}(\var{argument-list})}.
There are really two flavors of function objects: built-in functions
and user-defined functions. Both support the same operation (to call
the function), but the implementation is different, hence the
different object types.
The implementation adds two special read-only attributes:
\code{\var{f}.func_code} is a function's \dfn{code object} (see below) and
\code{\var{f}.func_globals} is the dictionary used as the function's
global name space (this is the same as \code{\var{m}.__dict__} where
\var{m} is the module in which the function \var{f} was defined).
\subsubsection{Methods.}
Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods (such as \code{append()} on
lists) and class instance methods. Built-in methods are described
with the types that support them.
The implementation adds two special read-only attributes to class
instance methods: \code{\var{m}.im_self} is the object whose method this
is, and \code{\var{m}.im_func} is the function implementing the method.
Calling \code{\var{m}(\var{arg-1}, \var{arg-2}, {\rm \ldots},
\var{arg-n})} is completely equivalent to calling
\code{\var{m}.im_func(\var{m}.im_self, \var{arg-1}, \var{arg-2}, {\rm
\ldots}, \var{arg-n})}.
(See the Python Reference Manual for more info.)
\subsubsection{Type Objects.}
Type objects represent the various object types. An object's type is
% XXXJH xref here
accessed by the built-in function \code{type()}. There are no special
operations on types.
Types are written like this: \code{<type 'int'>}.
\subsubsection{The Null Object.}
This object is returned by functions that don't explicitly return a
value. It supports no special operations. There is exactly one null
object, named \code{None} (a built-in name).
It is written as \code{None}.
\subsubsection{File Objects.}
File objects are implemented using \C{}'s \code{stdio} package and can be
% XXXJH xref here
created with the built-in function \code{open()} described under
Built-in Functions below.
When a file operation fails for an I/O-related reason, the exception
\code{IOError} is raised. This includes situations where the
operation is not defined for some reason, like \code{seek()} on a tty
device or writing a file opened for reading.
Files have the following methods:
\renewcommand{\indexsubitem}{(file method)}
\begin{funcdesc}{close}{}
Close the file. A closed file cannot be read or written anymore.
\end{funcdesc}
\begin{funcdesc}{flush}{}
Flush the internal buffer, like \code{stdio}'s \code{fflush()}.
\end{funcdesc}
\begin{funcdesc}{isatty}{}
Return \code{1} if the file is connected to a tty(-like) device, else
\code{0}.
\end{funcdesc}
\begin{funcdesc}{read}{size}
Read at most \var{size} bytes from the file (less if the read hits
\EOF{} or no more data is immediately available on a pipe, tty or
similar device). If the \var{size} argument is omitted, read all
data until \EOF{} is reached. The bytes are returned as a string
object. An empty string is returned when \EOF{} is encountered
immediately. (For certain files, like ttys, it makes sense to
continue reading after an \EOF{} is hit.)
\end{funcdesc}
\begin{funcdesc}{readline}{}
Read one entire line from the file. A trailing newline character is
kept in the string (but may be absent when a file ends with an
incomplete line). An empty string is returned when \EOF{} is hit
immediately. Note: unlike \code{stdio}'s \code{fgets()}, the returned
string contains null characters (\code{'\e 0'}) if they occurred in the
input.
\end{funcdesc}
\begin{funcdesc}{readlines}{}
Read until \EOF{} using \code{readline()} and return a list containing
the lines thus read.
\end{funcdesc}
\begin{funcdesc}{seek}{offset\, whence}
Set the file's current position, like \code{stdio}'s \code{fseek()}.
The \var{whence} argument is optional and defaults to \code{0}
(absolute file positioning); other values are \code{1} (seek
relative to the current position) and \code{2} (seek relative to the
file's end). There is no return value.
\end{funcdesc}
\begin{funcdesc}{tell}{}
Return the file's current position, like \code{stdio}'s \code{ftell()}.
\end{funcdesc}
\begin{funcdesc}{write}{str}
Write a string to the file. There is no return value.
\end{funcdesc}
\subsubsection{Internal Objects.}
(See the Python Reference Manual for these.)
\subsection{Special Attributes}
The implementation adds a few special read-only attributes to several
object types, where they are relevant:
\begin{itemize}
\item
\code{\var{x}.__dict__} is a dictionary of some sort used to store an
object's (writable) attributes;
\item
\code{\var{x}.__methods__} lists the methods of many built-in object types,
e.g., \code{[].__methods__} is
% XXXJH results in?, yields?, written down as an example
\code{['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort']};
\item
\code{\var{x}.__members__} lists data attributes;
\item
\code{\var{x}.__class__} is the class to which a class instance belongs;
\item
\code{\var{x}.__bases__} is the tuple of base classes of a class object.
\end{itemize}
\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}
\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
\section{Built-in Module \sectcode{audio}}
\bimodindex{audio}
\strong{Note:} This module is obsolete, since the hardware to which it
interfaces is obsolete. For audio on the Indigo or 4D/35, see
built-in module \code{al} above.
This module provides rudimentary access to the audio I/O device
\file{/dev/audio} on the Silicon Graphics Personal IRIS 4D/25;
see {\it audio}(7). It supports the following operations:
\renewcommand{\indexsubitem}{(in module audio)}
\begin{funcdesc}{setoutgain}{n}
Sets the output gain.
\iftexi
\code{0 <= \var{n} < 256}.
\else
$0 \leq \var{n} < 256$.
%%JHXXX Sets the output gain (0-255).
\fi
\end{funcdesc}
\begin{funcdesc}{getoutgain}{}
Returns the output gain.
\end{funcdesc}
\begin{funcdesc}{setrate}{n}
Sets the sampling rate: \code{1} = 32K/sec, \code{2} = 16K/sec,
\code{3} = 8K/sec.
\end{funcdesc}
\begin{funcdesc}{setduration}{n}
Sets the `sound duration' in units of 1/100 seconds.
\end{funcdesc}
\begin{funcdesc}{read}{n}
Reads a chunk of
\var{n}
sampled bytes from the audio input (line in or microphone).
The chunk is returned as a string of length n.
Each byte encodes one sample as a signed 8-bit quantity using linear
encoding.
This string can be converted to numbers using \code{chr2num()} described
below.
\end{funcdesc}
\begin{funcdesc}{write}{buf}
Writes a chunk of samples to the audio output (speaker).
\end{funcdesc}
These operations support asynchronous audio I/O:
\renewcommand{\indexsubitem}{(in module audio)}
\begin{funcdesc}{start_recording}{n}
Starts a second thread (a process with shared memory) that begins reading
\var{n}
bytes from the audio device.
The main thread immediately continues.
\end{funcdesc}
\begin{funcdesc}{wait_recording}{}
Waits for the second thread to finish and returns the data read.
\end{funcdesc}
\begin{funcdesc}{stop_recording}{}
Makes the second thread stop reading as soon as possible.
Returns the data read so far.
\end{funcdesc}
\begin{funcdesc}{poll_recording}{}
Returns true if the second thread has finished reading (so
\code{wait_recording()} would return the data without delay).
\end{funcdesc}
\begin{funcdesc}{start_playing}{}
\funcline{wait_playing}{}
\funcline{stop_playing}{}
\funcline{poll_playing}{}
\begin{sloppypar}
Similar but for output.
\code{stop_playing()}
returns a lower bound for the number of bytes actually played (not very
accurate).
\end{sloppypar}
\end{funcdesc}
The following operations do not affect the audio device but are
implemented in C for efficiency:
\renewcommand{\indexsubitem}{(in module audio)}
\begin{funcdesc}{amplify}{buf\, f1\, f2}
Amplifies a chunk of samples by a variable factor changing from
\code{\var{f1}/256} to \code{\var{f2}/256.}
Negative factors are allowed.
Resulting values that are to large to fit in a byte are clipped.
\end{funcdesc}
\begin{funcdesc}{reverse}{buf}
Returns a chunk of samples backwards.
\end{funcdesc}
\begin{funcdesc}{add}{buf1\, buf2}
Bytewise adds two chunks of samples.
Bytes that exceed the range are clipped.
If one buffer is shorter, it is assumed to be padded with zeros.
\end{funcdesc}
\begin{funcdesc}{chr2num}{buf}
Converts a string of sampled bytes as returned by \code{read()} into
a list containing the numeric values of the samples.
\end{funcdesc}
\begin{funcdesc}{num2chr}{list}
\begin{sloppypar}
Converts a list as returned by
\code{chr2num()}
back to a buffer acceptable by
\code{write()}.
\end{sloppypar}
\end{funcdesc}
\section{Built-in module \sectcode{audioop}}
\bimodindex{audioop}
The audioop module contains some useful operations on sound fragments.
It operates on sound fragments consisting of signed integer samples of
8, 16 or 32 bits wide, stored in Python strings. This is the same
format as used by the \code{al} and \code{sunaudiodev} modules. All
scalar items are integers, unless specified otherwise.
A few of the more complicated operations only take 16-bit samples,
otherwise the sample size (in bytes) is always a parameter of the operation.
The module defines the following variables and functions:
\renewcommand{\indexsubitem}{(in module audioop)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unknown number of bytes
per sample, etc.
\end{excdesc}
\begin{funcdesc}{add}{fragment1\, fragment2\, width}
This function returns a fragment that is the addition of the two samples
passed as parameters. \var{width} is the sample width in bytes, either
\code{1}, \code{2} or \code{4}. Both fragments should have the same length.
\end{funcdesc}
\begin{funcdesc}{adpcm2lin}{adpcmfragment\, width\, state}
This routine decodes an Intel/DVI ADPCM coded fragment to a linear
fragment. See the description of \code{lin2adpcm} for details on ADPCM
coding. The routine returns a tuple
\code{(\var{sample}, \var{newstate})}
where the sample has the width specified in \var{width}.
\end{funcdesc}
\begin{funcdesc}{adpcm32lin}{adpcmfragment\, width\, state}
This routine decodes an alternative 3-bit ADPCM code. See
\code{lin2adpcm3} for details.
\end{funcdesc}
\begin{funcdesc}{avg}{fragment\, width}
This function returns the average over all samples in the fragment.
\end{funcdesc}
\begin{funcdesc}{avgpp}{fragment\, width}
This function returns the average peak-peak value over all samples in
the fragment. No filtering is done, so the useability of this routine
is questionable.
\end{funcdesc}
\begin{funcdesc}{bias}{fragment\, width\, bias}
This function returns a fragment that is the original fragment with a
bias added to each sample.
\end{funcdesc}
\begin{funcdesc}{cross}{fragment\, width}
This function returns the number of zero crossings in the fragment
passed as an argument.
\end{funcdesc}
\begin{funcdesc}{findfactor}{fragment\, reference}
This routine (which only accepts 2-byte sample fragments) calculates a
factor \var{F} such that \code{rms(add(fragment, mul(reference, -F)))}
is minimal, i.e. it calculates the factor with which you should
multiply \var{reference} to make it match as good as possible to
\var{fragment}. The fragments should be the same size.
The time taken by this routine is proportional to \code{len(fragment)}.
\end{funcdesc}
\begin{funcdesc}{findfit}{fragment\, reference}
This routine (which only accepts 2-byte sample fragments) tries to
match \var{reference} as good as possible to a portion of
\var{fragment} (which should be the longer fragment). It
(conceptually) does this by taking slices out of \var{fragment}, using
\code{findfactor} to compute the best match, and minimizing the
result.
It returns a tuple \code{(\var{offset}, \var{factor})} with offset the
(integer) offset into \var{fragment} where the optimal match started
and \var{factor} the floating-point factor as per findfactor.
\end{funcdesc}
\begin{funcdesc}{findmax}{fragment\, length}
This routine (which only accepts 2-byte sample fragments) searches
\var{fragment} for a slice of length \var{length} samples (not bytes!)
with maximum energy, i.e. it returns \var{i} for which
\code{rms(fragment[i*2:(i+length)*2])} is maximal.
The routine takes time proportional to \code{len(fragment)}.
\end{funcdesc}
\begin{funcdesc}{getsample}{fragment\, width\, index}
This function returns the value of sample \var{index} from the
fragment.
\end{funcdesc}
\begin{funcdesc}{lin2lin}{fragment\, width\, newwidth}
This function converts samples between 1-, 2- and 4-byte formats.
\end{funcdesc}
\begin{funcdesc}{lin2adpcm}{fragment\, width\, state}
This function converts samples to 4 bit Intel/DVI ADPCM encoding.
ADPCM coding is an adaptive coding scheme, whereby each 4 bit number
is the difference between one sample and the next, divided by a
(varying) step. The Intel/DVI ADPCM algorythm has been selected for
use by the IMA, so may well become a standard.
\code{State} is a tuple containing the state of the coder. The coder
returns a tuple \code{(\var{adpcmfrag}, \var{newstate})}, and the
\var{newstate} should be passed to the next call of lin2adpcm. In the
initial call \code{None} can be passed as the state. \var{adpcmfrag} is
the ADPCM coded fragment packed 2 4-bit values per byte.
\end{funcdesc}
\begin{funcdesc}{lin2adpcm3}{fragment\, width\, state}
This is an alternative ADPCM coder that uses only 3 bits per sample.
It is not compatible with the Intel/DVI ADPCM coder and its output is
not packed (due to laziness on the side of the author). Its use is
discouraged.
\end{funcdesc}
\begin{funcdesc}{lin2ulaw}{fragment\, width}
This function converts samples in the audio fragment to U-LAW encoding
and returns this as a python string. U-LAW is an audio encoding format
whereby you get a dynamic range of about 14 bits using only 8 bit
samples. It is used by the Sun audio hardware, among others.
\end{funcdesc}
\begin{funcdesc}{minmax}{fragment\, width}
This function returns a tuple consisting of the minimum and maximum
values of all samples in the sound fragment.
\end{funcdesc}
\begin{funcdesc}{max}{fragment\, width}
This function returns the maximum of the {\em absolute value} of all
samples in a fragment.
\end{funcdesc}
\begin{funcdesc}{maxpp}{fragment\, width}
This function returns the maximum peak-peak value in the sound fragment.
\end{funcdesc}
\begin{funcdesc}{mul}{fragment\, width\, factor}
Mul returns a fragment that has all samples in the original framgent
multiplied by the floating-point value \var{factor}. Overflow is
silently ignored.
\end{funcdesc}
\begin{funcdesc}{reverse}{fragment\, width}
This function reverses the samples in a fragment and returns the
modified fragment.
\end{funcdesc}
\begin{funcdesc}{tomono}{fragment\, width\, lfactor\, rfactor}
This function converts a stereo fragment to a mono fragment. The left
channel is multiplied by \var{lfactor} and the right channel by
\var{rfactor} before adding the two channels to give a mono signal.
\end{funcdesc}
\begin{funcdesc}{tostereo}{fragment\, width\, lfactor\, rfactor}
This function generates a stereo fragment from a mono fragment. Each
pair of samples in the stereo fragment are computed from the mono
sample, whereby left channel samples are multiplied by \var{lfactor}
and right channel samples by \var{rfactor}.
\end{funcdesc}
\begin{funcdesc}{mul}{fragment\, width\, factor}
Mul returns a fragment that has all samples in the original framgent
multiplied by the floating-point value \var{factor}. Overflow is
silently ignored.
\end{funcdesc}
\begin{funcdesc}{rms}{fragment\, width\, factor}
Returns the root-mean-square of the fragment, i.e.
\iftexi
the square root of the quotient of the sum of all squared sample value,
divided by the sumber of samples.
\else
% in eqn: sqrt { sum S sub i sup 2 over n }
\begin{displaymath}
\catcode`_=8
\sqrt{\frac{\sum{{S_{i}}^{2}}}{n}}
\end{displaymath}
\fi
This is a measure of the power in an audio signal.
\end{funcdesc}
\begin{funcdesc}{ulaw2lin}{fragment\, width}
This function converts sound fragments in ULAW encoding to linearly
encoded sound fragments. ULAW encoding always uses 8 bits samples, so
\var{width} refers only to the sample width of the output fragment here.
\end{funcdesc}
Note that operations such as \code{mul} or \code{max} make no
distinction between mono and stereo fragments, i.e. all samples are
treated equal. If this is a problem the stereo fragment should be split
into two mono fragments first and recombined later. Here is an example
of how to do that:
\bcode\begin{verbatim}
def mul_stereo(sample, width, lfactor, rfactor):
lsample = audioop.tomono(sample, width, 1, 0)
rsample = audioop.tomono(sample, width, 0, 1)
lsample = audioop.mul(sample, width, lfactor)
rsample = audioop.mul(sample, width, rfactor)
lsample = audioop.tostereo(lsample, width, 1, 0)
rsample = audioop.tostereo(rsample, width, 0, 1)
return audioop.add(lsample, rsample, width)
\end{verbatim}\ecode
If you use the ADPCM coder to build network packets and you want your
protocol to be stateless (i.e. to be able to tolerate packet loss)
you should not only transmit the data but also the state. Note that
you should send the \var{initial} state (the one you passed to
lin2adpcm) along to the decoder, not the final state (as returned by
the coder). If you want to use \code{struct} to store the state in
binary you can code the first element (the predicted value) in 16 bits
and the second (the delta index) in 8.
The ADPCM coders have never been tried against other ADPCM coders,
only against themselves. It could well be that I misinterpreted the
standards in which case they will not be interoperable with the
respective standards.
The \code{find...} routines might look a bit funny at first sight.
They are primarily meant for doing echo cancellation. A reasonably
fast way to do this is to pick the most energetic piece of the output
sample, locate that in the input sample and subtract the whole output
sample from the input sample:
\bcode\begin{verbatim}
def echocancel(outputdata, inputdata):
pos = audioop.findmax(outputdata, 800) # one tenth second
out_test = outputdata[pos*2:]
in_test = inputdata[pos*2:]
ipos, factor = audioop.findfit(in_test, out_test)
# Optional (for better cancellation):
# factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
# out_test)
prefill = '\0'*(pos+ipos)*2
postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
return audioop.add(inputdata, outputdata, 2)
\end{verbatim}\ecode
\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}
\section{Built-in Module \sectcode{fl}}
\bimodindex{fl}
This module provides an interface to the FORMS Library by Mark
Overmars, version 2.0b. For more info about FORMS, write to
{\tt markov@cs.ruu.nl}.
Most functions are literal translations of their C equivalents,
dropping the initial \samp{fl_} from their name. Constants used by the
library are defined in module \code{FL} described below.
The creation of objects is a little different in Python than in C:
instead of the `current form' maintained by the library to which new
FORMS objects are added, all functions that add a FORMS object to a
button are methods of the Python object representing the form.
Consequently, there are no Python equivalents for the C functions
\code{fl_addto_form} and \code{fl_end_form}, and the equivalent of
\code{fl_bgn_form} is called \code{fl.make_form}.
Watch out for the somewhat confusing terminology: FORMS uses the word
\dfn{object} for the buttons, sliders etc. that you can place in a form.
In Python, `object' means any value. The Python interface to FORMS
introduces two new Python object types: form objects (representing an
entire form) and FORMS objects (representing one button, slider etc.).
Hopefully this isn't too confusing...
There are no `free objects' in the Python interface to FORMS, nor is
there an easy way to add object classes written in Python. The FORMS
interface to GL event handling is avaiable, though, so you can mix
FORMS with pure GL windows.
\strong{Please note:} importing \code{fl} implies a call to the GL function
\code{foreground()} and to the FORMS routine \code{fl_init()}.
\subsection{Functions defined in module \sectcode{fl}}
Module \code{fl} defines the following functions. For more information
about what they do, see the description of the equivalent C function
in the FORMS documentation:
\renewcommand{\indexsubitem}{(in module fl)}
\begin{funcdesc}{make_form}{type\, width\, height}
Create a form with given type, width and height. This returns a
\dfn{form} object, whose methods are described below.
\end{funcdesc}
\begin{funcdesc}{do_forms}{}
The standard FORMS main loop. Returns a Python object representing
the FORMS object needing interaction, or the special value
\code{FL.EVENT}.
\end{funcdesc}
\begin{funcdesc}{check_forms}{}
Check for FORMS events. Returns what \code{do_forms} above returns,
or \code{None} if there is no event that immediately needs
interaction.
\end{funcdesc}
\begin{funcdesc}{set_event_call_back}{function}
Set the event callback function.
\end{funcdesc}
\begin{funcdesc}{set_graphics_mode}{rgbmode\, doublebuffering}
Set the graphics modes.
\end{funcdesc}
\begin{funcdesc}{get_rgbmode}{}
Return the current rgb mode. This is the value of the C global
variable \code{fl_rgbmode}.
\end{funcdesc}
\begin{funcdesc}{show_message}{str1\, str2\, str3}
Show a dialog box with a three-line message and an OK button.
\end{funcdesc}
\begin{funcdesc}{show_question}{str1\, str2\, str3}
Show a dialog box with a three-line message and YES and NO buttons.
It returns \code{1} if the user pressed YES, \code{0} if NO.
\end{funcdesc}
\begin{funcdesc}{show_choice}{str1\, str2\, str3\, but1\, but2\, but3}
Show a dialog box with a three-line message and up to three buttons.
It returns the number of the button clicked by the user
(\code{1}, \code{2} or \code{3}).
The \var{but2} and \var{but3} arguments are optional.
\end{funcdesc}
\begin{funcdesc}{show_input}{prompt\, default}
Show a dialog box with a one-line prompt message and text field in
which the user can enter a string. The second argument is the default
input string. It returns the string value as edited by the user.
\end{funcdesc}
\begin{funcdesc}{show_file_selector}{message\, directory\, pattern\, default}
Show a dialog box inm which the user can select a file. It returns
the absolute filename selected by the user, or \code{None} if the user
presses Cancel.
\end{funcdesc}
\begin{funcdesc}{get_directory}{}
\funcline{get_pattern}{}
\funcline{get_filename}{}
These functions return the directory, pattern and filename (the tail
part only) selected by the user in the last \code{show_file_selector}
call.
\end{funcdesc}
\begin{funcdesc}{qdevice}{dev}
\funcline{unqdevice}{dev}
\funcline{isqueued}{dev}
\funcline{qtest}{}
\funcline{qread}{}
%\funcline{blkqread}{?}
\funcline{qreset}{}
\funcline{qenter}{dev\, val}
\funcline{get_mouse}{}
\funcline{tie}{button\, valuator1\, valuator2}
These functions are the FORMS interfaces to the corresponding GL
functions. Use these if you want to handle some GL events yourself
when using \code{fl.do_events}. When a GL event is detected that
FORMS cannot handle, \code{fl.do_forms()} returns the special value
\code{FL.EVENT} and you should call \code{fl.qread()} to read the
event from the queue. Don't use the equivalent GL functions!
\end{funcdesc}
\begin{funcdesc}{color}{}
\funcline{mapcolor}{}
\funcline{getmcolor}{}
See the description in the FORMS documentation of \code{fl_color},
\code{fl_mapcolor} and \code{fl_getmcolor}.
\end{funcdesc}
\subsection{Form object methods and data attributes}
Form objects (returned by \code{fl.make_form()} above) have the
following methods. Each method corresponds to a C function whose name
is prefixed with \samp{fl_}; and whose first argument is a form
pointer; please refer to the official FORMS documentation for
descriptions.
All the \samp{add_{\rm \ldots}} functions return a Python object representing
the FORMS object. Methods of FORMS objects are described below. Most
kinds of FORMS object also have some methods specific to that kind;
these methods are listed here.
\begin{flushleft}
\renewcommand{\indexsubitem}{(form object method)}
\begin{funcdesc}{show_form}{placement\, bordertype\, name}
Show the form.
\end{funcdesc}
\begin{funcdesc}{hide_form}{}
Hide the form.
\end{funcdesc}
\begin{funcdesc}{redraw_form}{}
Redraw the form.
\end{funcdesc}
\begin{funcdesc}{set_form_position}{x\, y}
Set the form's position.
\end{funcdesc}
\begin{funcdesc}{freeze_form}{}
Freeze the form.
\end{funcdesc}
\begin{funcdesc}{unfreeze_form}{}
Unfreeze the form.
\end{funcdesc}
\begin{funcdesc}{activate_form}{}
Activate the form.
\end{funcdesc}
\begin{funcdesc}{deactivate_form}{}
Deactivate the form.
\end{funcdesc}
\begin{funcdesc}{bgn_group}{}
Begin a new group of objects; return a group object.
\end{funcdesc}
\begin{funcdesc}{end_group}{}
End the current group of objects.
\end{funcdesc}
\begin{funcdesc}{find_first}{}
Find the first object in the form.
\end{funcdesc}
\begin{funcdesc}{find_last}{}
Find the last object in the form.
\end{funcdesc}
%---
\begin{funcdesc}{add_box}{type\, x\, y\, w\, h\, name}
Add a box object to the form.
No extra methods.
\end{funcdesc}
\begin{funcdesc}{add_text}{type\, x\, y\, w\, h\, name}
Add a text object to the form.
No extra methods.
\end{funcdesc}
%\begin{funcdesc}{add_bitmap}{type\, x\, y\, w\, h\, name}
%Add a bitmap object to the form.
%\end{funcdesc}
\begin{funcdesc}{add_clock}{type\, x\, y\, w\, h\, name}
Add a clock object to the form. \\
Method:
\code{get_clock}.
\end{funcdesc}
%---
\begin{funcdesc}{add_button}{type\, x\, y\, w\, h\, name}
Add a button object to the form. \\
Methods:
\code{get_button},
\code{set_button}.
\end{funcdesc}
\begin{funcdesc}{add_lightbutton}{type\, x\, y\, w\, h\, name}
Add a lightbutton object to the form. \\
Methods:
\code{get_button},
\code{set_button}.
\end{funcdesc}
\begin{funcdesc}{add_roundbutton}{type\, x\, y\, w\, h\, name}
Add a roundbutton object to the form. \\
Methods:
\code{get_button},
\code{set_button}.
\end{funcdesc}
%---
\begin{funcdesc}{add_slider}{type\, x\, y\, w\, h\, name}
Add a slider object to the form. \\
Methods:
\code{set_slider_value},
\code{get_slider_value},
\code{set_slider_bounds},
\code{get_slider_bounds},
\code{set_slider_return},
\code{set_slider_size},
\code{set_slider_precision},
\code{set_slider_step}.
\end{funcdesc}
\begin{funcdesc}{add_valslider}{type\, x\, y\, w\, h\, name}
Add a valslider object to the form. \\
Methods:
\code{set_slider_value},
\code{get_slider_value},
\code{set_slider_bounds},
\code{get_slider_bounds},
\code{set_slider_return},
\code{set_slider_size},
\code{set_slider_precision},
\code{set_slider_step}.
\end{funcdesc}
\begin{funcdesc}{add_dial}{type\, x\, y\, w\, h\, name}
Add a dial object to the form. \\
Methods:
\code{set_dial_value},
\code{get_dial_value},
\code{set_dial_bounds},
\code{get_dial_bounds}.
\end{funcdesc}
\begin{funcdesc}{add_positioner}{type\, x\, y\, w\, h\, name}
Add a positioner object to the form. \\
Methods:
\code{set_positioner_xvalue},
\code{set_positioner_yvalue},
\code{set_positioner_xbounds},
\code{set_positioner_ybounds},
\code{get_positioner_xvalue},
\code{get_positioner_yvalue},
\code{get_positioner_xbounds},
\code{get_positioner_ybounds}.
\end{funcdesc}
\begin{funcdesc}{add_counter}{type\, x\, y\, w\, h\, name}
Add a counter object to the form. \\
Methods:
\code{set_counter_value},
\code{get_counter_value},
\code{set_counter_bounds},
\code{set_counter_step},
\code{set_counter_precision},
\code{set_counter_return}.
\end{funcdesc}
%---
\begin{funcdesc}{add_input}{type\, x\, y\, w\, h\, name}
Add a input object to the form. \\
Methods:
\code{set_input},
\code{get_input},
\code{set_input_color},
\code{set_input_return}.
\end{funcdesc}
%---
\begin{funcdesc}{add_menu}{type\, x\, y\, w\, h\, name}
Add a menu object to the form. \\
Methods:
\code{set_menu},
\code{get_menu},
\code{addto_menu}.
\end{funcdesc}
\begin{funcdesc}{add_choice}{type\, x\, y\, w\, h\, name}
Add a choice object to the form. \\
Methods:
\code{set_choice},
\code{get_choice},
\code{clear_choice},
\code{addto_choice},
\code{replace_choice},
\code{delete_choice},
\code{get_choice_text},
\code{set_choice_fontsize},
\code{set_choice_fontstyle}.
\end{funcdesc}
\begin{funcdesc}{add_browser}{type\, x\, y\, w\, h\, name}
Add a browser object to the form. \\
Methods:
\code{set_browser_topline},
\code{clear_browser},
\code{add_browser_line},
\code{addto_browser},
\code{insert_browser_line},
\code{delete_browser_line},
\code{replace_browser_line},
\code{get_browser_line},
\code{load_browser},
\code{get_browser_maxline},
\code{select_browser_line},
\code{deselect_browser_line},
\code{deselect_browser},
\code{isselected_browser_line},
\code{get_browser},
\code{set_browser_fontsize},
\code{set_browser_fontstyle},
\code{set_browser_specialkey}.
\end{funcdesc}
%---
\begin{funcdesc}{add_timer}{type\, x\, y\, w\, h\, name}
Add a timer object to the form. \\
Methods:
\code{set_timer},
\code{get_timer}.
\end{funcdesc}
\end{flushleft}
Form objects have the following data attributes; see the FORMS
documentation:
\begin{tableiii}{|l|c|l|}{code}{Name}{Type}{Meaning}
\lineiii{window}{int (read-only)}{GL window id}
\lineiii{w}{float}{form width}
\lineiii{h}{float}{form height}
\lineiii{x}{float}{form x origin}
\lineiii{y}{float}{form y origin}
\lineiii{deactivated}{int}{nonzero if form is deactivated}
\lineiii{visible}{int}{nonzero if form is visible}
\lineiii{frozen}{int}{nonzero if form is frozen}
\lineiii{doublebuf}{int}{nonzero if double buffering on}
\end{tableiii}
\subsection{FORMS object methods and data attributes}
Besides methods specific to particular kinds of FORMS objects, all
FORMS objects also have the following methods:
\renewcommand{\indexsubitem}{(FORMS object method)}
\begin{funcdesc}{set_call_back}{function\, argument}
Set the object's callback function and argument. When the object
needs interaction, the callback function will be called with two
arguments: the object, and the callback argument. (FORMS objects
without a callback function are returned by \code{fl.do_forms()} or
\code{fl.check_forms()} when they need interaction.) Call this method
without arguments to remove the callback function.
\end{funcdesc}
\begin{funcdesc}{delete_object}{}
Delete the object.
\end{funcdesc}
\begin{funcdesc}{show_object}{}
Show the object.
\end{funcdesc}
\begin{funcdesc}{hide_object}{}
Hide the object.
\end{funcdesc}
\begin{funcdesc}{redraw_object}{}
Redraw the object.
\end{funcdesc}
\begin{funcdesc}{freeze_object}{}
Freeze the object.
\end{funcdesc}
\begin{funcdesc}{unfreeze_object}{}
Unfreeze the object.
\end{funcdesc}
%\begin{funcdesc}{handle_object}{} XXX
%\end{funcdesc}
%\begin{funcdesc}{handle_object_direct}{} XXX
%\end{funcdesc}
FORMS objects have these data attributes; see the FORMS documentation:
\begin{tableiii}{|l|c|l|}{code}{Name}{Type}{Meaning}
\lineiii{objclass}{int (read-only)}{object class}
\lineiii{type}{int (read-only)}{object type}
\lineiii{boxtype}{int}{box type}
\lineiii{x}{float}{x origin}
\lineiii{y}{float}{y origin}
\lineiii{w}{float}{width}
\lineiii{h}{float}{height}
\lineiii{col1}{int}{primary color}
\lineiii{col2}{int}{secondary color}
\lineiii{align}{int}{alignment}
\lineiii{lcol}{int}{label color}
\lineiii{lsize}{float}{label font size}
\lineiii{label}{string}{label string}
\lineiii{lstyle}{int}{label style}
\lineiii{pushed}{int (read-only)}{(see FORMS docs)}
\lineiii{focus}{int (read-only)}{(see FORMS docs)}
\lineiii{belowmouse}{int (read-only)}{(see FORMS docs)}
\lineiii{frozen}{int (read-only)}{(see FORMS docs)}
\lineiii{active}{int (read-only)}{(see FORMS docs)}
\lineiii{input}{int (read-only)}{(see FORMS docs)}
\lineiii{visible}{int (read-only)}{(see FORMS docs)}
\lineiii{radio}{int (read-only)}{(see FORMS docs)}
\lineiii{automatic}{int (read-only)}{(see FORMS docs)}
\end{tableiii}
\section{Standard Module \sectcode{FL}}
\nodename{FL (uppercase)}
\stmodindex{FL}
This module defines symbolic constants needed to use the built-in
module \code{fl} (see above); they are equivalent to those defined in
the C header file \file{<forms.h>} except that the name prefix
\samp{FL_} is omitted. Read the module source for a complete list of
the defined names. Suggested use:
\bcode\begin{verbatim}
import fl
from FL import *
\end{verbatim}\ecode
\section{Standard Module \sectcode{flp}}
\stmodindex{flp}
This module defines functions that can read form definitions created
by the `form designer' (\code{fdesign}) program that comes with the
FORMS library (see module \code{fl} above).
For now, see the file \file{flp.doc} in the Python library source
directory for a description.
XXX A complete description should be inserted here!
\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}
\section{Built-in Functions}
The Python interpreter has a number of functions built into it that
are always available. They are listed here in alphabetical order.
\renewcommand{\indexsubitem}{(built-in function)}
\begin{funcdesc}{abs}{x}
Return the absolute value of a number. The argument may be a plain
or long integer or a floating point number.
\end{funcdesc}
\begin{funcdesc}{apply}{function\, args}
The \var{function} argument must be a callable object (a user-defined or
built-in function or method, or a class object) and the \var{args}
argument must be a tuple. The \var{function} is called with
\var{args} as argument list; the number of arguments is the the length
of the tuple. (This is different from just calling
\code{\var{func}(\var{args})}, since in that case there is always
exactly one argument.)
\end{funcdesc}
\begin{funcdesc}{chr}{i}
Return a string of one character whose \ASCII{} code is the integer
\var{i}, e.g., \code{chr(97)} returns the string \code{'a'}. This is the
inverse of \code{ord()}. The argument must be in the range [0..255],
inclusive.
\end{funcdesc}
\begin{funcdesc}{cmp}{x\, y}
Compare the two objects \var{x} and \var{y} and return an integer
according to the outcome. The return value is negative if \code{\var{x}
< \var{y}}, zero if \code{\var{x} == \var{y}} and strictly positive if
\code{\var{x} > \var{y}}.
\end{funcdesc}
\begin{funcdesc}{coerce}{x\, y}
Return a tuple consisting of the two numeric arguments converted to
a common type, using the same rules as used by arithmetic
operations.
\end{funcdesc}
\begin{funcdesc}{compile}{string\, filename\, kind}
Compile the \var{string} into a code object. Code objects can be
executed by a \code{exec()} statement or evaluated by a call to
\code{eval()}. The \var{filename} argument should
give the file from which the code was read; pass e.g. \code{'<string>'}
if it wasn't read from a file. The \var{kind} argument specifies
what kind of code must be compiled; it can be \code{'exec'} if
\var{string} consists of a sequence of statements, or \code{'eval'}
if it consists of a single expression.
\end{funcdesc}
\begin{funcdesc}{dir}{}
Without arguments, return the list of names in the current local
symbol table. With a module, class or class instance object as
argument (or anything else that has a \code{__dict__} attribute),
returns the list of names in that object's attribute dictionary.
The resulting list is sorted. For example:
\bcode\begin{verbatim}
>>> import sys
>>> dir()
['sys']
>>> dir(sys)
['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
>>>
\end{verbatim}\ecode
\end{funcdesc}
\begin{funcdesc}{divmod}{a\, b}
Take two numbers as arguments and return a pair of integers
consisting of their integer quotient and remainder. With mixed
operand types, the rules for binary arithmetic operators apply. For
plain and long integers, the result is the same as
\code{(\var{a} / \var{b}, \var{a} \%{} \var{b})}.
For floating point numbers the result is the same as
\code{(math.floor(\var{a} / \var{b}), \var{a} \%{} \var{b})}.
\end{funcdesc}
\begin{funcdesc}{eval}{s\, globals\, locals}
The arguments are a string and two optional dictionaries. The
string argument is parsed and evaluated as a Python expression
(technically speaking, a condition list) using the dictionaries as
global and local name space. The string must not contain null bytes
or newline characters. The return value is the
result of the expression. If the third argument is omitted it
defaults to the second. If both dictionaries are omitted, the
expression is executed in the environment where \code{eval} is
called. Syntax errors are reported as exceptions. Example:
\bcode\begin{verbatim}
>>> x = 1
>>> print eval('x+1')
2
>>>
\end{verbatim}\ecode
This function can also be used to execute arbitrary code objects
(e.g. created by \code{compile()}). In this case pass a code
object instead of a string. The code object must have been compiled
passing \code{'eval'} to the \var{kind} argument.
Note: dynamic execution of statements is supported by the
\code{exec} statement.
\end{funcdesc}
\begin{funcdesc}{filter}{function\, list}
Construct a list from those elements of \var{list} for which
\var{function} returns true. If \var{list} is a string or a tuple,
the result also has that type; otherwise it is always a list. If
\var{function} is \code{None}, the identity function is assumed,
i.e. all elements of \var{list} that are false (zero or empty) are
removed.
\end{funcdesc}
\begin{funcdesc}{float}{x}
Convert a number to floating point. The argument may be a plain or
long integer or a floating point number.
\end{funcdesc}
\begin{funcdesc}{getattr}{object\, name}
The arguments are an object and a string. The string must be the
name
of one of the object's attributes. The result is the value of that
attribute. For example, \code{getattr(\var{x}, '\var{foobar}')} is equivalent to
\code{\var{x}.\var{foobar}}.
\end{funcdesc}
\begin{funcdesc}{hasattr}{object\, name}
The arguments are an object and a string. The result is 1 if the
string is the name of one of the object's attributes, 0 if not.
(This is implemented by calling \code{getattr(object, name)} and
seeing whether it raises an exception or not.)
\end{funcdesc}
\begin{funcdesc}{hash}{object}
Return the hash value of the object (if it has one). Hash values
are 32-bit integers. They are used to quickly compare dictionary
keys during a dictionary lookup. Numeric values that compare equal
have the same hash value (even if they are of different types, e.g.
1 and 1.0).
\end{funcdesc}
\begin{funcdesc}{hex}{x}
Convert a number to a hexadecimal string. The result is a valid
Python expression.
\end{funcdesc}
\begin{funcdesc}{id}{object}
Return the `identity' of an object. This is an integer which is
guaranteed to be unique and constant for this object during its
lifetime. (Two objects whose lifetimes are disjunct may have the
same id() value.) (Implementation note: this is the address of the
object.)
\end{funcdesc}
\begin{funcdesc}{input}{prompt}
Almost equivalent to \code{eval(raw_input(\var{prompt}))}. As for
\code{raw_input()}, the prompt argument is optional. The difference is
that a long input expression may be broken over multiple lines using the
backslash convention.
\end{funcdesc}
\begin{funcdesc}{int}{x}
Convert a number to a plain integer. The argument may be a plain or
long integer or a floating point number.
\end{funcdesc}
\begin{funcdesc}{len}{s}
Return the length (the number of items) of an object. The argument
may be a sequence (string, tuple or list) or a mapping (dictionary).
\end{funcdesc}
\begin{funcdesc}{long}{x}
Convert a number to a long integer. The argument may be a plain or
long integer or a floating point number.
\end{funcdesc}
\begin{funcdesc}{map}{function\, list\, ...}
Apply \var{function} to every item of \var{list} and return a list
of the results. If additional \var{list} arguments are passed,
\var{function} must take that many arguments and is applied to
the items of all lists in parallel; if a list is shorter than another
it is assumed to be extended with \code{None} items. If
\var{function} is \code{None}, the identity function is assumed; if
there are multiple list arguments, \code{map} returns a list
consisting of tuples containing the corresponding items from all lists
(i.e. a kind of transpose operation). The \var{list} arguments may be
any kind of sequence; the result is always a list.
\end{funcdesc}
\begin{funcdesc}{max}{s}
Return the largest item of a non-empty sequence (string, tuple or
list).
\end{funcdesc}
\begin{funcdesc}{min}{s}
Return the smallest item of a non-empty sequence (string, tuple or
list).
\end{funcdesc}
\begin{funcdesc}{oct}{x}
Convert a number to an octal string. The result is a valid Python
expression.
\end{funcdesc}
\begin{funcdesc}{open}{filename\, mode}
% XXXJH xrefs here to Built-in types?
Return a new file object (described earlier under Built-in Types).
The string arguments are the same as for \code{stdio}'s
\code{fopen()}: \var{filename} is the file name to be opened,
\var{mode} indicates how the file is to be opened: \code{'r'} for
reading, \code{'w'} for writing (truncating an existing file), and
\code{'a'} opens it for appending. Modes \code{'r+'}, \code{'w+'} and
\code{'a+'} open the file for updating, provided the underlying
\code{stdio} library understands this. On systems that differentiate
between binary and text files, \code{'b'} appended to the mode opens
the file in binary mode. If the file cannot be opened, \code{IOError}
is raised.
\end{funcdesc}
\begin{funcdesc}{ord}{c}
Return the \ASCII{} value of a string of one character. E.g.,
\code{ord('a')} returns the integer \code{97}. This is the inverse of
\code{chr()}.
\end{funcdesc}
\begin{funcdesc}{pow}{x\, y}
Return \var{x} to the power \var{y}. The arguments must have
numeric types. With mixed operand types, the rules for binary
arithmetic operators apply. The effective operand type is also the
type of the result; if the result is not expressible in this type, the
function raises an exception; e.g., \code{pow(2, -1)} is not allowed.
\end{funcdesc}
\begin{funcdesc}{range}{start\, end\, step}
This is a versatile function to create lists containing arithmetic
progressions. It is most often used in \code{for} loops. The
arguments must be plain integers. If the \var{step} argument is
omitted, it defaults to \code{1}. If the \var{start} argument is
omitted, it defaults to \code{0}. The full form returns a list of
plain integers \code{[\var{start}, \var{start} + \var{step},
\var{start} + 2 * \var{step}, \ldots]}. If \var{step} is positive,
the last element is the largest \code{\var{start} + \var{i} *
\var{step}} less than \var{end}; if \var{step} is negative, the last
element is the largest \code{\var{start} + \var{i} * \var{step}}
greater than \var{end}. \var{step} must not be zero. Example:
\bcode\begin{verbatim}
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
>>>
\end{verbatim}\ecode
\end{funcdesc}
\begin{funcdesc}{raw_input}{prompt}
The string argument is optional; if present, it is written to
standard
output without a trailing newline. The function then reads a line
from input, converts it to a string (stripping a trailing newline),
and returns that. When \EOF{} is read, \code{EOFError} is raised.
Example:
\bcode\begin{verbatim}
>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
'Monty Python\'s Flying Circus'
>>>
\end{verbatim}\ecode
\end{funcdesc}
\begin{funcdesc}{reduce}{function\, list\, initializer}
Apply the binary \var{function} to the items of \var{list} so as to
reduce the list to a single value. E.g.,
\code{reduce(lambda x, y: x*y, \var{list}, 1)} returns the product of
the elements of \var{list}. The optional \var{initializer} can be
thought of as being prepended to \var{list} so as to allow reduction
of an empty \var{list}. The \var{list} arguments may be any kind of
sequence.
\end{funcdesc}
\begin{funcdesc}{reload}{module}
Re-parse and re-initialize an already imported \var{module}. The
argument must be a module object, so it must have been successfully
imported before. This is useful if you have edited the module source
file using an external editor and want to try out the new version
without leaving the Python interpreter. Note that if a module is
syntactically correct but its initialization fails, the first
\code{import} statement for it does not import the name, but does
create a (partially initialized) module object; to reload the module
you must first \code{import} it again (this will just make the
partially initialized module object available) before you can
\code{reload()} it.
\end{funcdesc}
\begin{funcdesc}{repr}{object}
Return a string containing a printable representation of an object.
This is the same value yielded by conversions (reverse quotes).
It is sometimes useful to be able to access this operation as an
ordinary function. For many types, this function makes an attempt
to return a string that would yield an object with the same value
when passed to \code{eval()}.
\end{funcdesc}
\begin{funcdesc}{round}{x\, n}
Return the floating point value \var{x} rounded to \var{n} digits
after the decimal point. If \var{n} is omitted, it defaults to zero.
The result is a floating point number. Values are rounded to the
closest multiple of 10 to the power minus \var{n}; if two multiples
are equally close, rounding is done away from 0 (so e.g.
\code{round(0.5)} is \code{1.0} and \code{round(-0.5)} is \code{-1.0}).
\end{funcdesc}
\begin{funcdesc}{setattr}{object\, name\, value}
This is the counterpart of \code{getattr}. The arguments are an
object, a string and an arbitrary value. The string must be the name
of one of the object's attributes. The function assigns the value to
the attribute, provided the object allows it. For example,
\code{setattr(\var{x}, '\var{foobar}', 123)} is equivalent to
\code{\var{x}.\var{foobar} = 123}.
\end{funcdesc}
\begin{funcdesc}{str}{object}
Return a string containing a nicely printable representation of an
object. For strings, this returns the string itself. The difference
with \code{repr(\var{object}} is that \code{str(\var{object}} does not
always attempt to return a string that is acceptable to \code{eval()};
its goal is to return a printable string.
\end{funcdesc}
\begin{funcdesc}{type}{object}
% XXXJH xref to buil-in objects here?
Return the type of an \var{object}. The return value is a type
object. There is not much you can do with type objects except compare
them to other type objects; e.g., the following checks if a variable
is a string:
\bcode\begin{verbatim}
>>> if type(x) == type(''): print 'It is a string'
\end{verbatim}\ecode
\end{funcdesc}
\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.
\chapter{MACINTOSH ONLY}
The following modules are available on the Apple Macintosh only.
\section{Built-in module \sectcode{mac}}
\bimodindex{mac}
This module provides a subset of the operating system dependent
functionality provided by the optional built-in module \code{posix}.
It is best accessed through the more portable standard module
\code{os}.
The following functions are available in this module:
\code{chdir},
\code{getcwd},
\code{listdir},
\code{mkdir},
\code{rename},
\code{rmdir},
\code{stat},
\code{sync},
\code{unlink},
as well as the exception \code{error}.
\section{Standard module \sectcode{macpath}}
\stmodindex{macpath}
This module provides a subset of the pathname manipulation functions
available from the optional standard module \code{posixpath}. It is
best accessed through the more portable standard module \code{os}, as
\code{os.path}.
The following functions are available in this module:
\code{normcase},
\code{isabs},
\code{join},
\code{split},
\code{isdir},
\code{isfile},
\code{exists}.
\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.
\chapter{Built-in Modules}
The modules described in this chapter are built into the interpreter
and considered part of Python's standard environment: they are always
avaialble.\footnote{at least in theory --- it is possible to specify
at build time that one or more of these modules should be excluded,
but it would be antisocial to do so.}
\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).
\section{Built-in Module \sectcode{socket}}
\bimodindex{socket}
This module provides access to the BSD {\em socket} interface.
It is available on \UNIX{} systems that support this interface.
For an introduction to socket programming (in C), see the following
papers: \emph{An Introductory 4.3BSD Interprocess Communication
Tutorial}, by Stuart Sechrest and \emph{An Advanced 4.3BSD Interprocess
Communication Tutorial}, by Samuel J. Leffler et al, both in the
\UNIX{} Programmer's Manual, Supplementary Documents 1 (sections PS1:7
and PS1:8). The \UNIX{} manual pages for the various socket-related
system calls also a valuable source of information on the details of
socket semantics.
The Python interface is a straightforward transliteration of the
\UNIX{} system call and library interface for sockets to Python's
object-oriented style: the \code{socket()} function returns a
\dfn{socket object} whose methods implement the various socket system
calls. Parameter types are somewhat higer-level than in the C
interface: as with \code{read()} and \code{write()} operations on Python
files, buffer allocation on receive operations is automatic, and
buffer length is implicit on send operations.
Socket addresses are represented as a single string for the
\code{AF_UNIX} address family and as a pair
\code{(\var{host}, \var{port})} for the \code{AF_INET} address family,
where \var{host} is a string representing
either a hostname in Internet domain notation like
\code{'daring.cwi.nl'} or an IP address like \code{'100.50.200.5'},
and \var{port} is an integral port number. Other address families are
currently not supported. The address format required by a particular
socket object is automatically selected based on the address family
specified when the socket object was created.
All errors raise exceptions. The normal exceptions for invalid
argument types and out-of-memory conditions can be raised; errors
related to socket or address semantics raise the error \code{socket.error}.
Non-blocking and asynchronous mode are not supported; see module
\code{select} for a way to do non-blocking socket I/O.
The module \code{socket} exports the following constants and functions:
\renewcommand{\indexsubitem}{(in module socket)}
\begin{excdesc}{error}
This exception is raised for socket- or address-related errors.
The accompanying value is either a string telling what went wrong or a
pair \code{(\var{errno}, \var{string})}
representing an error returned by a system
call, similar to the value accompanying \code{posix.error}.
\end{excdesc}
\begin{datadesc}{AF_UNIX}
\dataline{AF_INET}
These constants represent the address (and protocol) families,
used for the first argument to \code{socket()}.
\end{datadesc}
\begin{datadesc}{SOCK_STREAM}
\dataline{SOCK_DGRAM}
These constants represent the socket types,
used for the second argument to \code{socket()}.
(There are other types, but only \code{SOCK_STREAM} and
\code{SOCK_DGRAM} appear to be generally useful.)
\end{datadesc}
\begin{funcdesc}{gethostbyname}{hostname}
Translate a host name to IP address format. The IP address is
returned as a string, e.g., \code{'100.50.200.5'}. If the host name
is an IP address itself it is returned unchanged.
\end{funcdesc}
\begin{funcdesc}{getservbyname}{servicename\, protocolname}
Translate an Internet service name and protocol name to a port number
for that service. The protocol name should be \code{'tcp'} or
\code{'udp'}.
\end{funcdesc}
\begin{funcdesc}{socket}{family\, type\, proto}
Create a new socket using the given address family, socket type and
protocol number. The address family should be \code{AF_INET} or
\code{AF_UNIX}. The socket type should be \code{SOCK_STREAM},
\code{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants.
The protocol number is usually zero and may be omitted in that case.
\end{funcdesc}
\begin{funcdesc}{fromfd}{fd\, family\, type\, proto}
Build a socket object from an existing file descriptor (an integer as
returned by a file object's \code{fileno} method). Address family,
socket type and protocol number are as for the \code{socket} function
above. The file descriptor should refer to a socket, but this is not
checked --- subsequent operations on the object may fail if the file
descriptor is invalid. This function is rarely needed, but can be
used to get or set socket options on a socket passed to a program as
standard input or output (e.g. a server started by the \UNIX{} inet
daemon).
\end{funcdesc}
\subsection{Socket Object Methods}
\noindent
Socket objects have the following methods. Except for
\code{makefile()} these correspond to \UNIX{} system calls applicable to
sockets.
\renewcommand{\indexsubitem}{(socket method)}
\begin{funcdesc}{accept}{}
Accept a connection.
The socket must be bound to an address and listening for connections.
The return value is a pair \code{(\var{conn}, \var{address})}
where \var{conn} is a \emph{new} socket object usable to send and
receive data on the connection, and \var{address} is the address bound
to the socket on the other end of the connection.
\end{funcdesc}
\begin{funcdesc}{avail}{}
Return true (nonzero) if at least one byte of data can be received
from the socket without blocking, false (zero) if not. There is no
indication of how many bytes are available. (\strong{This function is
obsolete --- see module \code{select} for a more general solution.})
\end{funcdesc}
\begin{funcdesc}{bind}{address}
Bind the socket to an address. The socket must not already be bound.
\end{funcdesc}
\begin{funcdesc}{close}{}
Close the socket. All future operations on the socket object will fail.
The remote end will receive no more data (after queued data is flushed).
Sockets are automatically closed when they are garbage-collected.
\end{funcdesc}
\begin{funcdesc}{connect}{address}
Connect to a remote socket.
\end{funcdesc}
\begin{funcdesc}{fileno}{}
Return the socket's file descriptor (a small integer). This is useful
with \code{select}.
\end{funcdesc}
\begin{funcdesc}{getpeername}{}
Return the remote address to which the socket is connected. This is
useful to find out the port number of a remote IP socket, for instance.
\end{funcdesc}
\begin{funcdesc}{getsockname}{}
Return the socket's own address. This is useful to find out the port
number of an IP socket, for instance.
\end{funcdesc}
\begin{funcdesc}{getsockopt}{level\, optname\, buflen}
Return the value of the given socket option (see the \UNIX{} man page
{\it getsockopt}(2)). The needed symbolic constants are defined in module
SOCKET. If the optional third argument is absent, an integer option
is assumed and its integer value is returned by the function. If
\var{buflen} is present, it specifies the maximum length of the buffer used
to receive the option in, and this buffer is returned as a string.
It's up to the caller to decode the contents of the buffer (see the
optional built-in module \code{struct} for a way to decode C structures
encoded as strings).
\end{funcdesc}
\begin{funcdesc}{listen}{backlog}
Listen for connections made to the socket.
The argument (in the range 0-5) specifies the maximum number of
queued connections.
\end{funcdesc}
\begin{funcdesc}{makefile}{mode}
Return a \dfn{file object} associated with the socket.
(File objects were described earlier under Built-in Types.)
The file object references a \code{dup}ped version of the socket file
descriptor, so the file object and socket object may be closed or
garbage-collected independently.
\end{funcdesc}
\begin{funcdesc}{recv}{bufsize\, flags}
Receive data from the socket. The return value is a string representing
the data received. The maximum amount of data to be received
at once is specified by \var{bufsize}. See the \UNIX{} manual page
for the meaning of the optional argument \var{flags}; it defaults to
zero.
\end{funcdesc}
\begin{funcdesc}{recvfrom}{bufsize}
Receive data from the socket. The return value is a pair
\code{(\var{string}, \var{address})} where \var{string} is a string
representing the data received and \var{address} is the address of the
socket sending the data.
\end{funcdesc}
\begin{funcdesc}{send}{string}
Send data to the socket. The socket must be connected to a remote
socket.
\end{funcdesc}
\begin{funcdesc}{sendto}{string\, address}
Send data to the socket. The socket should not be connected to a
remote socket, since the destination socket is specified by
\code{address}.
\end{funcdesc}
\begin{funcdesc}{setsockopt}{level\, optname\, value}
Set the value of the given socket option (see the \UNIX{} man page
{\it setsockopt}(2)). The needed symbolic constants are defined in module
\code{SOCKET}. The value can be an integer or a string representing a
buffer. In the latter case it is up to the caller to ensure that the
string contains the proper bits (see the optional built-in module
\code{struct} for a way to encode C structures as strings).
\end{funcdesc}
\begin{funcdesc}{shutdown}{how}
Shut down one or both halves of the connection. If \var{how} is \code{0},
further receives are disallowed. If \var{how} is \code{1}, further sends are
disallowed. If \var{how} is \code{2}, further sends and receives are
disallowed.
\end{funcdesc}
Note that there are no methods \code{read()} or \code{write()}; use
\code{recv()} and \code{send()} without \var{flags} argument instead.
\subsection{Example}
\nodename{Socket Example}
Here are two minimal example programs using the TCP/IP protocol: a
server that echoes all data that it receives back (servicing only one
client), and a client using it. Note that a server must perform the
sequence \code{socket}, \code{bind}, \code{listen}, \code{accept}
(possibly repeating the \code{accept} to service more than one client),
while a client only needs the sequence \code{socket}, \code{connect}.
Also note that the server does not \code{send}/\code{receive} on the
socket it is listening on but on the new socket returned by
\code{accept}.
\bcode\begin{verbatim}
# Echo server program
from socket import *
HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged server
s = socket(AF_INET, SOCK_STREAM)
s.bind(HOST, PORT)
s.listen(0)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
\end{verbatim}\ecode
\bcode\begin{verbatim}
# Echo client program
from socket import *
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket(AF_INET, SOCK_STREAM)
s.connect(HOST, PORT)
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', `data`
\end{verbatim}\ecode
\chapter{Standard Modules}
The modules described in this chapter are implemented in Python, but
are considered to be a part of Python's standard environment: they are
always available.\footnote{at least in theory --- it is possible to
botch the library installation or to sabotage the module search path
so that these modules cannot be found.}
\chapter{STDWIN ONLY}
\section{Built-in Module \sectcode{stdwin}}
\bimodindex{stdwin}
This module defines several new object types and functions that
provide access to the functionality of the Standard Window System
Interface, STDWIN [CWI report CR-R8817].
It is available on systems to which STDWIN has been ported (which is
most systems).
It is only available if the \code{DISPLAY} environment variable is set
or an explicit \samp{-display \var{displayname}} argument is passed to
the interpreter.
Functions have names that usually resemble their C STDWIN counterparts
with the initial `w' dropped.
Points are represented by pairs of integers; rectangles
by pairs of points.
For a complete description of STDWIN please refer to the documentation
of STDWIN for C programmers (aforementioned CWI report).
\subsection{Functions Defined in Module \sectcode{stdwin}}
The following functions are defined in the \code{stdwin} module:
\renewcommand{\indexsubitem}{(in module stdwin)}
\begin{funcdesc}{open}{title}
Open a new window whose initial title is given by the string argument.
Return a window object; window object methods are described below.%
\footnote{The Python version of STDWIN does not support draw procedures; all
drawing requests are reported as draw events.}
\end{funcdesc}
\begin{funcdesc}{getevent}{}
Wait for and return the next event.
An event is returned as a triple: the first element is the event
type, a small integer; the second element is the window object to which
the event applies, or
\code{None}
if it applies to no window in particular;
the third element is type-dependent.
Names for event types and command codes are defined in the standard
module
\code{stdwinevent}.
\end{funcdesc}
\begin{funcdesc}{pollevent}{}
Return the next event, if one is immediately available.
If no event is available, return \code{()}.
\end{funcdesc}
\begin{funcdesc}{getactive}{}
Return the window that is currently active, or \code{None} if no
window is currently active. (This can be emulated by monitoring
WE_ACTIVATE and WE_DEACTIVATE events.)
\end{funcdesc}
\begin{funcdesc}{listfontnames}{pattern}
Return the list of font names in the system that match the pattern (a
string). The pattern should normally be \code{'*'}; returns all
available fonts. If the underlying window system is X11, other
patterns follow the standard X11 font selection syntax (as used e.g.
in resource definitions), i.e. the wildcard character \code{'*'}
matches any sequence of characters (including none) and \code{'?'}
matches any single character.
\end{funcdesc}
\begin{funcdesc}{setdefscrollbars}{hflag\, vflag}
Set the flags controlling whether subsequently opened windows will
have horizontal and/or vertical scroll bars.
\end{funcdesc}
\begin{funcdesc}{setdefwinpos}{h\, v}
Set the default window position for windows opened subsequently.
\end{funcdesc}
\begin{funcdesc}{setdefwinsize}{width\, height}
Set the default window size for windows opened subsequently.
\end{funcdesc}
\begin{funcdesc}{getdefscrollbars}{}
Return the flags controlling whether subsequently opened windows will
have horizontal and/or vertical scroll bars.
\end{funcdesc}
\begin{funcdesc}{getdefwinpos}{}
Return the default window position for windows opened subsequently.
\end{funcdesc}
\begin{funcdesc}{getdefwinsize}{}
Return the default window size for windows opened subsequently.
\end{funcdesc}
\begin{funcdesc}{getscrsize}{}
Return the screen size in pixels.
\end{funcdesc}
\begin{funcdesc}{getscrmm}{}
Return the screen size in millimeters.
\end{funcdesc}
\begin{funcdesc}{fetchcolor}{colorname}
Return the pixel value corresponding to the given color name.
Return the default foreground color for unknown color names.
Hint: the following code tests wheter you are on a machine that
supports more than two colors:
\bcode\begin{verbatim}
if stdwin.fetchcolor('black') <> \
stdwin.fetchcolor('red') <> \
stdwin.fetchcolor('white'):
print 'color machine'
else:
print 'monochrome machine'
\end{verbatim}\ecode
\end{funcdesc}
\begin{funcdesc}{setfgcolor}{pixel}
Set the default foreground color.
This will become the default foreground color of windows opened
subsequently, including dialogs.
\end{funcdesc}
\begin{funcdesc}{setbgcolor}{pixel}
Set the default background color.
This will become the default background color of windows opened
subsequently, including dialogs.
\end{funcdesc}
\begin{funcdesc}{getfgcolor}{}
Return the pixel value of the current default foreground color.
\end{funcdesc}
\begin{funcdesc}{getbgcolor}{}
Return the pixel value of the current default background color.
\end{funcdesc}
\begin{funcdesc}{setfont}{fontname}
Set the current default font.
This will become the default font for windows opened subsequently,
and is also used by the text measuring functions \code{textwidth},
\code{textbreak}, \code{lineheight} and \code{baseline} below.
This accepts two more optional parameters, size and style:
Size is the font size (in `points').
Style is a single character specifying the style, as follows:
\code{'b'} = bold,
\code{'i'} = italic,
\code{'o'} = bold + italic,
\code{'u'} = underline;
default style is roman.
Size and style are ignored under X11 but used on the Macintosh.
(Sorry for all this complexity --- a more uniform interface is being designed.)
\end{funcdesc}
\begin{funcdesc}{menucreate}{title}
Create a menu object referring to a global menu (a menu that appears in
all windows).
Methods of menu objects are described below.
Note: normally, menus are created locally; see the window method
\code{menucreate} below.
\strong{Warning:} the menu only appears in a window as long as the object
returned by this call exists.
\end{funcdesc}
\begin{funcdesc}{newbitmap}{width\, height}
Create a new bitmap object of the given dimensions.
Methods of bitmap objects are described below.
\end{funcdesc}
\begin{funcdesc}{fleep}{}
Cause a beep or bell (or perhaps a `visual bell' or flash, hence the
name).
\end{funcdesc}
\begin{funcdesc}{message}{string}
Display a dialog box containing the string.
The user must click OK before the function returns.
\end{funcdesc}
\begin{funcdesc}{askync}{prompt\, default}
Display a dialog that prompts the user to answer a question with yes or
no.
Return 0 for no, 1 for yes.
If the user hits the Return key, the default (which must be 0 or 1) is
returned.
If the user cancels the dialog, the
\code{KeyboardInterrupt}
exception is raised.
\end{funcdesc}
\begin{funcdesc}{askstr}{prompt\, default}
Display a dialog that prompts the user for a string.
If the user hits the Return key, the default string is returned.
If the user cancels the dialog, the
\code{KeyboardInterrupt}
exception is raised.
\end{funcdesc}
\begin{funcdesc}{askfile}{prompt\, default\, new}
Ask the user to specify a filename.
If
\var{new}
is zero it must be an existing file; otherwise, it must be a new file.
If the user cancels the dialog, the
\code{KeyboardInterrupt}
exception is raised.
\end{funcdesc}
\begin{funcdesc}{setcutbuffer}{i\, string}
Store the string in the system's cut buffer number
\var{i},
where it can be found (for pasting) by other applications.
On X11, there are 8 cut buffers (numbered 0..7).
Cut buffer number 0 is the `clipboard' on the Macintosh.
\end{funcdesc}
\begin{funcdesc}{getcutbuffer}{i}
Return the contents of the system's cut buffer number
\var{i}.
\end{funcdesc}
\begin{funcdesc}{rotatecutbuffers}{n}
On X11, rotate the 8 cut buffers by
\var{n}.
Ignored on the Macintosh.
\end{funcdesc}
\begin{funcdesc}{getselection}{i}
Return X11 selection number
\var{i.}
Selections are not cut buffers.
Selection numbers are defined in module
\code{stdwinevents}.
Selection \code{WS_PRIMARY} is the
\dfn{primary}
selection (used by
xterm,
for instance);
selection \code{WS_SECONDARY} is the
\dfn{secondary}
selection; selection \code{WS_CLIPBOARD} is the
\dfn{clipboard}
selection (used by
xclipboard).
On the Macintosh, this always returns an empty string.
\end{funcdesc}
\begin{funcdesc}{resetselection}{i}
Reset selection number
\var{i},
if this process owns it.
(See window method
\code{setselection()}).
\end{funcdesc}
\begin{funcdesc}{baseline}{}
Return the baseline of the current font (defined by STDWIN as the
vertical distance between the baseline and the top of the
characters).
\end{funcdesc}
\begin{funcdesc}{lineheight}{}
Return the total line height of the current font.
\end{funcdesc}
\begin{funcdesc}{textbreak}{str\, width}
Return the number of characters of the string that fit into a space of
\var{width}
bits wide when drawn in the curent font.
\end{funcdesc}
\begin{funcdesc}{textwidth}{str}
Return the width in bits of the string when drawn in the current font.
\end{funcdesc}
\begin{funcdesc}{connectionnumber}{}
\funcline{fileno}{}
(X11 under \UNIX{} only) Return the ``connection number'' used by the
underlying X11 implementation. (This is normally the file number of
the socket.) Both functions return the same value;
\code{connectionnumber()} is named after the corresponding function in
X11 and STDWIN, while \code{fileno()} makes it possible to use the
\code{stdwin} module as a ``file'' object parameter to
\code{select.select()}. Note that if \code{select()} implies that
input is possible on \code{stdwin}, this does not guarantee that an
event is ready --- it may be some internal communication going on
between the X server and the client library. Thus, you should call
\code{stdwin.pollevent()} until it returns \code{None} to check for
events if you don't want your program to block. Because of internal
buffering in X11, it is also possible that \code{stdwin.pollevent()}
returns an event while \code{select()} does not find \code{stdwin} to
be ready, so you should read any pending events with
\code{stdwin.pollevent()} until it returns \code{None} before entering
a blocking \code{select()} call.
\ttindex{select}
\end{funcdesc}
\subsection{Window Object Methods}
Window objects are created by \code{stdwin.open()}. They are closed
by their \code{close()} method or when they are garbage-collected.
Window objects have the following methods:
\renewcommand{\indexsubitem}{(window method)}
\begin{funcdesc}{begindrawing}{}
Return a drawing object, whose methods (described below) allow drawing
in the window.
\end{funcdesc}
\begin{funcdesc}{change}{rect}
Invalidate the given rectangle; this may cause a draw event.
\end{funcdesc}
\begin{funcdesc}{gettitle}{}
Returns the window's title string.
\end{funcdesc}
\begin{funcdesc}{getdocsize}{}
\begin{sloppypar}
Return a pair of integers giving the size of the document as set by
\code{setdocsize()}.
\end{sloppypar}
\end{funcdesc}
\begin{funcdesc}{getorigin}{}
Return a pair of integers giving the origin of the window with respect
to the document.
\end{funcdesc}
\begin{funcdesc}{gettitle}{}
Return the window's title string.
\end{funcdesc}
\begin{funcdesc}{getwinsize}{}
Return a pair of integers giving the size of the window.
\end{funcdesc}
\begin{funcdesc}{getwinpos}{}
Return a pair of integers giving the position of the window's upper
left corner (relative to the upper left corner of the screen).
\end{funcdesc}
\begin{funcdesc}{menucreate}{title}
Create a menu object referring to a local menu (a menu that appears
only in this window).
Methods of menu objects are described below.
{\bf Warning:} the menu only appears as long as the object
returned by this call exists.
\end{funcdesc}
\begin{funcdesc}{scroll}{rect\, point}
Scroll the given rectangle by the vector given by the point.
\end{funcdesc}
\begin{funcdesc}{setdocsize}{point}
Set the size of the drawing document.
\end{funcdesc}
\begin{funcdesc}{setorigin}{point}
Move the origin of the window (its upper left corner)
to the given point in the document.
\end{funcdesc}
\begin{funcdesc}{setselection}{i\, str}
Attempt to set X11 selection number
\var{i}
to the string
\var{str}.
(See stdwin method
\code{getselection()}
for the meaning of
\var{i}.)
Return true if it succeeds.
If succeeds, the window ``owns'' the selection until
(a) another applications takes ownership of the selection; or
(b) the window is deleted; or
(c) the application clears ownership by calling
\code{stdwin.resetselection(\var{i})}.
When another application takes ownership of the selection, a
\code{WE_LOST_SEL}
event is received for no particular window and with the selection number
as detail.
Ignored on the Macintosh.
\end{funcdesc}
\begin{funcdesc}{settimer}{dsecs}
Schedule a timer event for the window in
\code{\var{dsecs}/10}
seconds.
\end{funcdesc}
\begin{funcdesc}{settitle}{title}
Set the window's title string.
\end{funcdesc}
\begin{funcdesc}{setwincursor}{name}
\begin{sloppypar}
Set the window cursor to a cursor of the given name.
It raises the
\code{RuntimeError}
exception if no cursor of the given name exists.
Suitable names include
\code{'ibeam'},
\code{'arrow'},
\code{'cross'},
\code{'watch'}
and
\code{'plus'}.
On X11, there are many more (see
\file{<X11/cursorfont.h>}).
\end{sloppypar}
\end{funcdesc}
\begin{funcdesc}{setwinpos}{h\, v}
Set the the position of the window's upper left corner (relative to
the upper left corner of the screen).
\end{funcdesc}
\begin{funcdesc}{setwinsize}{width\, height}
Set the window's size.
\end{funcdesc}
\begin{funcdesc}{show}{rect}
Try to ensure that the given rectangle of the document is visible in
the window.
\end{funcdesc}
\begin{funcdesc}{textcreate}{rect}
Create a text-edit object in the document at the given rectangle.
Methods of text-edit objects are described below.
\end{funcdesc}
\begin{funcdesc}{setactive}{}
Attempt to make this window the active window. If successful, this
will generate a WE_ACTIVATE event (and a WE_DEACTIVATE event in case
another window in this application became inactive).
\end{funcdesc}
\begin{funcdesc}{close}{}
Discard the window object. It should not be used again.
\end{funcdesc}
\subsection{Drawing Object Methods}
Drawing objects are created exclusively by the window method
\code{begindrawing()}.
Only one drawing object can exist at any given time; the drawing object
must be deleted to finish drawing.
No drawing object may exist when
\code{stdwin.getevent()}
is called.
Drawing objects have the following methods:
\renewcommand{\indexsubitem}{(drawing method)}
\begin{funcdesc}{box}{rect}
Draw a box just inside a rectangle.
\end{funcdesc}
\begin{funcdesc}{circle}{center\, radius}
Draw a circle with given center point and radius.
\end{funcdesc}
\begin{funcdesc}{elarc}{center\, \(rh\, rv\)\, \(a1\, a2\)}
Draw an elliptical arc with given center point.
\code{(\var{rh}, \var{rv})}
gives the half sizes of the horizontal and vertical radii.
\code{(\var{a1}, \var{a2})}
gives the angles (in degrees) of the begin and end points.
0 degrees is at 3 o'clock, 90 degrees is at 12 o'clock.
\end{funcdesc}
\begin{funcdesc}{erase}{rect}
Erase a rectangle.
\end{funcdesc}
\begin{funcdesc}{fillcircle}{center\, radius}
Draw a filled circle with given center point and radius.
\end{funcdesc}
\begin{funcdesc}{fillelarc}{center\, \(rh\, rv\)\, \(a1\, a2\)}
Draw a filled elliptical arc; arguments as for \code{elarc}.
\end{funcdesc}
\begin{funcdesc}{fillpoly}{points}
Draw a filled polygon given by a list (or tuple) of points.
\end{funcdesc}
\begin{funcdesc}{invert}{rect}
Invert a rectangle.
\end{funcdesc}
\begin{funcdesc}{line}{p1\, p2}
Draw a line from point
\var{p1}
to
\var{p2}.
\end{funcdesc}
\begin{funcdesc}{paint}{rect}
Fill a rectangle.
\end{funcdesc}
\begin{funcdesc}{poly}{points}
Draw the lines connecting the given list (or tuple) of points.
\end{funcdesc}
\begin{funcdesc}{shade}{rect\, percent}
Fill a rectangle with a shading pattern that is about
\var{percent}
percent filled.
\end{funcdesc}
\begin{funcdesc}{text}{p\, str}
Draw a string starting at point p (the point specifies the
top left coordinate of the string).
\end{funcdesc}
\begin{funcdesc}{xorcircle}{center\, radius}
\funcline{xorelarc}{center\, \(rh\, rv\)\, \(a1\, a2\)}
\funcline{xorline}{p1\, p2}
\funcline{xorpoly}{points}
Draw a circle, an elliptical arc, a line or a polygon, respectively,
in XOR mode.
\end{funcdesc}
\begin{funcdesc}{setfgcolor}{}
\funcline{setbgcolor}{}
\funcline{getfgcolor}{}
\funcline{getbgcolor}{}
These functions are similar to the corresponding functions described
above for the
\code{stdwin}
module, but affect or return the colors currently used for drawing
instead of the global default colors.
When a drawing object is created, its colors are set to the window's
default colors, which are in turn initialized from the global default
colors when the window is created.
\end{funcdesc}
\begin{funcdesc}{setfont}{}
\funcline{baseline}{}
\funcline{lineheight}{}
\funcline{textbreak}{}
\funcline{textwidth}{}
These functions are similar to the corresponding functions described
above for the
\code{stdwin}
module, but affect or use the current drawing font instead of
the global default font.
When a drawing object is created, its font is set to the window's
default font, which is in turn initialized from the global default
font when the window is created.
\end{funcdesc}
\begin{funcdesc}{bitmap}{point\, bitmap\, mask}
Draw the \var{bitmap} with its top left corner at \var{point}.
If the optional \var{mask} argument is present, it should be either
the same object as \var{bitmap}, to draw only those bits that are set
in the bitmap, in the foreground color, or \code{None}, to draw all
bits (ones are drawn in the foreground color, zeros in the background
color).
\end{funcdesc}
\begin{funcdesc}{cliprect}{rect}
Set the ``clipping region'' to a rectangle.
The clipping region limits the effect of all drawing operations, until
it is changed again or until the drawing object is closed. When a
drawing object is created the clipping region is set to the entire
window. When an object to be drawn falls partly outside the clipping
region, the set of pixels drawn is the intersection of the clipping
region and the set of pixels that would be drawn by the same operation
in the absence of a clipping region.
clipping region
\end{funcdesc}
\begin{funcdesc}{noclip}{}
Reset the clipping region to the entire window.
\end{funcdesc}
\begin{funcdesc}{close}{}
\funcline{enddrawing}{}
Discard the drawing object. It should not be used again.
\end{funcdesc}
\subsection{Menu Object Methods}
A menu object represents a menu.
The menu is destroyed when the menu object is deleted.
The following methods are defined:
\renewcommand{\indexsubitem}{(menu method)}
\begin{funcdesc}{additem}{text\, shortcut}
Add a menu item with given text.
The shortcut must be a string of length 1, or omitted (to specify no
shortcut).
\end{funcdesc}
\begin{funcdesc}{setitem}{i\, text}
Set the text of item number
\var{i}.
\end{funcdesc}
\begin{funcdesc}{enable}{i\, flag}
Enable or disables item
\var{i}.
\end{funcdesc}
\begin{funcdesc}{check}{i\, flag}
Set or clear the
\dfn{check mark}
for item
\var{i}.
\end{funcdesc}
\begin{funcdesc}{close}{}
Discard the menu object. It should not be used again.
\end{funcdesc}
\subsection{Bitmap Object Methods}
A bitmap represents a rectangular array of bits.
The top left bit has coordinate (0, 0).
A bitmap can be drawn with the \code{bitmap} method of a drawing object.
The following methods are defined:
\renewcommand{\indexsubitem}{(bitmap method)}
\begin{funcdesc}{getsize}{}
Return a tuple representing the width and height of the bitmap.
(This returns the values that have been passed to the \code{newbitmap}
function.)
\end{funcdesc}
\begin{funcdesc}{setbit}{point\, bit}
Set the value of the bit indicated by \var{point} to \var{bit}.
\end{funcdesc}
\begin{funcdesc}{getbit}{point}
Return the value of the bit indicated by \var{point}.
\end{funcdesc}
\begin{funcdesc}{close}{}
Discard the bitmap object. It should not be used again.
\end{funcdesc}
\subsection{Text-edit Object Methods}
A text-edit object represents a text-edit block.
For semantics, see the STDWIN documentation for C programmers.
The following methods exist:
\renewcommand{\indexsubitem}{(text-edit method)}
\begin{funcdesc}{arrow}{code}
Pass an arrow event to the text-edit block.
The
\var{code}
must be one of
\code{WC_LEFT},
\code{WC_RIGHT},
\code{WC_UP}
or
\code{WC_DOWN}
(see module
\code{stdwinevents}).
\end{funcdesc}
\begin{funcdesc}{draw}{rect}
Pass a draw event to the text-edit block.
The rectangle specifies the redraw area.
\end{funcdesc}
\begin{funcdesc}{event}{type\, window\, detail}
Pass an event gotten from
\code{stdwin.getevent()}
to the text-edit block.
Return true if the event was handled.
\end{funcdesc}
\begin{funcdesc}{getfocus}{}
Return 2 integers representing the start and end positions of the
focus, usable as slice indices on the string returned by
\code{gettext()}.
\end{funcdesc}
\begin{funcdesc}{getfocustext}{}
Return the text in the focus.
\end{funcdesc}
\begin{funcdesc}{getrect}{}
Return a rectangle giving the actual position of the text-edit block.
(The bottom coordinate may differ from the initial position because
the block automatically shrinks or grows to fit.)
\end{funcdesc}
\begin{funcdesc}{gettext}{}
Return the entire text buffer.
\end{funcdesc}
\begin{funcdesc}{move}{rect}
Specify a new position for the text-edit block in the document.
\end{funcdesc}
\begin{funcdesc}{replace}{str}
Replace the text in the focus by the given string.
The new focus is an insert point at the end of the string.
\end{funcdesc}
\begin{funcdesc}{setfocus}{i\, j}
Specify the new focus.
Out-of-bounds values are silently clipped.
\end{funcdesc}
\begin{funcdesc}{settext}{str}
Replace the entire text buffer by the given string and set the focus
to \code{(0, 0)}.
\end{funcdesc}
\begin{funcdesc}{setview}{rect}
Set the view rectangle to \var{rect}. If \var{rect} is \code{None},
viewing mode is reset. In viewing mode, all output from the text-edit
object is clipped to the viewing rectangle. This may be useful to
implement your own scrolling text subwindow.
\end{funcdesc}
\begin{funcdesc}{close}{}
Discard the text-edit object. It should not be used again.
\end{funcdesc}
\subsection{Example}
\nodename{Stdwin Example}
Here is a minimal example of using STDWIN in Python.
It creates a window and draws the string ``Hello world'' in the top
left corner of the window.
The window will be correctly redrawn when covered and re-exposed.
The program quits when the close icon or menu item is requested.
\bcode\begin{verbatim}
import stdwin
from stdwinevents import *
def main():
mywin = stdwin.open('Hello')
#
while 1:
(type, win, detail) = stdwin.getevent()
if type == WE_DRAW:
draw = win.begindrawing()
draw.text((0, 0), 'Hello, world')
del draw
elif type == WE_CLOSE:
break
main()
\end{verbatim}\ecode
\section{Standard Module \sectcode{stdwinevents}}
\stmodindex{stdwinevents}
This module defines constants used by STDWIN for event types
(\code{WE_ACTIVATE} etc.), command codes (\code{WC_LEFT} etc.)
and selection types (\code{WS_PRIMARY} etc.).
Read the file for details.
Suggested usage is
\bcode\begin{verbatim}
>>> from stdwinevents import *
>>>
\end{verbatim}\ecode
\section{Standard Module \sectcode{rect}}
\stmodindex{rect}
This module contains useful operations on rectangles.
A rectangle is defined as in module
\code{stdwin}:
a pair of points, where a point is a pair of integers.
For example, the rectangle
\bcode\begin{verbatim}
(10, 20), (90, 80)
\end{verbatim}\ecode
is a rectangle whose left, top, right and bottom edges are 10, 20, 90
and 80, respectively.
Note that the positive vertical axis points down (as in
\code{stdwin}).
The module defines the following objects:
\renewcommand{\indexsubitem}{(in module rect)}
\begin{excdesc}{error}
The exception raised by functions in this module when they detect an
error.
The exception argument is a string describing the problem in more
detail.
\end{excdesc}
\begin{datadesc}{empty}
The rectangle returned when some operations return an empty result.
This makes it possible to quickly check whether a result is empty:
\bcode\begin{verbatim}
>>> import rect
>>> r1 = (10, 20), (90, 80)
>>> r2 = (0, 0), (10, 20)
>>> r3 = rect.intersect([r1, r2])
>>> if r3 is rect.empty: print 'Empty intersection'
Empty intersection
>>>
\end{verbatim}\ecode
\end{datadesc}
\begin{funcdesc}{is_empty}{r}
Returns true if the given rectangle is empty.
A rectangle
\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})}
is empty if
\iftexi
\code{\var{left} >= \var{right}} or \code{\var{top} => \var{bottom}}.
\else
$\var{left} \geq \var{right}$ or $\var{top} \geq \var{bottom}$.
%%JHXXX{\em left~$\geq$~right} or {\em top~$\leq$~bottom}.
\fi
\end{funcdesc}
\begin{funcdesc}{intersect}{list}
Returns the intersection of all rectangles in the list argument.
It may also be called with a tuple argument.
Raises
\code{rect.error}
if the list is empty.
Returns
\code{rect.empty}
if the intersection of the rectangles is empty.
\end{funcdesc}
\begin{funcdesc}{union}{list}
Returns the smallest rectangle that contains all non-empty rectangles in
the list argument.
It may also be called with a tuple argument or with two or more
rectangles as arguments.
Returns
\code{rect.empty}
if the list is empty or all its rectangles are empty.
\end{funcdesc}
\begin{funcdesc}{pointinrect}{point\, rect}
Returns true if the point is inside the rectangle.
By definition, a point
\code{(\var{h}, \var{v})}
is inside a rectangle
\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})} if
\iftexi
\code{\var{left} <= \var{h} < \var{right}} and
\code{\var{top} <= \var{v} < \var{bottom}}.
\else
$\var{left} \leq \var{h} < \var{right}$ and
$\var{top} \leq \var{v} < \var{bottom}$.
\fi
\end{funcdesc}
\begin{funcdesc}{inset}{rect\, \(dh\, dv\)}
Returns a rectangle that lies inside the
\code{rect}
argument by
\var{dh}
pixels horizontally
and
\var{dv}
pixels
vertically.
If
\var{dh}
or
\var{dv}
is negative, the result lies outside
\var{rect}.
\end{funcdesc}
\begin{funcdesc}{rect2geom}{rect}
Converts a rectangle to geometry representation:
\code{(\var{left}, \var{top}), (\var{width}, \var{height})}.
\end{funcdesc}
\begin{funcdesc}{geom2rect}{geom}
Converts a rectangle given in geometry representation back to the
standard rectangle representation
\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})}.
\end{funcdesc}
\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.)
\chapter{SUNOS ONLY}
The modules described in this chapter provide interfaces to features
that are unique to the SunOS operating system (versions 4 and 5; the
latter is also known as SOLARIS version 2).
\section{Built-in module \sectcode{sunaudiodev}}
\bimodindex{sunaudiodev}
This module allows you to access the sun audio interface. The sun
audio hardware is capable of recording and playing back audio data
in U-LAW format with a sample rate of 8K per second. A full
description can be gotten with \samp{man audio}.
The module defines the following variables and functions:
\renewcommand{\indexsubitem}{(in module sunaudiodev)}
\begin{excdesc}{error}
This exception is raised on all errors. The argument is a string
describing what went wrong.
\end{excdesc}
\begin{funcdesc}{open}{mode}
This function opens the audio device and returns a sun audio device
object. This object can then be used to do I/O on. The \var{mode} parameter
is one of \code{'r'} for record-only access, \code{'w'} for play-only
access, \code{'rw'} for both and \code{'control'} for access to the
control device. Since only one process is allowed to have the recorder
or player open at the same time it is a good idea to open the device
only for the activity needed. See the audio manpage for details.
\end{funcdesc}
\subsection{Audio device object methods}
The audio device objects are returned by \code{open} define the
following methods (except \code{control} objects which only provide
getinfo, setinfo and drain):
\renewcommand{\indexsubitem}{(audio device method)}
\begin{funcdesc}{close}{}
This method explicitly closes the device. It is useful in situations
where deleting the object does not immediately close it since there
are other references to it. A closed device should not be used again.
\end{funcdesc}
\begin{funcdesc}{drain}{}
This method waits until all pending output is processed and then returns.
Calling this method is often not necessary: destroying the object will
automatically close the audio device and this will do an implicit drain.
\end{funcdesc}
\begin{funcdesc}{flush}{}
This method discards all pending output. It can be used avoid the
slow response to a user's stop request (due to buffering of up to one
second of sound).
\end{funcdesc}
\begin{funcdesc}{getinfo}{}
This method retrieves status information like input and output volume,
etc. and returns it in the form of
an audio status object. This object has no methods but it contains a
number of attributes describing the current device status. The names
and meanings of the attributes are described in
\file{/usr/include/sun/audioio.h} and in the audio man page. Member names
are slightly different from their C counterparts: a status object is
only a single structure. Members of the \code{play} substructure have
\samp{o_} prepended to their name and members of the \code{record}
structure have \samp{i_}. So, the C member \code{play.sample_rate} is
accessed as \code{o_sample_rate}, \code{record.gain} as \code{i_gain}
and \code{monitor_gain} plainly as \code{monitor_gain}.
\end{funcdesc}
\begin{funcdesc}{ibufcount}{}
This method returns the number of samples that are buffered on the
recording side, i.e.
the program will not block on a \code{read} call of so many samples.
\end{funcdesc}
\begin{funcdesc}{obufcount}{}
This method returns the number of samples buffered on the playback
side. Unfortunately, this number cannot be used to determine a number
of samples that can be written without blocking since the kernel
output queue length seems to be variable.
\end{funcdesc}
\begin{funcdesc}{read}{size}
This method reads \var{size} samples from the audio input and returns
them as a python string. The function blocks until enough data is available.
\end{funcdesc}
\begin{funcdesc}{setinfo}{status}
This method sets the audio device status parameters. The \var{status}
parameter is an device status object as returned by \code{getinfo} and
possibly modified by the program.
\end{funcdesc}
\begin{funcdesc}{write}{samples}
Write is passed a python string containing audio samples to be played.
If there is enough buffer space free it will immedeately return,
otherwise it will block.
\end{funcdesc}
There is a companion module, \code{SUNAUDIODEV}, which defines useful
symbolic constants like \code{MIN_GAIN}, \code{MAX_GAIN},
\code{SPEAKER}, etc. The names of
the constants are the same names as used in the C include file
\file{<sun/audioio.h>}, with the leading string \samp{AUDIO_} stripped.
Useability of the control device is limited at the moment, since there
is no way to use the 'wait for something to happen' feature the device
provides. This is because that feature makes heavy use of signals, and
these do not map too well onto Python.
\section{Built-in Module \sectcode{sys}}
\bimodindex{sys}
This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
It is always available.
\renewcommand{\indexsubitem}{(in module sys)}
\begin{datadesc}{argv}
The list of command line arguments passed to a Python script.
\code{sys.argv[0]} is the script name.
If no script name was passed to the Python interpreter,
\code{sys.argv} is empty.
\end{datadesc}
\begin{datadesc}{builtin_module_names}
A list of strings giving the names of all modules that are compiled
into this Python interpreter. (This information is not available in
any other way --- \code{sys.modules.keys()} only lists the imported
modules.)
\end{datadesc}
\begin{datadesc}{exc_type}
\dataline{exc_value}
\dataline{exc_traceback}
These three variables are not always defined; they are set when an
exception handler (an \code{except} clause of a \code{try} statement) is
invoked. Their meaning is: \code{exc_type} gets the exception type of
the exception being handled; \code{exc_value} gets the exception
parameter (its \dfn{associated value} or the second argument to
\code{raise}); \code{exc_traceback} gets a traceback object which
encapsulates the call stack at the point where the exception
originally occurred.
\end{datadesc}
\begin{funcdesc}{exit}{n}
Exit from Python with numeric exit status \var{n}. This is
implemented by raising the \code{SystemExit} exception, so cleanup
actions specified by \code{finally} clauses of \code{try} statements
are honored, and it is possible to catch the exit attempt at an outer
level.
\end{funcdesc}
\begin{datadesc}{exitfunc}
This value is not actually defined by the module, but can be set by
the user (or by a program) to specify a clean-up action at program
exit. When set, it should be a parameterless function. This function
will be called when the interpreter exits in any way (but not when a
fatal error occurs: in that case the interpreter's internal state
cannot be trusted).
\end{datadesc}
\begin{datadesc}{last_type}
\dataline{last_value}
\dataline{last_traceback}
These three variables are not always defined; they are set when an
exception is not handled and the interpreter prints an error message
and a stack traceback. Their intended use is to allow an interactive
user to import a debugger module and engage in post-mortem debugging
without having to re-execute the command that cause the error (which
may be hard to reproduce). The meaning of the variables is the same
as that of \code{exc_type}, \code{exc_value} and \code{exc_tracaback},
respectively.
\end{datadesc}
\begin{datadesc}{modules}
Gives the list of modules that have already been loaded.
This can be manipulated to force reloading of modules and other tricks.
\end{datadesc}
\begin{datadesc}{path}
A list of strings that specifies the search path for modules.
Initialized from the environment variable \code{PYTHONPATH}, or an
installation-dependent default.
\end{datadesc}
\begin{datadesc}{ps1}
\dataline{ps2}
Strings specifying the primary and secondary prompt of the
interpreter. These are only defined if the interpreter is in
interactive mode. Their initial values in this case are
\code{'>>> '} and \code{'... '}.
\end{datadesc}
\begin{funcdesc}{settrace}{tracefunc}
Set the system's trace function, which allows you to implement a
Python source code debugger in Python. The standard modules
\code{pdb} and \code{wdb} are such debuggers; the difference is that
\code{wdb} uses windows and needs STDWIN, while \code{pdb} has a
line-oriented interface not unlike dbx. See the file \file{pdb.doc}
in the Python library source directory for more documentation (both
about \code{pdb} and \code{sys.trace}).
\end{funcdesc}
\ttindex{pdb}
\ttindex{wdb}
\index{trace function}
\begin{funcdesc}{setprofile}{profilefunc}
Set the system's profile function, which allows you to implement a
Python source code profiler in Python. The system's profile function
is called similarly to the system's trace function (see
\code{sys.settrace}), but it isn't called for each executed line of
code (only on call and return and when an exception occurs). Also,
its return value is not used, so it can just return \code{None}.
\end{funcdesc}
\index{profile function}
\begin{datadesc}{stdin}
\dataline{stdout}
\dataline{stderr}
File objects corresponding to the interpreter's standard input,
output and error streams. \code{sys.stdin} is used for all
interpreter input except for scripts but including calls to
\code{input()} and \code{raw_input()}. \code{sys.stdout} is used
for the output of \code{print} and expression statements and for the
prompts of \code{input()} and \code{raw_input()}. The interpreter's
own prompts and (almost all of) its error messages go to
\code{sys.stderr}. \code{sys.stdout} and \code{sys.stderr} needn't
be built-in file objects: any object is acceptable as long as it has
a \code{write} method that takes a string argument.
\end{datadesc}
\begin{datadesc}{tracebacklimit}
When this variable is set to an integer value, it determines the
maximum number of levels of traceback information printed when an
unhandled exception occurs. The default is 1000. When set to 0 or
less, all traceback information is suppressed and only the exception
type and value are printed.
\end{datadesc}
\section{Built-in Module \sectcode{thread}}
\bimodindex{thread}
This module provides low-level primitives for working with multiple
threads (a.k.a. \dfn{light-weight processes} or \dfn{tasks}) --- multiple
threads of control sharing their global data space. For
synchronization, simple locks (a.k.a. \dfn{mutexes} or \dfn{binary
semaphores}) are provided.
The module is optional and supported on SGI and Sun Sparc systems only.
It defines the following constant and functions:
\renewcommand{\indexsubitem}{(in module thread)}
\begin{excdesc}{error}
Raised on thread-specific errors.
\end{excdesc}
\begin{funcdesc}{start_new_thread}{func\, arg}
Start a new thread. The thread executes the function \var{func}
with the argument list \var{arg} (which must be a tuple). When the
function returns, the thread silently exits. When the function raises
terminates with an unhandled exception, a stack trace is printed and
then the thread exits (but other threads continue to run).
\end{funcdesc}
\begin{funcdesc}{exit_thread}{}
Exit the current thread silently. Other threads continue to run.
\strong{Caveat:} code in pending \code{finally} clauses is not executed.
\end{funcdesc}
\begin{funcdesc}{exit_prog}{status}
Exit all threads and report the value of the integer argument
\var{status} as the exit status of the entire program.
\strong{Caveat:} code in pending \code{finally} clauses, in this thread
or in other threads, is not executed.
\end{funcdesc}
\begin{funcdesc}{allocate_lock}{}
Return a new lock object. Methods of locks are described below. The
lock is initially unlocked.
\end{funcdesc}
Lock objects have the following methods:
\renewcommand{\indexsubitem}{(lock method)}
\begin{funcdesc}{acquire}{waitflag}
Without the optional argument, this method acquires the lock
unconditionally, if necessary waiting until it is released by another
thread (only one thread at a time can acquire a lock --- that's their
reason for existence), and returns \code{None}. If the integer
\var{waitflag} argument is present, the action depends on its value:
if it is zero, the lock is only acquired if it can be acquired
immediately without waiting, while if it is nonzero, the lock is
acquired unconditionally as before. If an argument is present, the
return value is 1 if the lock is acquired successfully, 0 if not.
\end{funcdesc}
\begin{funcdesc}{release}{}
Releases the lock. The lock must have been acquired earlier, but not
necessarily by the same thread.
\end{funcdesc}
\begin{funcdesc}{locked}{}
Return the status of the lock: 1 if it has been acquired by some
thread, 0 if not.
\end{funcdesc}
{\bf Caveats:}
\begin{itemize}
\item
Threads interact strangely with interrupts: the
\code{KeyboardInterrupt} exception will be received by an arbitrary
thread.
\item
Calling \code{sys.exit(\var{status})} or executing
\code{raise SystemExit, \var{status}} is almost equivalent to calling
\code{thread.exit_prog(\var{status})}, except that the former ways of
exiting the entire program do honor \code{finally} clauses in the
current thread (but not in other threads).
\item
Not all built-in functions that may block waiting for I/O allow other
threads to run, although the most popular ones (\code{sleep},
\code{read}, \code{select}) work as expected.
\end{itemize}
\section{Built-in Module \sectcode{time}}
\bimodindex{time}
This module provides various time-related functions.
It is always available. (On some systems, not all functions may
exist; e.g. the ``milli'' variants can't always be implemented.)
An explanation of some terminology and conventions is in order.
\begin{itemize}
\item
The ``epoch'' is the point where the time starts. On January 1st that
year, at 0 hours, the ``time since the epoch'' is zero. For UNIX, the
epoch is 1970. To find out what the epoch is, look at the first
element of \code{gmtime(0)}.
\item
UTC is Coordinated Universal Time (formerly known as Greenwich Mean
Time). The acronym UTC is not a mistake but a compromise between
English and French.
\item
DST is Daylight Saving Time, an adjustment of the timezone by
(usually) one hour during part of the year. DST rules are magic
(determined by local law) and can change from year to year. The C
library has a table containing the local rules (often it is read from
a system file for flexibility) and is the only source of True Wisdom
in this respect.
\item
The precision of the various real-time functions may be less than
suggested by the units in which their value or argument is expressed.
E.g. on most UNIX systems, the clock ``ticks'' only every 1/50th or
1/100th of a second, and on the Mac, it ticks 60 times a second.
\end{itemize}
Functions and data items are:
\renewcommand{\indexsubitem}{(in module time)}
\begin{datadesc}{altzone}
The offset of the local DST timezone, in seconds west of the 0th
meridian, if one is defined. Only use this if \code{daylight} is
nonzero.
\end{datadesc}
\begin{funcdesc}{asctime}{tuple}
Convert a tuple representing a time as returned by \code{gmtime()} or
\code{localtime()} to a 24-character string of the following form:
\code{'Sun Jun 20 23:21:05 1993'}. Note: unlike the C function of
the same name, there is no trailing newline.
\end{funcdesc}
\begin{funcdesc}{ctime}{secs}
Convert a time expressed in seconds since the epoch to a string
representing local time. \code{ctime(t)} is equivalent to
\code{asctime(localtime(t))}.
\end{funcdesc}
\begin{datadesc}{daylight}
Nonzero if a DST timezone is defined.
\end{datadesc}
\begin{funcdesc}{gmtime}{secs}
Convert a time expressed in seconds since the epoch to a tuple of 9
integers, in UTC: year (e.g. 1993), month (1-12), day (1-31), hour
(0-23), minute (0-59), second (0-59), weekday (0-6, monday is 0),
julian day (1-366), dst flag (always zero). Fractions of a second are
ignored. Note subtle differences with the C function of this name.
\end{funcdesc}
\begin{funcdesc}{localtime}{secs}
Like \code{gmtime} but converts to local time. The dst flag is set
to 1 when DST applies to the given time.
\end{funcdesc}
\begin{funcdesc}{millisleep}{msecs}
Suspend execution for the given number of milliseconds. (Obsolete,
you can now use use \code{sleep} with a floating point argument.)
\end{funcdesc}
\begin{funcdesc}{millitimer}{}
Return the number of milliseconds of real time elapsed since some
point in the past that is fixed per execution of the python
interpreter (but may change in each following run). The return value
may be negative, and it may wrap around.
\end{funcdesc}
\begin{funcdesc}{mktime}{tuple}
This is the inverse function of \code{localtime}. Its argument is the
full 9-tuple (since the dst flag is needed). It returns an integer.
\end{funcdesc}
\begin{funcdesc}{sleep}{secs}
Suspend execution for the given number of seconds. The argument may
be a floating point number to indicate a more precise sleep time.
\end{funcdesc}
\begin{funcdesc}{time}{}
Return the time as a floating point number expressed in seconds since
the epoch, in UTC. Note that even though the time is always returned
as a floating point number, not all systems provide time with a better
precision than 1 second. An alternative for measuring precise
intervals is \code{millitimer}.
\end{funcdesc}
\begin{datadesc}{timezone}
The offset of the local (non-DST) timezone, in seconds west of the 0th
meridian (i.e. negative in most of Western Europe, positive in the US,
zero in the UK).
\end{datadesc}
\begin{datadesc}{tzname}
A tuple of two strings: the first is the name of the local non-DST
timezone, the second is the name of the local DST timezone. If no DST
timezone is defined, the second string should not be used.
\end{datadesc}
\section{Built-in Types}
The following sections describe the standard types that are built into
the interpreter. These are the numeric types, sequence types, and
several others, including types themselves. There is no explicit
Boolean type; use integers instead.
\indexii{built-in}{types}
\indexii{Boolean}{type}
Some operations are supported by several object types; in particular,
all objects can be compared, tested for truth value, and converted to
a string (with the \code{`{\rm \ldots}`} notation). The latter conversion is
implicitly used when an object is written by the \code{print} statement.
\stindex{print}
\subsection{Truth Value Testing}
Any object can be tested for truth value, for use in an \code{if} or
\code{while} condition or as operand of the Boolean operations below.
The following values are false:
\stindex{if}
\stindex{while}
\indexii{truth}{value}
\indexii{Boolean}{operations}
\index{false}
\begin{itemize}
\renewcommand{\indexsubitem}{(Built-in object)}
\item \code{None}
\ttindex{None}
\item zero of any numeric type, e.g., \code{0}, \code{0L}, \code{0.0}.
\item any empty sequence, e.g., \code{''}, \code{()}, \code{[]}.
\item any empty mapping, e.g., \code{\{\}}.
\end{itemize}
\emph{All} other values are true --- so objects of many types are
always true.
\index{true}
\subsection{Boolean Operations}
These are the Boolean operations:
\indexii{Boolean}{operations}
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{\var{x} or \var{y}}{if \var{x} is false, then \var{y}, else \var{x}}{(1)}
\lineiii{\var{x} and \var{y}}{if \var{x} is false, then \var{x}, else \var{y}}{(1)}
\lineiii{not \var{x}}{if \var{x} is false, then \code{1}, else \code{0}}{}
\end{tableiii}
\opindex{and}
\opindex{or}
\opindex{not}
\noindent
Notes:
\begin{description}
\item[(1)]
These only evaluate their second argument if needed for their outcome.
\end{description}
\subsection{Comparisons}
Comparison operations are supported by all objects:
\begin{tableiii}{|c|l|c|}{code}{Operation}{Meaning}{Notes}
\lineiii{<}{strictly less than}{}
\lineiii{<=}{less than or equal}{}
\lineiii{>}{strictly greater than}{}
\lineiii{>=}{greater than or equal}{}
\lineiii{==}{equal}{}
\lineiii{<>}{not equal}{(1)}
\lineiii{!=}{not equal}{(1)}
\lineiii{is}{object identity}{}
\lineiii{is not}{negated object identity}{}
\end{tableiii}
\indexii{operator}{comparison}
\opindex{==} % XXX *All* others have funny characters < ! >
\opindex{is}
\opindex{is not}
\noindent
Notes:
\begin{description}
\item[(1)]
\code{<>} and \code{!=} are alternate spellings for the same operator.
(I couldn't choose between \ABC{} and \C{}! :-)
\indexii{\ABC{}}{language}
\indexii{\C{}}{language}
\end{description}
Objects of different types, except different numeric types, never
compare equal; such objects are ordered consistently but arbitrarily
(so that sorting a heterogeneous array yields a consistent result).
Furthermore, some types (e.g., windows) support only a degenerate
notion of comparison where any two objects of that type are unequal.
Again, such objects are ordered arbitrarily but consistently.
\indexii{types}{numeric}
\indexii{objects}{comparing}
(Implementation note: objects of different types except numbers are
ordered by their type names; objects of the same types that don't
support proper comparison are ordered by their address.)
Two more operations with the same syntactic priority, \code{in} and
\code{not in}, are supported only by sequence types (below).
\opindex{in}
\opindex{not in}
\subsection{Numeric Types}
There are three numeric types: \dfn{plain integers}, \dfn{long integers}, and
\dfn{floating point numbers}. Plain integers (also just called \dfn{integers})
are implemented using \code{long} in \C{}, which gives them at least 32
bits of precision. Long integers have unlimited precision. Floating
point numbers are implemented using \code{double} in \C{}. All bets on
their precision are off unless you happen to know the machine you are
working with.
\indexii{numeric}{types}
\indexii{integer}{types}
\indexii{integer}{type}
\indexiii{long}{integer}{type}
\indexii{floating point}{type}
\indexii{\C{}}{language}
Numbers are created by numeric literals or as the result of built-in
functions and operators. Unadorned integer literals (including hex
and octal numbers) yield plain integers. Integer literals with an \samp{L}
or \samp{l} suffix yield long integers
(\samp{L} is preferred because \code{1l} looks too much like eleven!).
Numeric literals containing a decimal point or an exponent sign yield
floating point numbers.
\indexii{numeric}{literals}
\indexii{integer}{literals}
\indexiii{long}{integer}{literals}
\indexii{floating point}{literals}
\indexii{hexadecimal}{literals}
\indexii{octal}{literals}
Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
``smaller'' type is converted to that of the other, where plain
integer is smaller than long integer is smaller than floating point.
Comparisons between numbers of mixed type use the same rule.%
\footnote{As a consequence, the list \code{[1, 2]} is considered equal
to \code{[1.0, 2.0]}, and similar for tuples.}
The functions \code{int()}, \code{long()} and \code{float()} can be used
to coerce numbers to a specific type.
\index{arithmetic}
\bifuncindex{int}
\bifuncindex{long}
\bifuncindex{float}
All numeric types support the following operations:
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{abs(\var{x})}{absolute value of \var{x}}{}
\lineiii{int(\var{x})}{\var{x} converted to integer}{(1)}
\lineiii{long(\var{x})}{\var{x} converted to long integer}{(1)}
\lineiii{float(\var{x})}{\var{x} converted to floating point}{}
\lineiii{-\var{x}}{\var{x} negated}{}
\lineiii{+\var{x}}{\var{x} unchanged}{}
\lineiii{\var{x} + \var{y}}{sum of \var{x} and \var{y}}{}
\lineiii{\var{x} - \var{y}}{difference of \var{x} and \var{y}}{}
\lineiii{\var{x} * \var{y}}{product of \var{x} and \var{y}}{}
\lineiii{\var{x} / \var{y}}{quotient of \var{x} and \var{y}}{(2)}
\lineiii{\var{x} \%{} \var{y}}{remainder of \code{\var{x} / \var{y}}}{}
\lineiii{divmod(\var{x}, \var{y})}{the pair \code{(\var{x} / \var{y}, \var{x} \%{} \var{y})}}{(3)}
\lineiii{pow(\var{x}, \var{y})}{\var{x} to the power \var{y}}{}
\end{tableiii}
\indexiii{operations on}{numeric}{types}
\noindent
Notes:
\begin{description}
\item[(1)]
Conversion from floating point to (long or plain) integer may round or
% XXXJH xref here
truncate as in \C{}; see functions \code{floor} and \code{ceil} in module
\code{math} for well-defined conversions.
\indexii{numeric}{conversions}
\ttindex{math}
\indexii{\C{}}{language}
\item[(2)]
For (plain or long) integer division, the result is an integer; it
always truncates towards zero.
% XXXJH integer division is better defined nowadays
\indexii{integer}{division}
\indexiii{long}{integer}{division}
\item[(3)]
See the section on built-in functions for an exact definition.
\end{description}
% XXXJH exceptions: overflow (when? what operations?) zerodivision
\subsubsection{Bit-string Operations on Integer Types.}
Plain and long integer types support additional operations that make
sense only for bit-strings. Negative numbers are treated as their 2's
complement value:
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{\~\var{x}}{the bits of \var{x} inverted}{}
\lineiii{\var{x} \^{} \var{y}}{bitwise \dfn{exclusive or} of \var{x} and \var{y}}{}
\lineiii{\var{x} \&{} \var{y}}{bitwise \dfn{and} of \var{x} and \var{y}}{}
\lineiii{\var{x} | \var{y}}{bitwise \dfn{or} of \var{x} and \var{y}}{}
\lineiii{\var{x} << \var{n}}{\var{x} shifted left by \var{n} bits}{}
\lineiii{\var{x} >> \var{n}}{\var{x} shifted right by \var{n} bits}{}
\end{tableiii}
% XXXJH what's `left'? `right'? maybe better use lsb or msb or something
\indexiii{operations on}{integer}{types}
\indexii{bit-string}{operations}
\indexii{shifting}{operations}
\indexii{masking}{operations}
\subsection{Sequence Types}
There are three sequence types: strings, lists and tuples.
Strings literals are written in single quotes: \code{'xyzzy'}.
Lists are constructed with square brackets,
separating items with commas:
\code{[a, b, c]}.
Tuples are constructed by the comma operator
(not within square brackets), with or without enclosing parentheses,
but an empty tuple must have the enclosing parentheses, e.g.,
\code{a, b, c} or \code{()}. A single item tuple must have a trailing comma,
e.g., \code{(d,)}.
\indexii{sequence}{types}
\indexii{string}{type}
\indexii{tuple}{type}
\indexii{list}{type}
Sequence types support the following operations (\var{s} and \var{t} are
sequences of the same type; \var{n}, \var{i} and \var{j} are integers):
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{len(\var{s})}{length of \var{s}}{}
\lineiii{min(\var{s})}{smallest item of \var{s}}{}
\lineiii{max(\var{s})}{largest item of \var{s}}{}
\lineiii{\var{x} in \var{s}}{\code{1} if an item of \var{s} is equal to \var{x}, else \code{0}}{}
\lineiii{\var{x} not in \var{s}}{\code{0} if an item of \var{s} is equal to \var{x}, else \code{1}}{}
\lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{}
\lineiii{\var{s} * \var{n}{\rm ,} \var{n} * \var{s}}{\var{n} copies of \var{s} concatenated}{}
\lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(1)}
\lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(1), (2)}
\end{tableiii}
\indexiii{operations on}{sequence}{types}
\bifuncindex{len}
\bifuncindex{min}
\bifuncindex{max}
\indexii{concatenation}{operation}
\indexii{repetition}{operation}
\indexii{subscript}{operation}
\indexii{slice}{operation}
\opindex{in}
\opindex{not in}
\noindent
Notes:
% XXXJH all TeX-math expressions replaced by python-syntax expressions
\begin{description}
\item[(1)] If \var{i} or \var{j} is negative, the index is relative to
the end of the string, i.e., \code{len(\var{s}) + \var{i}} or
\code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is
still \code{0}.
\item[(2)] The slice of \var{s} from \var{i} to \var{j} is defined as
the sequence of items with index \var{k} such that \code{\var{i} <=
\var{k} < \var{j}}. If \var{i} or \var{j} is greater than
\code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted,
use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If
\var{i} is greater than or equal to \var{j}, the slice is empty.
\end{description}
\subsubsection{More String Operations.}
String objects have one unique built-in operation: the \code{\%}
operator (modulo) with a string left argument interprets this string
as a C sprintf format string to be applied to the right argument, and
returns the string resulting from this formatting operation.
Unless the format string requires exactly one argument, the right
argument should be a tuple of the correct size. The following format
characters are understood: \%, c, s, i, d, u, o, x, X, e, E, f, g, G.
Width and precision may be a * to specify that an integer argument
specifies the actual width or precision. The flag characters -, +,
blank, \# and 0 are understood. The size specifiers h, l or L may be
present but are ignored. The ANSI features \code{\%p} and \code{\%n}
are not supported. Since Python strings have an explicit length,
\code{\%s} conversions don't assume that \code{'\\0'} is the end of
the string.
For safety reasons, huge floating point precisions are truncated;
\code{\%f} conversions for huge numbers are replaced by
\code{\%g} conversions. All other errors raise exceptions.
Additional string operations are defined in standard module
\code{string} and in built-in module \code{regex}.
\index{string}
\index{regex}
\subsubsection{Mutable Sequence Types.}
List objects support additional operations that allow in-place
modification of the object.
These operations would be supported by other mutable sequence types
(when added to the language) as well.
Strings and tuples are immutable sequence types and such objects cannot
be modified once created.
The following operations are defined on mutable sequence types (where
\var{x} is an arbitrary object):
\indexiii{mutable}{sequence}{types}
\indexii{list}{type}
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{\var{s}[\var{i}] = \var{x}}
{item \var{i} of \var{s} is replaced by \var{x}}{}
\lineiii{\var{s}[\var{i}:\var{j}] = \var{t}}
{slice of \var{s} from \var{i} to \var{j} is replaced by \var{t}}{}
\lineiii{del \var{s}[\var{i}:\var{j}]}
{same as \code{\var{s}[\var{i}:\var{j}] = []}}{}
\lineiii{\var{s}.append(\var{x})}
{same as \code{\var{s}[len(\var{x}):len(\var{x})] = [\var{x}]}}{}
\lineiii{\var{s}.count(\var{x})}
{return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{}
\lineiii{\var{s}.index(\var{x})}
{return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(1)}
\lineiii{\var{s}.insert(\var{i}, \var{x})}
{same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]}}{}
\lineiii{\var{s}.remove(\var{x})}
{same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(1)}
\lineiii{\var{s}.reverse()}
{reverses the items of \var{s} in place}{}
\lineiii{\var{s}.sort()}
{permutes the items of \var{s} to satisfy
\code{\var{s}[\var{i}] <= \var{s}[\var{j}]},
for \code{\var{i} < \var{j}}}{(2)}
\end{tableiii}
\indexiv{operations on}{mutable}{sequence}{types}
\indexiii{operations on}{sequence}{types}
\indexiii{operations on}{list}{type}
\indexii{subscript}{assignment}
\indexii{slice}{assignment}
\stindex{del}
\renewcommand{\indexsubitem}{(list method)}
\ttindex{append}
\ttindex{count}
\ttindex{index}
\ttindex{insert}
\ttindex{remove}
\ttindex{reverse}
\ttindex{sort}
\noindent
Notes:
\begin{description}
\item[(1)] Raises an exception when \var{x} is not found in \var{s}.
\item[(2)] The \code{sort()} method takes an optional argument
specifying a comparison function of two arguments (list items) which
should return \code{-1}, \code{0} or \code{1} depending on whether the
first argument is considered smaller than, equal to, or larger than the
second argument. Note that this slows the sorting process down
considerably; e.g. to sort an array in reverse order it is much faster
to use calls to \code{sort()} and \code{reverse()} than to use
\code{sort()} with a comparison function that reverses the ordering of
the elements.
\end{description}
\subsection{Mapping Types}
A \dfn{mapping} object maps values of one type (the key type) to
arbitrary objects. Mappings are mutable objects. There is currently
only one mapping type, the \dfn{dictionary}. A dictionary's keys are
almost arbitrary values. The only types of values not acceptable as
keys are values containing lists or dictionaries or other mutable
types that are compared by value rather than by object identity.
Numeric types used for keys obey the normal rules for numeric
comparison: if two numbers compare equal (e.g. 1 and 1.0) then they
can be used interchangeably to index the same dictionary entry.
\indexii{mapping}{types}
\indexii{dictionary}{type}
Dictionaries are created by placing a comma-separated list of
\code{\var{key}: \var{value}} pairs within braces, for example:
\code{\{'jack': 4098, 'sjoerd: 4127\}} or
\code{\{4098: 'jack', 4127: 'sjoerd\}}.
The following operations are defined on mappings (where \var{a} is a
mapping, \var{k} is a key and \var{x} is an arbitrary object):
\begin{tableiii}{|c|l|c|}{code}{Operation}{Result}{Notes}
\lineiii{len(\var{a})}{the number of items in \var{a}}{}
\lineiii{\var{a}[\var{k}]}{the item of \var{a} with key \var{k}}{(1)}
\lineiii{\var{a}[\var{k}] = \var{x}}{set \code{\var{a}[\var{k}]} to \var{x}}{}
\lineiii{del \var{a}[\var{k}]}{remove \code{\var{a}[\var{k}]} from \var{a}}{(1)}
\lineiii{\var{a}.items()}{a copy of \var{a}'s list of (key, item) pairs}{(2)}
\lineiii{\var{a}.keys()}{a copy of \var{a}'s list of keys}{(2)}
\lineiii{\var{a}.values()}{a copy of \var{a}'s list of values}{(2)}
\lineiii{\var{a}.has_key(\var{k})}{\code{1} if \var{a} has a key \var{k}, else \code{0}}{}
\end{tableiii}
\indexiii{operations on}{mapping}{types}
\indexiii{operations on}{dictionary}{type}
\stindex{del}
\bifuncindex{len}
\renewcommand{\indexsubitem}{(dictionary method)}
\ttindex{keys}
\ttindex{has_key}
% XXXJH some lines above, you talk about `true', elsewhere you
% explicitely states \code{0} or \code{1}.
\noindent
Notes:
\begin{description}
\item[(1)] Raises an exception if \var{k} is not in the map.
\item[(2)] Keys and values are listed in random order, but at any
moment the ordering of the \code{keys()}, \code{values()} and
\code{items()} lists is the consistent with each other.
\end{description}
\subsection{Other Built-in Types}
The interpreter supports several other kinds of objects.
Most of these support only one or two operations.
\subsubsection{Modules.}
The only special operation on a module is attribute access:
\code{\var{m}.\var{name}}, where \var{m} is a module and \var{name} accesses
a name defined in \var{m}'s symbol table. Module attributes can be
assigned to. (Note that the \code{import} statement is not, strictly
spoken, an operation on a module object; \code{import \var{foo}} does not
require a module object named \var{foo} to exist, rather it requires
an (external) \emph{definition} for a module named \var{foo}
somewhere.)
A special member of every module is \code{__dict__}.
This is the dictionary containing the module's symbol table.
Modifying this dictionary will actually change the module's symbol
table, but direct assignment to the \code{__dict__} attribute is not
possible (i.e., you can write \code{\var{m}.__dict__['a'] = 1}, which
defines \code{\var{m}.a} to be \code{1}, but you can't write \code{\var{m}.__dict__ = \{\}}.
Modules are written like this: \code{<module 'sys'>}.
\subsubsection{Classes and Class Instances.}
% XXXJH cross ref here
(See the Python Reference Manual for these.)
\subsubsection{Functions.}
Function objects are created by function definitions. The only
operation on a function object is to call it:
\code{\var{func}(\var{argument-list})}.
There are really two flavors of function objects: built-in functions
and user-defined functions. Both support the same operation (to call
the function), but the implementation is different, hence the
different object types.
The implementation adds two special read-only attributes:
\code{\var{f}.func_code} is a function's \dfn{code object} (see below) and
\code{\var{f}.func_globals} is the dictionary used as the function's
global name space (this is the same as \code{\var{m}.__dict__} where
\var{m} is the module in which the function \var{f} was defined).
\subsubsection{Methods.}
Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods (such as \code{append()} on
lists) and class instance methods. Built-in methods are described
with the types that support them.
The implementation adds two special read-only attributes to class
instance methods: \code{\var{m}.im_self} is the object whose method this
is, and \code{\var{m}.im_func} is the function implementing the method.
Calling \code{\var{m}(\var{arg-1}, \var{arg-2}, {\rm \ldots},
\var{arg-n})} is completely equivalent to calling
\code{\var{m}.im_func(\var{m}.im_self, \var{arg-1}, \var{arg-2}, {\rm
\ldots}, \var{arg-n})}.
(See the Python Reference Manual for more info.)
\subsubsection{Type Objects.}
Type objects represent the various object types. An object's type is
% XXXJH xref here
accessed by the built-in function \code{type()}. There are no special
operations on types.
Types are written like this: \code{<type 'int'>}.
\subsubsection{The Null Object.}
This object is returned by functions that don't explicitly return a
value. It supports no special operations. There is exactly one null
object, named \code{None} (a built-in name).
It is written as \code{None}.
\subsubsection{File Objects.}
File objects are implemented using \C{}'s \code{stdio} package and can be
% XXXJH xref here
created with the built-in function \code{open()} described under
Built-in Functions below.
When a file operation fails for an I/O-related reason, the exception
\code{IOError} is raised. This includes situations where the
operation is not defined for some reason, like \code{seek()} on a tty
device or writing a file opened for reading.
Files have the following methods:
\renewcommand{\indexsubitem}{(file method)}
\begin{funcdesc}{close}{}
Close the file. A closed file cannot be read or written anymore.
\end{funcdesc}
\begin{funcdesc}{flush}{}
Flush the internal buffer, like \code{stdio}'s \code{fflush()}.
\end{funcdesc}
\begin{funcdesc}{isatty}{}
Return \code{1} if the file is connected to a tty(-like) device, else
\code{0}.
\end{funcdesc}
\begin{funcdesc}{read}{size}
Read at most \var{size} bytes from the file (less if the read hits
\EOF{} or no more data is immediately available on a pipe, tty or
similar device). If the \var{size} argument is omitted, read all
data until \EOF{} is reached. The bytes are returned as a string
object. An empty string is returned when \EOF{} is encountered
immediately. (For certain files, like ttys, it makes sense to
continue reading after an \EOF{} is hit.)
\end{funcdesc}
\begin{funcdesc}{readline}{}
Read one entire line from the file. A trailing newline character is
kept in the string (but may be absent when a file ends with an
incomplete line). An empty string is returned when \EOF{} is hit
immediately. Note: unlike \code{stdio}'s \code{fgets()}, the returned
string contains null characters (\code{'\e 0'}) if they occurred in the
input.
\end{funcdesc}
\begin{funcdesc}{readlines}{}
Read until \EOF{} using \code{readline()} and return a list containing
the lines thus read.
\end{funcdesc}
\begin{funcdesc}{seek}{offset\, whence}
Set the file's current position, like \code{stdio}'s \code{fseek()}.
The \var{whence} argument is optional and defaults to \code{0}
(absolute file positioning); other values are \code{1} (seek
relative to the current position) and \code{2} (seek relative to the
file's end). There is no return value.
\end{funcdesc}
\begin{funcdesc}{tell}{}
Return the file's current position, like \code{stdio}'s \code{ftell()}.
\end{funcdesc}
\begin{funcdesc}{write}{str}
Write a string to the file. There is no return value.
\end{funcdesc}
\subsubsection{Internal Objects.}
(See the Python Reference Manual for these.)
\subsection{Special Attributes}
The implementation adds a few special read-only attributes to several
object types, where they are relevant:
\begin{itemize}
\item
\code{\var{x}.__dict__} is a dictionary of some sort used to store an
object's (writable) attributes;
\item
\code{\var{x}.__methods__} lists the methods of many built-in object types,
e.g., \code{[].__methods__} is
% XXXJH results in?, yields?, written down as an example
\code{['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort']};
\item
\code{\var{x}.__members__} lists data attributes;
\item
\code{\var{x}.__class__} is the class to which a class instance belongs;
\item
\code{\var{x}.__bases__} is the tuple of base classes of a class object.
\end{itemize}
\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}
\chapter{MACINTOSH ONLY}
The following modules are available on the Apple Macintosh only.
\section{Built-in module \sectcode{mac}}
\bimodindex{mac}
This module provides a subset of the operating system dependent
functionality provided by the optional built-in module \code{posix}.
It is best accessed through the more portable standard module
\code{os}.
The following functions are available in this module:
\code{chdir},
\code{getcwd},
\code{listdir},
\code{mkdir},
\code{rename},
\code{rmdir},
\code{stat},
\code{sync},
\code{unlink},
as well as the exception \code{error}.
\section{Standard module \sectcode{macpath}}
\stmodindex{macpath}
This module provides a subset of the pathname manipulation functions
available from the optional standard module \code{posixpath}. It is
best accessed through the more portable standard module \code{os}, as
\code{os.path}.
The following functions are available in this module:
\code{normcase},
\code{isabs},
\code{join},
\code{split},
\code{isdir},
\code{isfile},
\code{exists}.
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