Commit cda63cc8 authored by Fred Drake's avatar Fred Drake

Relocating file to Doc/lib/

parent bbe33c55
\documentclass{manual}
% NOTE: this file controls which chapters/sections of the library
% manual are actually printed. It is easy to customize your manual
% by commenting out sections that you're not interested in.
\title{Python Library Reference}
\input{boilerplate}
\makeindex % tell \index to actually write the
% .idx file
\makemodindex % ... and the module index as well.
\begin{document}
\maketitle
\input{copyright}
\begin{abstract}
\noindent
Python is an extensible, interpreted, object-oriented programming
language. It supports a wide range of applications, from simple text
processing scripts to interactive WWW browsers.
While the \emph{Python Reference Manual} describes the exact syntax and
semantics of the language, it does not describe the standard library
that is distributed with the language, and which greatly enhances its
immediate usability. This library contains built-in modules (written
in C) that provide access to system functionality such as file I/O
that would otherwise be inaccessible to Python programmers, as well as
modules written in Python that provide standardized solutions for many
problems that occur in everyday programming. Some of these modules
are explicitly designed to encourage and enhance the portability of
Python programs.
This library reference manual documents Python's standard library, as
well as many optional library modules (which may or may not be
available, depending on whether the underlying platform supports them
and on the configuration choices made at compile time). It also
documents the standard types of the language and its built-in
functions and exceptions, many of which are not or incompletely
documented in the Reference Manual.
This manual assumes basic knowledge about the Python language. For an
informal introduction to Python, see the \emph{Python Tutorial}; the
\emph{Python Reference Manual} remains the highest authority on
syntactic and semantic questions. Finally, the manual entitled
\emph{Extending and Embedding the Python Interpreter} describes how to
add new extensions to Python and how to embed it in other applications.
\end{abstract}
\tableofcontents
% Chapter title:
\input{libintro} % Introduction
\input{libobjs} % Built-in Types, Exceptions and Functions
\input{libtypes}
\input{libexcs}
\input{libfuncs}
\input{libpython} % Python Services
\input{libsys}
\input{libtypes2} % types is already taken :-(
\input{libuserdict}
\input{liboperator}
\input{libtraceback}
\input{libpickle}
\input{libcopyreg}
\input{libshelve}
\input{libcopy}
\input{libmarshal}
\input{libimp}
%\input{libni}
\input{libparser}
\input{libsymbol}
\input{libtoken}
\input{libkeyword}
\input{libcode}
\input{libpprint}
\input{libdis}
\input{libsite}
\input{libuser}
\input{libbltin} % really __builtin__
\input{libmain} % really __main__
\input{libstrings} % String Services
\input{libstring}
\input{libre}
\input{libregex}
\input{libregsub}
\input{libstruct}
\input{libstrio}
%\input{libsoundex}
\input{libmisc} % Miscellaneous Services
\input{libmath}
\input{libcmath}
\input{libwhrandom}
\input{librandom}
%\input{librand}
\input{libbisect}
\input{libarray}
\input{libfileinput}
\input{libcalendar}
\input{liballos} % Generic Operating System Services
\input{libos}
\input{libtime}
\input{libgetopt}
\input{libtempfile}
\input{liberrno}
\input{libglob}
\input{libfnmatch}
\input{liblocale}
\input{libsomeos} % Optional Operating System Services
\input{libsignal}
\input{libsocket}
\input{libselect}
\input{libthread}
\input{libqueue}
\input{libanydbm}
\input{libwhichdb}
\input{libzlib}
\input{libgzip}
\input{libunix} % UNIX Specific Services
\input{libposix}
\input{libppath} % == posixpath
\input{libpwd}
\input{libgrp}
\input{libcrypt}
\input{libdbm}
\input{libgdbm}
\input{libtermios}
\input{libfcntl}
\input{libposixfile}
\input{libresource}
\input{libsyslog}
\input{libstat}
\input{libpopen2}
\input{libcommands}
\input{libpdb} % The Python Debugger
\input{libprofile} % The Python Profiler
\input{libwww} % Internet and WWW Services
\input{libcgi}
\input{liburllib}
\input{libhttplib}
\input{libftplib}
\input{libgopherlib}
\input{libpoplib}
\input{libimaplib}
\input{libnntplib}
\input{liburlparse}
\input{libsgmllib}
\input{libhtmllib}
\input{libxmllib}
\input{libformatter}
\input{librfc822}
\input{libmimetools}
\input{libbinhex}
\input{libuu}
\input{libbinascii}
\input{libxdrlib}
\input{libmailcap}
\input{libbase64}
\input{libquopri}
\input{libsocksvr}
\input{libmailbox}
\input{libmimify}
\input{libbasehttp}
\input{librestricted}
\input{librexec}
\input{libbastion}
\input{libmm} % Multimedia Services
\input{libaudioop}
\input{libimageop}
\input{libaifc}
\input{libjpeg}
\input{librgbimg}
\input{libimghdr}
\input{libcrypto} % Cryptographic Services
\input{libmd5}
\input{libmpz}
\input{librotor}
%\input{libamoeba} % AMOEBA ONLY
%\input{libstdwin} % STDWIN ONLY
\input{libsgi} % SGI IRIX ONLY
\input{libal}
\input{libcd}
\input{libfl}
\input{libfm}
\input{libgl}
\input{libimgfile}
%\input{libpanel}
\input{libsun} % SUNOS ONLY
\input{libsunaudio}
\input{libundoc}
%
% The ugly "%begin{latexonly}" pseudo-environments are really just to
% keep LaTeX2HTML quiet during the \renewcommand{} macros; they're
% not really valuable.
%
%begin{latexonly}
\renewcommand{\indexname}{Module Index}
%end{latexonly}
\input{modlib.ind} % Module Index
%begin{latexonly}
\renewcommand{\indexname}{Index}
%end{latexonly}
\input{lib.ind} % Index
\end{document}
\section{Standard Module \module{aifc}}
\label{module-aifc}
\stmodindex{aifc}
This module provides support for reading and writing AIFF and AIFF-C
files. AIFF is Audio Interchange File Format, a format for storing
digital audio samples in a file. AIFF-C is a newer version of the
format that includes the ability to compress the audio data.
\index{Audio Interchange File Format}
\index{AIFF}
\index{AIFF-C}
Audio files have a number of parameters that describe the audio data.
The sampling rate or frame rate is the number of times per second the
sound is sampled. The number of channels indicate if the audio is
mono, stereo, or quadro. Each frame consists of one sample per
channel. The sample size is the size in bytes of each sample. Thus a
frame consists of \var{nchannels}*\var{samplesize} bytes, and a
second's worth of audio consists of
\var{nchannels}*\var{samplesize}*\var{framerate} bytes.
For example, CD quality audio has a sample size of two bytes (16
bits), uses two channels (stereo) and has a frame rate of 44,100
frames/second. This gives a frame size of 4 bytes (2*2), and a
second's worth occupies 2*2*44100 bytes, i.e.\ 176,400 bytes.
Module \module{aifc} defines the following function:
\begin{funcdesc}{open}{file, mode}
Open an AIFF or AIFF-C file and return an object instance with
methods that are described below. The argument file is either a
string naming a file or a file object. The mode is either the string
\code{'r'} when the file must be opened for reading, or \code{'w'}
when the file must be opened for writing. When used for writing, the
file object should be seekable, unless you know ahead of time how many
samples you are going to write in total and use
\method{writeframesraw()} and \method{setnframes()}.
\end{funcdesc}
Objects returned by \function{open()} when a file is opened for
reading have the following methods:
\begin{methoddesc}[aifc]{getnchannels}{}
Return the number of audio channels (1 for mono, 2 for stereo).
\end{methoddesc}
\begin{methoddesc}[aifc]{getsampwidth}{}
Return the size in bytes of individual samples.
\end{methoddesc}
\begin{methoddesc}[aifc]{getframerate}{}
Return the sampling rate (number of audio frames per second).
\end{methoddesc}
\begin{methoddesc}[aifc]{getnframes}{}
Return the number of audio frames in the file.
\end{methoddesc}
\begin{methoddesc}[aifc]{getcomptype}{}
Return a four-character string describing the type of compression used
in the audio file. For AIFF files, the returned value is
\code{'NONE'}.
\end{methoddesc}
\begin{methoddesc}[aifc]{getcompname}{}
Return a human-readable description of the type of compression used in
the audio file. For AIFF files, the returned value is \code{'not
compressed'}.
\end{methoddesc}
\begin{methoddesc}[aifc]{getparams}{}
Return a tuple consisting of all of the above values in the above
order.
\end{methoddesc}
\begin{methoddesc}[aifc]{getmarkers}{}
Return a list of markers in the audio file. A marker consists of a
tuple of three elements. The first is the mark ID (an integer), the
second is the mark position in frames from the beginning of the data
(an integer), the third is the name of the mark (a string).
\end{methoddesc}
\begin{methoddesc}[aifc]{getmark}{id}
Return the tuple as described in \method{getmarkers()} for the mark
with the given \var{id}.
\end{methoddesc}
\begin{methoddesc}[aifc]{readframes}{nframes}
Read and return the next \var{nframes} frames from the audio file. The
returned data is a string containing for each frame the uncompressed
samples of all channels.
\end{methoddesc}
\begin{methoddesc}[aifc]{rewind}{}
Rewind the read pointer. The next \method{readframes()} will start from
the beginning.
\end{methoddesc}
\begin{methoddesc}[aifc]{setpos}{pos}
Seek to the specified frame number.
\end{methoddesc}
\begin{methoddesc}[aifc]{tell}{}
Return the current frame number.
\end{methoddesc}
\begin{methoddesc}[aifc]{close}{}
Close the AIFF file. After calling this method, the object can no
longer be used.
\end{methoddesc}
Objects returned by \function{open()} when a file is opened for
writing have all the above methods, except for \method{readframes()} and
\method{setpos()}. In addition the following methods exist. The
\method{get*()} methods can only be called after the corresponding
\method{set*()} methods have been called. Before the first
\method{writeframes()} or \method{writeframesraw()}, all parameters
except for the number of frames must be filled in.
\begin{methoddesc}[aifc]{aiff}{}
Create an AIFF file. The default is that an AIFF-C file is created,
unless the name of the file ends in \code{'.aiff'} in which case the
default is an AIFF file.
\end{methoddesc}
\begin{methoddesc}[aifc]{aifc}{}
Create an AIFF-C file. The default is that an AIFF-C file is created,
unless the name of the file ends in \code{'.aiff'} in which case the
default is an AIFF file.
\end{methoddesc}
\begin{methoddesc}[aifc]{setnchannels}{nchannels}
Specify the number of channels in the audio file.
\end{methoddesc}
\begin{methoddesc}[aifc]{setsampwidth}{width}
Specify the size in bytes of audio samples.
\end{methoddesc}
\begin{methoddesc}[aifc]{setframerate}{rate}
Specify the sampling frequency in frames per second.
\end{methoddesc}
\begin{methoddesc}[aifc]{setnframes}{nframes}
Specify the number of frames that are to be written to the audio file.
If this parameter is not set, or not set correctly, the file needs to
support seeking.
\end{methoddesc}
\begin{methoddesc}[aifc]{setcomptype}{type, name}
Specify the compression type. If not specified, the audio data will
not be compressed. In AIFF files, compression is not possible. The
name parameter should be a human-readable description of the
compression type, the type parameter should be a four-character
string. Currently the following compression types are supported:
NONE, ULAW, ALAW, G722.
\index{u-LAW}
\index{A-LAW}
\index{G.722}
\end{methoddesc}
\begin{methoddesc}[aifc]{setparams}{nchannels, sampwidth, framerate, comptype, compname}
Set all the above parameters at once. The argument is a tuple
consisting of the various parameters. This means that it is possible
to use the result of a \method{getparams()} call as argument to
\method{setparams()}.
\end{methoddesc}
\begin{methoddesc}[aifc]{setmark}{id, pos, name}
Add a mark with the given id (larger than 0), and the given name at
the given position. This method can be called at any time before
\method{close()}.
\end{methoddesc}
\begin{methoddesc}[aifc]{tell}{}
Return the current write position in the output file. Useful in
combination with \method{setmark()}.
\end{methoddesc}
\begin{methoddesc}[aifc]{writeframes}{data}
Write data to the output file. This method can only be called after
the audio file parameters have been set.
\end{methoddesc}
\begin{methoddesc}[aifc]{writeframesraw}{data}
Like \method{writeframes()}, except that the header of the audio file
is not updated.
\end{methoddesc}
\begin{methoddesc}[aifc]{close}{}
Close the AIFF file. The header of the file is updated to reflect the
actual size of the audio data. After calling this method, the object
can no longer be used.
\end{methoddesc}
\section{Built-in Module \module{al}}
\label{module-al}
\bimodindex{al}
This module provides access to the audio facilities of the SGI Indy
and Indigo workstations. See section 3A of the IRIX man pages for
details. You'll need to read those man pages to understand what these
functions do! Some of the functions are not available in IRIX
releases before 4.0.5. Again, see the manual to check whether a
specific function is available on your platform.
All functions and methods defined in this module are equivalent to
the \C{} functions with \samp{AL} prefixed to their name.
Symbolic constants from the \C{} header file \code{<audio.h>} are
defined in the standard module \module{AL}\refstmodindex{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.)
The module defines the following functions:
\begin{funcdesc}{openport}{name, direction\optional{, config}}
The name and direction arguments are strings. The optional
\var{config} argument is a configuration object as returned by
\function{newconfig()}. The return value is an \dfn{audio port
object}; methods of audio port objects are described below.
\end{funcdesc}
\begin{funcdesc}{newconfig}{}
The return value is a new \dfn{audio configuration object}; methods of
audio configuration objects are described below.
\end{funcdesc}
\begin{funcdesc}{queryparams}{device}
The device argument is an integer. The return value is a list of
integers containing the data returned by \cfunction{ALqueryparams()}.
\end{funcdesc}
\begin{funcdesc}{getparams}{device, list}
The \var{device} argument is an integer. The list argument is a list
such as returned by \function{queryparams()}; it is modified in place
(!).
\end{funcdesc}
\begin{funcdesc}{setparams}{device, list}
The \var{device} argument is an integer. The \var{list} argument is a
list such as returned by \function{queryparams()}.
\end{funcdesc}
\subsection{Configuration Objects}
\label{al-config-objects}
Configuration objects (returned by \function{newconfig()} have the
following methods:
\begin{methoddesc}[audio configuration]{getqueuesize}{}
Return the queue size.
\end{methoddesc}
\begin{methoddesc}[audio configuration]{setqueuesize}{size}
Set the queue size.
\end{methoddesc}
\begin{methoddesc}[audio configuration]{getwidth}{}
Get the sample width.
\end{methoddesc}
\begin{methoddesc}[audio configuration]{setwidth}{width}
Set the sample width.
\end{methoddesc}
\begin{methoddesc}[audio configuration]{getchannels}{}
Get the channel count.
\end{methoddesc}
\begin{methoddesc}[audio configuration]{setchannels}{nchannels}
Set the channel count.
\end{methoddesc}
\begin{methoddesc}[audio configuration]{getsampfmt}{}
Get the sample format.
\end{methoddesc}
\begin{methoddesc}[audio configuration]{setsampfmt}{sampfmt}
Set the sample format.
\end{methoddesc}
\begin{methoddesc}[audio configuration]{getfloatmax}{}
Get the maximum value for floating sample formats.
\end{methoddesc}
\begin{methoddesc}[audio configuration]{setfloatmax}{floatmax}
Set the maximum value for floating sample formats.
\end{methoddesc}
\subsection{Port Objects}
\label{al-port-objects}
Port objects, as returned by \function{openport()}, have the following
methods:
\begin{methoddesc}[audio port]{closeport}{}
Close the port.
\end{methoddesc}
\begin{methoddesc}[audio port]{getfd}{}
Return the file descriptor as an int.
\end{methoddesc}
\begin{methoddesc}[audio port]{getfilled}{}
Return the number of filled samples.
\end{methoddesc}
\begin{methoddesc}[audio port]{getfillable}{}
Return the number of fillable samples.
\end{methoddesc}
\begin{methoddesc}[audio port]{readsamps}{nsamples}
Read a number of samples from the queue, blocking if necessary.
Return the data 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{methoddesc}
\begin{methoddesc}[audio port]{writesamps}{samples}
Write samples into the queue, blocking if necessary. The samples are
encoded as described for the \method{readsamps()} return value.
\end{methoddesc}
\begin{methoddesc}[audio port]{getfillpoint}{}
Return the `fill point'.
\end{methoddesc}
\begin{methoddesc}[audio port]{setfillpoint}{fillpoint}
Set the `fill point'.
\end{methoddesc}
\begin{methoddesc}[audio port]{getconfig}{}
Return a configuration object containing the current configuration of
the port.
\end{methoddesc}
\begin{methoddesc}[audio port]{setconfig}{config}
Set the configuration from the argument, a configuration object.
\end{methoddesc}
\begin{methoddesc}[audio port]{getstatus}{list}
Get status information on last error.
\end{methoddesc}
\section{Standard Module \module{AL}}
\nodename{AL (uppercase)}
\stmodindex{AL}
This module defines symbolic constants needed to use the built-in
module \module{al} (see above); they are equivalent to those defined
in the \C{} header file \code{<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:
\begin{verbatim}
import al
from AL import *
\end{verbatim}
\chapter{Generic Operating System Services}
\label{allos}
The modules described in this chapter provide interfaces to operating
system features that are available on (almost) all operating systems,
such as files and a clock. The interfaces are generally modelled
after the \UNIX{} or \C{} interfaces but they are available on most
other systems as well. Here's an overview:
\begin{description}
\item[os]
--- Miscellaneous OS interfaces.
\item[time]
--- Time access and conversions.
\item[getopt]
--- Parser for command line options.
\item[tempfile]
--- Generate temporary file names.
\item[errno]
--- Standard errno system symbols.
\item[glob]
--- \UNIX{} shell style pathname pattern expansion.
\item[fnmatch]
--- \UNIX{} shell style pathname pattern matching.
\item[locale]
--- Internationalization services.
\end{description}
\chapter{Amoeba Specific Services}
\section{Built-in Module \module{amoeba}}
\label{module-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:
\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
\emph{c2a}(U)
and
\emph{a2c}(U).
For example:
\begin{verbatim}
>>> amoeba.name_lookup('/profile/cap')
aa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a
>>>
\end{verbatim}
%
The following methods are defined for capability objects.
\setindexsubitem{(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{Standard Module \module{anydbm}}
\label{module-anydbm}
\stmodindex{anydbm}
\module{anydbm} is a generic interface to variants of the DBM
database --- \module{dbhash}\refbimodindex{dbhash},
\module{gdbm}\refbimodindex{gdbm}, or \module{dbm}\refbimodindex{dbm}.
If none of these modules is installed, the slow-but-simple
implementation in module \module{dumbdbm}\refstmodindex{dumbdbm} will
be used.
\begin{funcdesc}{open}{filename\optional{, flag\optional{, mode}}}
Open the database file \var{filename} and return a corresponding object.
If the database file already exists, the \module{whichdb} module is
used to determine its type and the appropriate module is used; if it
doesn't exist, the first module listed above that can be imported is
used.
The optional \var{flag} argument can be
\code{'r'} to open an existing database for reading only,
\code{'w'} to open an existing database for reading and writing,
\code{'c'} to create the database if it doesn't exist, or
\code{'n'}, which will always create a new empty database. If not
specified, the default value is \code{'r'}.
The optional \var{mode} argument is the \UNIX{} mode of the file, used
only when the database has to be created. It defaults to octal
\code{0666} (and will be modified by the prevailing umask).
\end{funcdesc}
\begin{excdesc}{error}
A tuple containing the exceptions that can be raised by each of the
supported modules, with a unique exception \exception{anydbm.error} as
the first item --- the latter is used when \exception{anydbm.error} is
raised.
\end{excdesc}
The object returned by \function{open()} supports most of the same
functionality as dictionaries; keys and their corresponding values can
be stored, retrieved, and deleted, and the \method{has_key()} and
\method{keys()} methods are available. Keys and values must always be
strings.
\section{Standard Module \module{dumbdbm}}
\label{module-dumbdbm}
\stmodindex{dumbdbm}
A simple and slow database implemented entirely in Python. This
should only be used when no other DBM-style database is available.
\begin{funcdesc}{open}{filename\optional{, flag\optional{, mode}}}
Open the database file \var{filename} and return a corresponding object.
The optional \var{flag} argument can be
\code{'r'} to open an existing database for reading only,
\code{'w'} to open an existing database for reading and writing,
\code{'c'} to create the database if it doesn't exist, or
\code{'n'}, which will always create a new empty database. If not
specified, the default value is \code{'r'}.
The optional \var{mode} argument is the \UNIX{} mode of the file, used
only when the database has to be created. It defaults to octal
\code{0666} (and will be modified by the prevailing umask).
\end{funcdesc}
\begin{excdesc}{error}
Raised for errors not reported as \exception{KeyError} errors.
\end{excdesc}
\section{Built-in Module \module{array}}
\label{module-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|l|c}{code}{Type code}{C Type}{Minimum size in bytes}
\lineiii{'c'}{character}{1}
\lineiii{'b'}{signed integer}{1}
\lineiii{'B'}{unsigned integer}{1}
\lineiii{'h'}{signed integer}{2}
\lineiii{'H'}{unsigned integer}{2}
\lineiii{'i'}{signed integer}{2}
\lineiii{'I'}{unsigned integer}{2}
\lineiii{'l'}{signed integer}{4}
\lineiii{'L'}{unsigned 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 speaking, by the \C{} implementation). The actual
size can be accessed through the \var{itemsize} attribute. The values
stored for \code{'L'} and \code{'I'} items will be represented as
Python long integers when retrieved, because Python's plain integer
type cannot represent the full range of \C{}'s unsigned (long) integers.
The module defines the following function and type object:
\begin{funcdesc}{array}{typecode\optional{, 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
\method{fromlist()} or \method{fromstring()} method (see below) to add
initial items to the array.
\end{funcdesc}
\begin{datadesc}{ArrayType}
Type object corresponding to the objects returned by
\function{array()}.
\end{datadesc}
Array objects support the following data items and methods:
\begin{memberdesc}[array]{typecode}
The typecode character used to create the array.
\end{memberdesc}
\begin{memberdesc}[array]{itemsize}
The length in bytes of one array item in the internal representation.
\end{memberdesc}
\begin{methoddesc}[array]{append}{x}
Append a new item with value \var{x} to the end of the array.
\end{methoddesc}
\begin{methoddesc}[array]{buffer_info}{}
Return a tuple \code{(\var{address}, \var{length})} giving the current
memory address and the length in bytes of the buffer used to hold
array's contents. This is occasionally useful when working with
low-level (and inherently unsafe) I/O interfaces that require memory
addresses, such as certain \cfunction{ioctl()} operations. The returned
numbers are valid as long as the array exists and no length-changing
operations are applied to it.
\end{methoddesc}
\begin{methoddesc}[array]{byteswap}{x}
``Byteswap'' all items of the array. This is only supported for
integer values. It is useful when reading data from a file written
on a machine with a different byte order.
\end{methoddesc}
\begin{methoddesc}[array]{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, \exception{EOFError} is raised, but the items that were
available are still inserted into the array. \var{f} must be a real
built-in file object; something else with a \method{read()} method won't
do.
\end{methoddesc}
\begin{methoddesc}[array]{fromlist}{list}
Append items from the list. This is equivalent to
\samp{for x in \var{list}:\ a.append(x)}
except that if there is a type error, the array is unchanged.
\end{methoddesc}
\begin{methoddesc}[array]{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 \method{fromfile()} method).
\end{methoddesc}
\begin{methoddesc}[array]{insert}{i, x}
Insert a new item with value \var{x} in the array before position
\var{i}.
\end{methoddesc}
\begin{methoddesc}[array]{read}{f, n}
\deprecated {1.5.1}
{Use the \method{fromfile()} method.}
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, \exception{EOFError} is raised, but the items that were
available are still inserted into the array. \var{f} must be a real
built-in file object; something else with a \method{read()} method won't
do.
\end{methoddesc}
\begin{methoddesc}[array]{reverse}{}
Reverse the order of the items in the array.
\end{methoddesc}
\begin{methoddesc}[array]{tofile}{f}
Write all items (as machine values) to the file object \var{f}.
\end{methoddesc}
\begin{methoddesc}[array]{tolist}{}
Convert the array to an ordinary list with the same items.
\end{methoddesc}
\begin{methoddesc}[array]{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 \method{tofile()} method.)
\end{methoddesc}
\begin{methoddesc}[array]{write}{f}
\deprecated {1.5.1}
{Use the \method{tofile()} method.}
Write all items (as machine values) to the file object \var{f}.
\end{methoddesc}
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:
\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}
\begin{seealso}
\seemodule{struct}{Packing and unpacking of heterogeneous binary data.}
\end{seealso}
This diff is collapsed.
\section{Standard Module \module{base64}}
\label{module-base64}
\stmodindex{base64}
\indexii{base64}{encoding}
\index{MIME!base64 encoding}
This module perform base64 encoding and decoding of arbitrary binary
strings into text strings that can be safely emailed or posted. The
encoding scheme is defined in \rfc{1421} (``Privacy Enhancement for
Internet Electronic Mail: Part I: Message Encryption and
Authentication Procedures'', section 4.3.2.4, ``Step 4: Printable
Encoding'') and is used for MIME email and
various other Internet-related applications; it is not the same as the
output produced by the \program{uuencode} program. For example, the
string \code{'www.python.org'} is encoded as the string
\code{'d3d3LnB5dGhvbi5vcmc=\e n'}.
\begin{funcdesc}{decode}{input, output}
Decode the contents of the \var{input} file and write the resulting
binary data to the \var{output} file.
\var{input} and \var{output} must either be file objects or objects that
mimic the file object interface. \var{input} will be read until
\code{\var{input}.read()} returns an empty string.
\end{funcdesc}
\begin{funcdesc}{decodestring}{s}
Decode the string \var{s}, which must contain one or more lines of
base64 encoded data, and return a string containing the resulting
binary data.
\end{funcdesc}
\begin{funcdesc}{encode}{input, output}
Encode the contents of the \var{input} file and write the resulting
base64 encoded data to the \var{output} file.
\var{input} and \var{output} must either be file objects or objects that
mimic the file object interface. \var{input} will be read until
\code{\var{input}.read()} returns an empty string.
\end{funcdesc}
\begin{funcdesc}{encodestring}{s}
Encode the string \var{s}, which can contain arbitrary binary data,
and return a string containing one or more lines of
base64 encoded data.
\end{funcdesc}
\section{Standard Module \module{BaseHTTPServer}}
\label{module-BaseHTTPServer}
\stmodindex{BaseHTTPServer}
\indexii{WWW}{server}
\indexii{HTTP}{protocol}
\index{URL}
\index{httpd}
This module defines two classes for implementing HTTP servers
(web servers). Usually, this module isn't used directly, but is used
as a basis for building functioning web servers. See the
\module{SimpleHTTPServer} and \module{CGIHTTPServer} modules.
\refstmodindex{SimpleHTTPServer}
\refstmodindex{CGIHTTPServer}
The first class, \class{HTTPServer}, is a
\class{SocketServer.TCPServer} subclass. It creates and listens at the
web socket, dispatching the requests to a handler. Code to create and
run the server looks like this:
\begin{verbatim}
def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
\end{verbatim}
\begin{classdesc}{HTTPServer}{server_address, RequestHandlerClass}
This class builds on the \class{TCPServer} class by
storing the server address as instance
variables named \member{server_name} and \member{server_port}. The
server is accessible by the handler, typically through the handler's
\member{server} instance variable.
\end{classdesc}
\begin{classdesc}{BaseHTTPRequestHandler}{request, client_address, server}
This class is used
to handle the HTTP requests that arrive at the server. By itself,
it cannot respond to any actual HTTP requests; it must be subclassed
to handle each request method (e.g. GET or POST).
\class{BaseHTTPRequestHandler} provides a number of class and instance
variables, and methods for use by subclasses.
The handler will parse the request and the headers, then call a
method specific to the request type. The method name is constructed
from the request. For example, for the request method \samp{SPAM}, the
\method{do_SPAM()} method will be called with no arguments. All of
the relevant information is stored in instance variables of the
handler. Subclasses should not need to override or extend the
\method{__init__()} method.
\end{classdesc}
\class{BaseHTTPRequestHandler} has the following instance variables:
\begin{memberdesc}{client_address}
Contains a tuple of the form \code{(\var{host}, \var{port})} referring
to the client's address.
\end{memberdesc}
\begin{memberdesc}{command}
Contains the command (request type). For example, \code{'GET'}.
\end{memberdesc}
\begin{memberdesc}{path}
Contains the request path.
\end{memberdesc}
\begin{memberdesc}{request_version}
Contains the version string from the request. For example,
\code{'HTTP/1.0'}.
\end{memberdesc}
\begin{memberdesc}{headers}
Holds an instance of the class specified by the \member{MessageClass}
class variable. This instance parses and manages the headers in
the HTTP request.
\end{memberdesc}
\begin{memberdesc}{rfile}
Contains an input stream, positioned at the start of the optional
input data.
\end{memberdesc}
\begin{memberdesc}{wfile}
Contains the output stream for writing a response back to the client.
Proper adherance to the HTTP protocol must be used when writing
to this stream.
\end{memberdesc}
\class{BaseHTTPRequestHandler} has the following class variables:
\begin{memberdesc}{server_version}
Specifies the server software version. You may want to override
this.
The format is multiple whitespace-separated strings,
where each string is of the form name[/version].
For example, \code{'BaseHTTP/0.2'}.
\end{memberdesc}
\begin{memberdesc}{sys_version}
Contains the Python system version, in a form usable by the
\member{version_string} method and the \member{server_version} class
variable. For example, \code{'Python/1.4'}.
\end{memberdesc}
\begin{memberdesc}{error_message_format}
Specifies a format string for building an error response to the
client. It uses parenthesized, keyed format specifiers, so the
format operand must be a dictionary. The \var{code} key should
be an integer, specifing the numeric HTTP error code value.
\var{message} should be a string containing a (detailed) error
message of what occurred, and \var{explain} should be an
explanation of the error code number. Default \var{message}
and \var{explain} values can found in the \var{responses}
class variable.
\end{memberdesc}
\begin{memberdesc}{protocol_version}
This specifies the HTTP protocol version used in responses.
Typically, this should not be overridden. Defaults to
\code{'HTTP/1.0'}.
\end{memberdesc}
\begin{memberdesc}{MessageClass}
Specifies a \class{rfc822.Message}-like class to parse HTTP
headers. Typically, this is not overridden, and it defaults to
\class{mimetools.Message}.
\withsubitem{(in module mimetools)}{\ttindex{Message}}
\end{memberdesc}
\begin{memberdesc}{responses}
This variable contains a mapping of error code integers to two-element
tuples containing a short and long message. For example,
\code{\{\var{code}: (\var{shortmessage}, \var{longmessage})\}}. The
\var{shortmessage} is usually used as the \var{message} key in an
error response, and \var{longmessage} as the \var{explain} key
(see the \member{error_message_format} class variable).
\end{memberdesc}
A \class{BaseHTTPRequestHandler} instance has the following methods:
\begin{methoddesc}{handle}{}
Overrides the superclass' \method{handle()} method to provide the
specific handler behavior. This method will parse and dispatch
the request to the appropriate \method{do_*()} method.
\end{methoddesc}
\begin{methoddesc}{send_error}{code\optional{, message}}
Sends and logs a complete error reply to the client. The numeric
\var{code} specifies the HTTP error code, with \var{message} as
optional, more specific text. A complete set of headers is sent,
followed by text composed using the \member{error_message_format}
class variable.
\end{methoddesc}
\begin{methoddesc}{send_response}{code\optional{, message}}
Sends a response header and logs the accepted request. The HTTP
response line is sent, followed by \emph{Server} and \emph{Date}
headers. The values for these two headers are picked up from the
\method{version_string()} and \method{date_time_string()} methods,
respectively.
\end{methoddesc}
\begin{methoddesc}{send_header}{keyword, value}
Writes a specific MIME header to the output stream. \var{keyword}
should specify the header keyword, with \var{value} specifying
its value.
\end{methoddesc}
\begin{methoddesc}{end_headers}{}
Sends a blank line, indicating the end of the MIME headers in
the response.
\end{methoddesc}
\begin{methoddesc}{log_request}{\optional{code\optional{, size}}}
Logs an accepted (successful) request. \var{code} should specify
the numeric HTTP code associated with the response. If a size of
the response is available, then it should be passed as the
\var{size} parameter.
\end{methoddesc}
\begin{methoddesc}{log_error}{...}
Logs an error when a request cannot be fulfilled. By default,
it passes the message to \method{log_message()}, so it takes the
same arguments (\var{format} and additional values).
\end{methoddesc}
\begin{methoddesc}{log_message}{format, ...}
Logs an arbitrary message to \code{sys.stderr}. This is typically
overridden to create custom error logging mechanisms. The
\var{format} argument is a standard printf-style format string,
where the additional arguments to \method{log_message()} are applied
as inputs to the formatting. The client address and current date
and time are prefixed to every message logged.
\end{methoddesc}
\begin{methoddesc}{version_string}{}
Returns the server software's version string. This is a combination
of the \member{server_version} and \member{sys_version} class variables.
\end{methoddesc}
\begin{methoddesc}{date_time_string}{}
Returns the current date and time, formatted for a message header.
\end{methoddesc}
\begin{methoddesc}{log_data_time_string}{}
Returns the current date and time, formatted for logging.
\end{methoddesc}
\begin{methoddesc}{address_string}{}
Returns the client address, formatted for logging. A name lookup
is performed on the client's IP address.
\end{methoddesc}
\section{Standard Module \module{Bastion}}
\label{module-Bastion}
\stmodindex{Bastion}
% I'm concerned that the word 'bastion' won't be understood by people
% for whom English is a second language, making the module name
% somewhat mysterious. Thus, the brief definition... --amk
According to the dictionary, a bastion is ``a fortified area or
position'', or ``something that is considered a stronghold.'' It's a
suitable name for this module, which provides a way to forbid access
to certain attributes of an object. It must always be used with the
\module{rexec} module, in order to allow restricted-mode programs access
to certain safe attributes of an object, while denying access to
other, unsafe attributes.
% I've punted on the issue of documenting keyword arguments for now.
\begin{funcdesc}{Bastion}{object\optional{, filter\optional{,
name\optional{, class}}}}
Protect the object \var{object}, returning a bastion for the
object. Any attempt to access one of the object's attributes will
have to be approved by the \var{filter} function; if the access is
denied an \exception{AttributeError} exception will be raised.
If present, \var{filter} must be a function that accepts a string
containing an attribute name, and returns true if access to that
attribute will be permitted; if \var{filter} returns false, the access
is denied. The default filter denies access to any function beginning
with an underscore (\samp{_}). The bastion's string representation
will be \samp{<Bastion for \var{name}>} if a value for
\var{name} is provided; otherwise, \samp{repr(\var{object})} will be
used.
\var{class}, if present, should be a subclass of \class{BastionClass};
see the code in \file{bastion.py} for the details. Overriding the
default \class{BastionClass} will rarely be required.
\end{funcdesc}
\begin{classdesc}{BastionClass}{getfunc, name}
Class which actually implements bastion objects. This is the default
class used by \function{Bastion()}. The \var{getfunc} parameter is a
function which returns the value of an attribute which should be
exposed to the restricted execution environment when called with the
name of the attribute as the only parameter. \var{name} is used to
construct the \function{repr()} of the \class{BastionClass} instance.
\end{classdesc}
\section{Built-in Module \module{binascii}}
\label{module-binascii}
\bimodindex{binascii}
The \module{binascii} module contains a number of methods to convert
between binary and various \ASCII{}-encoded binary
representations. Normally, you will not use these modules directly but
use wrapper modules like \module{uu}\refstmodindex{uu} or
\module{hexbin}\refstmodindex{hexbin} instead, this module solely
exists because bit-manipuation of large amounts of data is slow in
Python.
The \module{binascii} module defines the following functions:
\begin{funcdesc}{a2b_uu}{string}
Convert a single line of uuencoded data back to binary and return the
binary data. Lines normally contain 45 (binary) bytes, except for the
last line. Line data may be followed by whitespace.
\end{funcdesc}
\begin{funcdesc}{b2a_uu}{data}
Convert binary data to a line of \ASCII{} characters, the return value
is the converted line, including a newline char. The length of
\var{data} should be at most 45.
\end{funcdesc}
\begin{funcdesc}{a2b_base64}{string}
Convert a block of base64 data back to binary and return the
binary data. More than one line may be passed at a time.
\end{funcdesc}
\begin{funcdesc}{b2a_base64}{data}
Convert binary data to a line of \ASCII{} characters in base64 coding.
The return value is the converted line, including a newline char.
The length of \var{data} should be at most 57 to adhere to the base64
standard.
\end{funcdesc}
\begin{funcdesc}{a2b_hqx}{string}
Convert binhex4 formatted \ASCII{} data to binary, without doing
RLE-decompression. The string should contain a complete number of
binary bytes, or (in case of the last portion of the binhex4 data)
have the remaining bits zero.
\end{funcdesc}
\begin{funcdesc}{rledecode_hqx}{data}
Perform RLE-decompression on the data, as per the binhex4
standard. The algorithm uses \code{0x90} after a byte as a repeat
indicator, followed by a count. A count of \code{0} specifies a byte
value of \code{0x90}. The routine returns the decompressed data,
unless data input data ends in an orphaned repeat indicator, in which
case the \exception{Incomplete} exception is raised.
\end{funcdesc}
\begin{funcdesc}{rlecode_hqx}{data}
Perform binhex4 style RLE-compression on \var{data} and return the
result.
\end{funcdesc}
\begin{funcdesc}{b2a_hqx}{data}
Perform hexbin4 binary-to-\ASCII{} translation and return the
resulting string. The argument should already be RLE-coded, and have a
length divisible by 3 (except possibly the last fragment).
\end{funcdesc}
\begin{funcdesc}{crc_hqx}{data, crc}
Compute the binhex4 crc value of \var{data}, starting with an initial
\var{crc} and returning the result.
\end{funcdesc}
\begin{excdesc}{Error}
Exception raised on errors. These are usually programming errors.
\end{excdesc}
\begin{excdesc}{Incomplete}
Exception raised on incomplete data. These are usually not programming
errors, but may be handled by reading a little more data and trying
again.
\end{excdesc}
\section{Standard Module \module{binhex}}
\label{module-binhex}
\stmodindex{binhex}
This module encodes and decodes files in binhex4 format, a format
allowing representation of Macintosh files in \ASCII{}. On the Macintosh,
both forks of a file and the finder information are encoded (or
decoded), on other platforms only the data fork is handled.
The \module{binhex} module defines the following functions:
\begin{funcdesc}{binhex}{input, output}
Convert a binary file with filename \var{input} to binhex file
\var{output}. The \var{output} parameter can either be a filename or a
file-like object (any object supporting a \var{write} and \var{close}
method).
\end{funcdesc}
\begin{funcdesc}{hexbin}{input\optional{, output}}
Decode a binhex file \var{input}. \var{input} may be a filename or a
file-like object supporting \var{read} and \var{close} methods.
The resulting file is written to a file named \var{output}, unless the
argument is empty in which case the output filename is read from the
binhex file.
\end{funcdesc}
\subsection{Notes}
There is an alternative, more powerful interface to the coder and
decoder, see the source for details.
If you code or decode textfiles on non-Macintosh platforms they will
still use the Macintosh newline convention (carriage-return as end of
line).
As of this writing, \function{hexbin()} appears to not work in all
cases.
% LaTeX produced by Fred L. Drake, Jr. <fdrake@acm.org>, with an
% example based on the PyModules FAQ entry by Aaron Watters
% <arw@pythonpros.com>.
\section{Standard Module \module{bisect}}
\stmodindex{bisect}
\label{module-bisect}
This module provides support for maintaining a list in sorted order
without having to sort the list after each insertion. For long lists
of items with expensive comparison operations, this can be an
improvement over the more common approach. The module is called
\module{bisect} because it uses a basic bisection algorithm to do its
work. The source code may be used a useful reference for a working
example of the algorithm (i.e., the boundary conditions are already
right!).
The following functions are provided:
\begin{funcdesc}{bisect}{list, item\optional{, lo\optional{, hi}}}
Locate the proper insertion point for \var{item} in \var{list} to
maintain sorted order. The parameters \var{lo} and \var{hi} may be
used to specify a subset of the list which should be considered. The
return value is suitable for use as the first parameter to
\code{\var{list}.insert()}.
\end{funcdesc}
\begin{funcdesc}{insort}{list, item\optional{, lo\optional{, hi}}}
Insert \var{item} in \var{list} in sorted order. This is equivalent
to \code{\var{list}.insert(bisect.bisect(\var{list}, \var{item},
\var{lo}, \var{hi}), \var{item})}.
\end{funcdesc}
\subsection{Example}
\nodename{bisect-example}
The \function{bisect()} function is generally useful for categorizing
numeric data. This example uses \function{bisect()} to look up a
letter grade for an exam total (say) based on a set of ordered numeric
breakpoints: 85 and up is an `A', 75..84 is a `B', etc.
\begin{verbatim}
>>> grades = "FEDCBA"
>>> breakpoints = [30, 44, 66, 75, 85]
>>> from bisect import bisect
>>> def grade(total):
... return grades[bisect(breakpoints, total)]
...
>>> grade(66)
'C'
>>> map(grade, [33, 99, 77, 44, 12, 88])
['E', 'A', 'B', 'D', 'F', 'A']
\end{verbatim}
\section{Built-in Module \module{__builtin__}}
\label{module-builtin}
\bimodindex{__builtin__}
This module provides direct access to all `built-in' identifiers of
Python; e.g. \code{__builtin__.open} is the full name for the built-in
function \code{open()}. See section \ref{built-in-funcs}, ``Built-in
Functions.''
% This section was contributed by Drew Csillag <drew_csillag@geocities.com>.
\section{Standard Module \module{calendar}}
\label{module-calendar}
\stmodindex{calendar}
This module allows you to output calendars like the \UNIX{}
\manpage{cal}{1} program.
\begin{funcdesc}{isleap}{year}
Returns \code{1} if \var{year} is a leap year.
\end{funcdesc}
\begin{funcdesc}{leapdays}{year1, year2}
Return the number of leap years in the range
[\var{year1}\ldots\var{year2}].
\end{funcdesc}
\begin{funcdesc}{weekday}{year, month, day}
Returns the day of the week (\code{0} is Monday) for \var{year}
(\code{1970}--\dots), \var{month} (\code{1}--\code{12}), \var{day}
(\code{1}--\code{31}).
\end{funcdesc}
\begin{funcdesc}{monthrange}{year, month}
Returns weekday of first day of the month and number of days in month,
for the specified \var{year} and \var{month}.
\end{funcdesc}
\begin{funcdesc}{monthcalendar}{year, month}
Returns a matrix representing a month's calendar. Each row represents
a week; days outside of the month a represented by zeros.
\end{funcdesc}
\begin{funcdesc}{prmonth}{year, month\optional{, width\optional{, length}}}
Prints a month's calendar. If \var{width} is provided, it specifies
the width of the columns that the numbers are centered in. If
\var{length} is given, it specifies the number of lines that each
week will use.
\end{funcdesc}
\begin{funcdesc}{prcal}{year}
Prints the calendar for the year \var{year}.
\end{funcdesc}
This diff is collapsed.
This diff is collapsed.
\section{Built-in Module \module{cmath}}
\label{module-cmath}
\bimodindex{cmath}
This module is always available.
It provides access to mathematical functions for complex numbers.
The functions are:
\begin{funcdesc}{acos}{x}
Return the arc cosine of \var{x}.
\end{funcdesc}
\begin{funcdesc}{acosh}{x}
Return the hyperbolic arc cosine of \var{x}.
\end{funcdesc}
\begin{funcdesc}{asin}{x}
Return the arc sine of \var{x}.
\end{funcdesc}
\begin{funcdesc}{asinh}{x}
Return the hyperbolic arc sine of \var{x}.
\end{funcdesc}
\begin{funcdesc}{atan}{x}
Return the arc tangent of \var{x}.
\end{funcdesc}
\begin{funcdesc}{atanh}{x}
Return the hyperbolic arc tangent of \var{x}.
\end{funcdesc}
\begin{funcdesc}{cos}{x}
Return the cosine of \var{x}.
\end{funcdesc}
\begin{funcdesc}{cosh}{x}
Return the hyperbolic cosine of \var{x}.
\end{funcdesc}
\begin{funcdesc}{exp}{x}
Return the exponential value \code{e**\var{x}}.
\end{funcdesc}
\begin{funcdesc}{log}{x}
Return the natural logarithm of \var{x}.
\end{funcdesc}
\begin{funcdesc}{log10}{x}
Return the base-10 logarithm of \var{x}.
\end{funcdesc}
\begin{funcdesc}{sin}{x}
Return the sine of \var{x}.
\end{funcdesc}
\begin{funcdesc}{sinh}{x}
Return the hyperbolic sine of \var{x}.
\end{funcdesc}
\begin{funcdesc}{sqrt}{x}
Return the square root of \var{x}.
\end{funcdesc}
\begin{funcdesc}{tan}{x}
Return the tangent of \var{x}.
\end{funcdesc}
\begin{funcdesc}{tanh}{x}
Return the hyperbolic tangent of \var{x}.
\end{funcdesc}
The module also defines two mathematical constants:
\begin{datadesc}{pi}
The mathematical constant \emph{pi}, as a real.
\end{datadesc}
\begin{datadesc}{e}
The mathematical constant \emph{e}, as a real.
\end{datadesc}
Note that the selection of functions is similar, but not identical, to
that in module \code{math}\refbimodindex{math}. The reason for having
two modules is, that some users aren't interested in complex numbers,
and perhaps don't even know what they are. They would rather have
\code{math.sqrt(-1)} raise an exception than return a complex number.
Also note that the functions defined in \code{cmath} always return a
complex number, even if the answer can be expressed as a real number
(in which case the complex number has an imaginary part of zero).
\section{Standard Module \module{code}}
\label{module-code}
\stmodindex{code}
The \code{code} module defines operations pertaining to Python code
objects.
The \code{code} module defines the following functions:
\begin{funcdesc}{compile_command}{source, \optional{filename\optional{, symbol}}}
This function is useful for programs that want to emulate Python's
interpreter main loop (a.k.a. the read-eval-print loop). The tricky
part is to determine when the user has entered an incomplete command
that can be completed by entering more text (as opposed to a complete
command or a syntax error). This function \emph{almost} always makes
the same decision as the real interpreter main loop.
Arguments: \var{source} is the source string; \var{filename} is the
optional filename from which source was read, defaulting to
\code{"<input>"}; and \var{symbol} is the optional grammar start
symbol, which should be either \code{"single"} (the default) or
\code{"eval"}.
Return a code object (the same as \code{compile(\var{source},
\var{filename}, \var{symbol})}) if the command is complete and valid;
return \code{None} if the command is incomplete; raise
\code{SyntaxError} if the command is a syntax error.
\end{funcdesc}
% Documentation written by Sue Williams.
\section{Standard Module \module{commands}}
\stmodindex{commands}
\label{module-commands}
The \module{commands} module contains wrapper functions for
\function{os.popen()} which take a system command as a string and
return any output generated by the command and, optionally, the exit
status.
The \module{commands} module is only usable on systems which support
\function{os.popen()} (currently \UNIX{}). It defines the following
functions:
\begin{funcdesc}{getstatusoutput}{cmd}
Execute the string \var{cmd} in a shell with \function{os.popen()} and
return a 2-tuple \code{(\var{status}, \var{output})}. \var{cmd} is
actually run as \code{\{ \var{cmd} ; \} 2>\&1}, so that the returned
output will contain output or error messages. A trailing newline is
stripped from the output. The exit status for the command can be
interpreted according to the rules for the \C{} function
\cfunction{wait()}.
\end{funcdesc}
\begin{funcdesc}{getoutput}{cmd}
Like \function{getstatusoutput()}, except the exit status is ignored
and the return value is a string containing the command's output.
\end{funcdesc}
\begin{funcdesc}{getstatus}{file}
Return the output of \samp{ls -ld \var{file}} as a string. This
function uses the \function{getoutput()} function, and properly
escapes backslashes and dollar signs in the argument.
\end{funcdesc}
Example:
\begin{verbatim}
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
\end{verbatim}
\section{Standard Module \module{copy}}
\label{module-copy}
\stmodindex{copy}
\setindexsubitem{(copy function)}
\ttindex{copy}
\ttindex{deepcopy}
This module provides generic (shallow and deep) copying operations.
Interface summary:
\begin{verbatim}
import copy
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
\end{verbatim}
%
For module specific errors, \code{copy.error} is raised.
The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or
class instances):
\begin{itemize}
\item
A \emph{shallow copy} constructs a new compound object and then (to the
extent possible) inserts \emph{references} into it to the objects found
in the original.
\item
A \emph{deep copy} constructs a new compound object and then,
recursively, inserts \emph{copies} into it of the objects found in the
original.
\end{itemize}
Two problems often exist with deep copy operations that don't exist
with shallow copy operations:
\begin{itemize}
\item
Recursive objects (compound objects that, directly or indirectly,
contain a reference to themselves) may cause a recursive loop.
\item
Because deep copy copies \emph{everything} it may copy too much, e.g.\
administrative data structures that should be shared even between
copies.
\end{itemize}
Python's \code{deepcopy()} operation avoids these problems by:
\begin{itemize}
\item
keeping a table of objects already copied during the current
copying pass; and
\item
letting user-defined classes override the copying operation or the
set of components copied.
\end{itemize}
This version does not copy types like module, class, function, method,
nor stack trace, stack frame, nor file, socket, window, nor array, nor
any similar types.
Classes can use the same interfaces to control copying that they use
to control pickling: they can define methods called
\code{__getinitargs__()}, \code{__getstate__()} and
\code{__setstate__()}. See the description of module \code{pickle}
for information on these methods.
\refstmodindex{pickle}
\setindexsubitem{(copy protocol)}
\ttindex{__getinitargs__}
\ttindex{__getstate__}
\ttindex{__setstate__}
\section{Standard Module \module{copy_reg}}
% Note that the label is a little off; the underscore causes LaTeX to
% yell & scream.
\label{module-copyreg}
\stmodindex{copy_reg}
The \code{copy_reg} module provides support for the
\code{pickle}\refstmodindex{pickle} and
\code{cPickle}\refbimodindex{cPickle} modules. The
\code{copy}\refstmodindex{copy} module is likely to use this in the
future as well. It provides configuration information about object
constructors which are not classes. Such constructors may be factory
functions or class instances.
\begin{funcdesc}{constructor}{object}
Declares \var{object} to be a valid constructor.
\end{funcdesc}
\begin{funcdesc}{pickle}{type, function\optional{, constructor}}
Declares that \var{function} should be used as a ``reduction''
function for objects of type or class \var{type}. \var{function}
should return either a string or a tuple. The optional
\var{constructor} parameter, if provided, is a callable object which
can be used to reconstruct the object when called with the tuple of
arguments returned by \var{function} at pickling time.
\end{funcdesc}
\section{Built-in Module \module{crypt}}
\label{module-crypt}
\bimodindex{crypt}
This module implements an interface to the \manpage{crypt}{3} routine,
which is a one-way hash function based upon a modified DES algorithm;
see the \UNIX{} man page for further details. Possible uses include
allowing Python scripts to accept typed passwords from the user, or
attempting to crack \UNIX{} passwords with a dictionary.
\index{crypt(3)}
\begin{funcdesc}{crypt}{word, salt}
\var{word} will usually be a user's password. \var{salt} is a
2-character string which will be used to select one of 4096 variations
of DES\indexii{cipher}{DES}. The characters in \var{salt} must be
either \code{.}, \code{/}, or an alphanumeric character. Returns the
hashed password as a string, which will be composed of characters from
the same alphabet as the salt.
\end{funcdesc}
The module and documentation were written by Steve Majewski.
\index{Majewski, Steve}
\chapter{Cryptographic Services}
\label{crypto}
\index{cryptography}
The modules described in this chapter implement various algorithms of
a cryptographic nature. They are available at the discretion of the
installation. Here's an overview:
\begin{description}
\item[md5]
--- RSA's MD5 message digest algorithm.
\item[mpz]
--- Interface to the GNU MP library for arbitrary precision arithmetic.
\item[rotor]
--- Enigma-like encryption and decryption.
\end{description}
Hardcore cypherpunks will probably find the cryptographic modules
written by Andrew Kuchling of further interest; the package adds
built-in modules for DES and IDEA encryption, provides a Python module
for reading and decrypting PGP files, and then some. These modules
are not distributed with Python but available separately. See the URL
\url{http://starship.skyport.net/crew/amk/maintained/crypto.html} or
send email to \email{akuchlin@acm.org} for more information.
\index{PGP}
\index{Pretty Good Privacy}
\indexii{DES}{cipher}
\indexii{IDEA}{cipher}
\index{cryptography}
\index{Kuchling, Andrew}
\section{Built-in Module \module{dbm}}
\label{module-dbm}
\bimodindex{dbm}
The \code{dbm} module provides an interface to the \UNIX{}
\code{(n)dbm} library. Dbm objects behave like mappings
(dictionaries), except that keys and values are always strings.
Printing a dbm object doesn't print the keys and values, and the
\code{items()} and \code{values()} methods are not supported.
See also the \code{gdbm} module, which provides a similar interface
using the GNU GDBM library.
\refbimodindex{gdbm}
The module defines the following constant and functions:
\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, \optional{flag, \optional{mode}}}
Open a dbm database and return a dbm object. The \var{filename}
argument is the name of the database file (without the \file{.dir} or
\file{.pag} extensions).
The optional \var{flag} argument can be
\code{'r'} (to open an existing database for reading only --- default),
\code{'w'} (to open an existing database for reading and writing),
\code{'c'} (which creates the database if it doesn't exist), or
\code{'n'} (which always creates a new empty database).
The optional \var{mode} argument is the \UNIX{} mode of the file, used
only when the database has to be created. It defaults to octal
\code{0666}.
\end{funcdesc}
This diff is collapsed.
\section{Standard Module \module{errno}}
\label{module-errno}
\stmodindex{errno}
This module makes available standard errno system symbols.
The value of each symbol is the corresponding integer value.
The names and descriptions are borrowed from \file{linux/include/errno.h},
which should be pretty all-inclusive.
\begin{datadesc}{errorcode}
Dictionary providing a mapping from the errno value to the string
name in the underlying system. For instance,
\code{errno.errorcode[errno.EPERM]} maps to \code{'EPERM'}.
\end{datadesc}
To translate a numeric error code to an error message, use
\function{os.strerror()}.
Of the following list, symbols that are not used on the current
platform are not defined by the module. Symbols available can
include:
\begin{datadesc}{EPERM} Operation not permitted \end{datadesc}
\begin{datadesc}{ENOENT} No such file or directory \end{datadesc}
\begin{datadesc}{ESRCH} No such process \end{datadesc}
\begin{datadesc}{EINTR} Interrupted system call \end{datadesc}
\begin{datadesc}{EIO} I/O error \end{datadesc}
\begin{datadesc}{ENXIO} No such device or address \end{datadesc}
\begin{datadesc}{E2BIG} Arg list too long \end{datadesc}
\begin{datadesc}{ENOEXEC} Exec format error \end{datadesc}
\begin{datadesc}{EBADF} Bad file number \end{datadesc}
\begin{datadesc}{ECHILD} No child processes \end{datadesc}
\begin{datadesc}{EAGAIN} Try again \end{datadesc}
\begin{datadesc}{ENOMEM} Out of memory \end{datadesc}
\begin{datadesc}{EACCES} Permission denied \end{datadesc}
\begin{datadesc}{EFAULT} Bad address \end{datadesc}
\begin{datadesc}{ENOTBLK} Block device required \end{datadesc}
\begin{datadesc}{EBUSY} Device or resource busy \end{datadesc}
\begin{datadesc}{EEXIST} File exists \end{datadesc}
\begin{datadesc}{EXDEV} Cross-device link \end{datadesc}
\begin{datadesc}{ENODEV} No such device \end{datadesc}
\begin{datadesc}{ENOTDIR} Not a directory \end{datadesc}
\begin{datadesc}{EISDIR} Is a directory \end{datadesc}
\begin{datadesc}{EINVAL} Invalid argument \end{datadesc}
\begin{datadesc}{ENFILE} File table overflow \end{datadesc}
\begin{datadesc}{EMFILE} Too many open files \end{datadesc}
\begin{datadesc}{ENOTTY} Not a typewriter \end{datadesc}
\begin{datadesc}{ETXTBSY} Text file busy \end{datadesc}
\begin{datadesc}{EFBIG} File too large \end{datadesc}
\begin{datadesc}{ENOSPC} No space left on device \end{datadesc}
\begin{datadesc}{ESPIPE} Illegal seek \end{datadesc}
\begin{datadesc}{EROFS} Read-only file system \end{datadesc}
\begin{datadesc}{EMLINK} Too many links \end{datadesc}
\begin{datadesc}{EPIPE} Broken pipe \end{datadesc}
\begin{datadesc}{EDOM} Math argument out of domain of func \end{datadesc}
\begin{datadesc}{ERANGE} Math result not representable \end{datadesc}
\begin{datadesc}{EDEADLK} Resource deadlock would occur \end{datadesc}
\begin{datadesc}{ENAMETOOLONG} File name too long \end{datadesc}
\begin{datadesc}{ENOLCK} No record locks available \end{datadesc}
\begin{datadesc}{ENOSYS} Function not implemented \end{datadesc}
\begin{datadesc}{ENOTEMPTY} Directory not empty \end{datadesc}
\begin{datadesc}{ELOOP} Too many symbolic links encountered \end{datadesc}
\begin{datadesc}{EWOULDBLOCK} Operation would block \end{datadesc}
\begin{datadesc}{ENOMSG} No message of desired type \end{datadesc}
\begin{datadesc}{EIDRM} Identifier removed \end{datadesc}
\begin{datadesc}{ECHRNG} Channel number out of range \end{datadesc}
\begin{datadesc}{EL2NSYNC} Level 2 not synchronized \end{datadesc}
\begin{datadesc}{EL3HLT} Level 3 halted \end{datadesc}
\begin{datadesc}{EL3RST} Level 3 reset \end{datadesc}
\begin{datadesc}{ELNRNG} Link number out of range \end{datadesc}
\begin{datadesc}{EUNATCH} Protocol driver not attached \end{datadesc}
\begin{datadesc}{ENOCSI} No CSI structure available \end{datadesc}
\begin{datadesc}{EL2HLT} Level 2 halted \end{datadesc}
\begin{datadesc}{EBADE} Invalid exchange \end{datadesc}
\begin{datadesc}{EBADR} Invalid request descriptor \end{datadesc}
\begin{datadesc}{EXFULL} Exchange full \end{datadesc}
\begin{datadesc}{ENOANO} No anode \end{datadesc}
\begin{datadesc}{EBADRQC} Invalid request code \end{datadesc}
\begin{datadesc}{EBADSLT} Invalid slot \end{datadesc}
\begin{datadesc}{EDEADLOCK} File locking deadlock error \end{datadesc}
\begin{datadesc}{EBFONT} Bad font file format \end{datadesc}
\begin{datadesc}{ENOSTR} Device not a stream \end{datadesc}
\begin{datadesc}{ENODATA} No data available \end{datadesc}
\begin{datadesc}{ETIME} Timer expired \end{datadesc}
\begin{datadesc}{ENOSR} Out of streams resources \end{datadesc}
\begin{datadesc}{ENONET} Machine is not on the network \end{datadesc}
\begin{datadesc}{ENOPKG} Package not installed \end{datadesc}
\begin{datadesc}{EREMOTE} Object is remote \end{datadesc}
\begin{datadesc}{ENOLINK} Link has been severed \end{datadesc}
\begin{datadesc}{EADV} Advertise error \end{datadesc}
\begin{datadesc}{ESRMNT} Srmount error \end{datadesc}
\begin{datadesc}{ECOMM} Communication error on send \end{datadesc}
\begin{datadesc}{EPROTO} Protocol error \end{datadesc}
\begin{datadesc}{EMULTIHOP} Multihop attempted \end{datadesc}
\begin{datadesc}{EDOTDOT} RFS specific error \end{datadesc}
\begin{datadesc}{EBADMSG} Not a data message \end{datadesc}
\begin{datadesc}{EOVERFLOW} Value too large for defined data type \end{datadesc}
\begin{datadesc}{ENOTUNIQ} Name not unique on network \end{datadesc}
\begin{datadesc}{EBADFD} File descriptor in bad state \end{datadesc}
\begin{datadesc}{EREMCHG} Remote address changed \end{datadesc}
\begin{datadesc}{ELIBACC} Can not access a needed shared library \end{datadesc}
\begin{datadesc}{ELIBBAD} Accessing a corrupted shared library \end{datadesc}
\begin{datadesc}{ELIBSCN} .lib section in a.out corrupted \end{datadesc}
\begin{datadesc}{ELIBMAX} Attempting to link in too many shared libraries \end{datadesc}
\begin{datadesc}{ELIBEXEC} Cannot exec a shared library directly \end{datadesc}
\begin{datadesc}{EILSEQ} Illegal byte sequence \end{datadesc}
\begin{datadesc}{ERESTART} Interrupted system call should be restarted \end{datadesc}
\begin{datadesc}{ESTRPIPE} Streams pipe error \end{datadesc}
\begin{datadesc}{EUSERS} Too many users \end{datadesc}
\begin{datadesc}{ENOTSOCK} Socket operation on non-socket \end{datadesc}
\begin{datadesc}{EDESTADDRREQ} Destination address required \end{datadesc}
\begin{datadesc}{EMSGSIZE} Message too long \end{datadesc}
\begin{datadesc}{EPROTOTYPE} Protocol wrong type for socket \end{datadesc}
\begin{datadesc}{ENOPROTOOPT} Protocol not available \end{datadesc}
\begin{datadesc}{EPROTONOSUPPORT} Protocol not supported \end{datadesc}
\begin{datadesc}{ESOCKTNOSUPPORT} Socket type not supported \end{datadesc}
\begin{datadesc}{EOPNOTSUPP} Operation not supported on transport endpoint \end{datadesc}
\begin{datadesc}{EPFNOSUPPORT} Protocol family not supported \end{datadesc}
\begin{datadesc}{EAFNOSUPPORT} Address family not supported by protocol \end{datadesc}
\begin{datadesc}{EADDRINUSE} Address already in use \end{datadesc}
\begin{datadesc}{EADDRNOTAVAIL} Cannot assign requested address \end{datadesc}
\begin{datadesc}{ENETDOWN} Network is down \end{datadesc}
\begin{datadesc}{ENETUNREACH} Network is unreachable \end{datadesc}
\begin{datadesc}{ENETRESET} Network dropped connection because of reset \end{datadesc}
\begin{datadesc}{ECONNABORTED} Software caused connection abort \end{datadesc}
\begin{datadesc}{ECONNRESET} Connection reset by peer \end{datadesc}
\begin{datadesc}{ENOBUFS} No buffer space available \end{datadesc}
\begin{datadesc}{EISCONN} Transport endpoint is already connected \end{datadesc}
\begin{datadesc}{ENOTCONN} Transport endpoint is not connected \end{datadesc}
\begin{datadesc}{ESHUTDOWN} Cannot send after transport endpoint shutdown \end{datadesc}
\begin{datadesc}{ETOOMANYREFS} Too many references: cannot splice \end{datadesc}
\begin{datadesc}{ETIMEDOUT} Connection timed out \end{datadesc}
\begin{datadesc}{ECONNREFUSED} Connection refused \end{datadesc}
\begin{datadesc}{EHOSTDOWN} Host is down \end{datadesc}
\begin{datadesc}{EHOSTUNREACH} No route to host \end{datadesc}
\begin{datadesc}{EALREADY} Operation already in progress \end{datadesc}
\begin{datadesc}{EINPROGRESS} Operation now in progress \end{datadesc}
\begin{datadesc}{ESTALE} Stale NFS file handle \end{datadesc}
\begin{datadesc}{EUCLEAN} Structure needs cleaning \end{datadesc}
\begin{datadesc}{ENOTNAM} Not a XENIX named type file \end{datadesc}
\begin{datadesc}{ENAVAIL} No XENIX semaphores available \end{datadesc}
\begin{datadesc}{EISNAM} Is a named type file \end{datadesc}
\begin{datadesc}{EREMOTEIO} Remote I/O error \end{datadesc}
\begin{datadesc}{EDQUOT} Quota exceeded \end{datadesc}
This diff is collapsed.
% Manual text by Jaap Vermeulen
\section{Built-in Module \module{fcntl}}
\label{module-fcntl}
\bimodindex{fcntl}
\indexii{UNIX@\UNIX{}}{file control}
\indexii{UNIX@\UNIX{}}{I/O control}
This module performs file control and I/O control on file descriptors.
It is an interface to the \cfunction{fcntl()} and \cfunction{ioctl()}
\UNIX{} routines. File descriptors can be obtained with the
\method{fileno()} method of a file or socket object.
The module defines the following functions:
\begin{funcdesc}{fcntl}{fd, op\optional{, arg}}
Perform the requested operation on file descriptor \var{fd}.
The operation is defined by \var{op} and is operating system
dependent. Typically these codes can be retrieved from the library
module \module{FCNTL}\refstmodindex{FCNTL}. The argument \var{arg}
is optional, and defaults to the integer value \code{0}. When
present, it can either be an integer value, or a string. With
the argument missing or an integer value, the return value of this
function is the integer return value of the \C{} \cfunction{fcntl()}
call. When the argument is a string it represents a binary
structure, e.g.\ created by \function{struct.pack()}. The binary
data is copied to a buffer whose address is passed to the \C{}
\cfunction{fcntl()} call. The return value after a successful call
is the contents of the buffer, converted to a string object. In
case the \cfunction{fcntl()} fails, an \exception{IOError} is
raised.
\end{funcdesc}
\begin{funcdesc}{ioctl}{fd, op, arg}
This function is identical to the \function{fcntl()} function, except
that the operations are typically defined in the library module
\module{IOCTL}.
\end{funcdesc}
\begin{funcdesc}{flock}{fd, op}
Perform the lock operation \var{op} on file descriptor \var{fd}.
See the \UNIX{} manual \manpage{flock}{3} for details. (On some
systems, this function is emulated using \cfunction{fcntl()}.)
\end{funcdesc}
\begin{funcdesc}{lockf}{fd, code, \optional{len, \optional{start, \optional{whence}}}}
This is a wrapper around the \constant{FCNTL.F_SETLK} and
\constant{FCNTL.F_SETLKW} \function{fcntl()} calls. See the \UNIX{}
manual for details.
\end{funcdesc}
If the library modules \module{FCNTL}\refstmodindex{FCNTL} or
\module{IOCTL}\refstmodindex{IOCTL} are missing, you can find the
opcodes in the \C{} include files \code{<sys/fcntl.h>} and
\code{<sys/ioctl.h>}. You can create the modules yourself with the
\program{h2py} script, found in the \file{Tools/scripts/} directory.
Examples (all on a SVR4 compliant system):
\begin{verbatim}
import struct, FCNTL
file = open(...)
rv = fcntl(file.fileno(), FCNTL.O_NDELAY, 1)
lockdata = struct.pack('hhllhh', FCNTL.F_WRLCK, 0, 0, 0, 0, 0)
rv = fcntl(file.fileno(), FCNTL.F_SETLKW, lockdata)
\end{verbatim}
Note that in the first example the return value variable \code{rv} will
hold an integer value; in the second example it will hold a string
value. The structure lay-out for the \var{lockdata} variable is
system dependent --- therefore using the \function{flock()} call may be
better.
% Documentation heavily adapted from module docstring.
\section{Standard Module \module{fileinput}}
\stmodindex{fileinput}
\label{module-fileinput}
This module implements a helper class and functions to quickly write a
loop over standard input or a list of files.
The typical use is:
\begin{verbatim}
import fileinput
for line in fileinput.input():
process(line)
\end{verbatim}
This iterates over the lines of all files listed in
\code{sys.argv[1:]}, defaulting to \code{sys.stdin} if the list is
empty. If a filename is \code{'-'}, it is also replaced by
\code{sys.stdin}. To specify an alternative list of filenames, pass
it as the first argument to \function{input()}. A single file name is
also allowed.
All files are opened in text mode. If an I/O error occurs during
opening or reading a file, \exception{IOError} is raised.
If \code{sys.stdin} is used more than once, the second and further use
will return no lines, except perhaps for interactive use, or if it has
been explicitly reset (e.g. using \code{sys.stdin.seek(0)}).
Empty files are opened and immediately closed; the only time their
presence in the list of filenames is noticeable at all is when the
last file opened is empty.
It is possible that the last line of a file does not end in a newline
character; lines are returned including the trailing newline when it
is present.
The following function is the primary interface of this module:
\begin{funcdesc}{input}{\optional{files\optional{,
inplace\optional{, backup}}}}
Create an instance of the \class{FileInput} class. The instance
will be used as global state for the functions of this module, and
is also returned to use during iteration.
\end{funcdesc}
The following functions use the global state created by
\function{input()}; if there is no active state,
\exception{RuntimeError} is raised.
\begin{funcdesc}{filename}{}
Return the name of the file currently being read. Before the first
line has been read, returns \code{None}.
\end{funcdesc}
\begin{funcdesc}{lineno}{}
Return the cumulative line number of the line that has just been
read. Before the first line has been read, returns \code{0}. After
the last line of the last file has been read, returns the line
number of that line.
\end{funcdesc}
\begin{funcdesc}{filelineno}{}
Return the line number in the current file. Before the first line
has been read, returns \code{0}. After the last line of the last
file has been read, returns the line number of that line within the
file.
\end{funcdesc}
\begin{funcdesc}{isfirstline}{}
Return true iff the line just read is the first line of its file.
\end{funcdesc}
\begin{funcdesc}{isstdin}{}
Returns true iff the last line was read from \code{sys.stdin}.
\end{funcdesc}
\begin{funcdesc}{nextfile}{}
Close the current file so that the next iteration will read the
first line from the next file (if any); lines not read from the file
will not count towards the cumulative line count. The filename is
not changed until after the first line of the next file has been
read. Before the first line has been read, this function has no
effect; it cannot be used to skip the first file. After the last
line of the last file has been read, this function has no effect.
\end{funcdesc}
\begin{funcdesc}{close}{}
Close the sequence.
\end{funcdesc}
The class which implements the sequence behavior provided by the
module is available for subclassing as well:
\begin{classdesc}{FileInput}{\optional{files\optional{,
inplace\optional{, backup}}}}
Class \class{FileInput} is the implementation; its methods
\method{filename()}, \method{lineno()}, \method{fileline()},
\method{isfirstline()}, \method{isstdin()}, \method{nextfile()} and
\method{close()} correspond to the functions of the same name in the
module. In addition it has a \method{readline()} method which
returns the next input line, and a \method{__getitem__()} method
which implements the sequence behavior. The sequence must be
accessed in strictly sequential order; random access and
\method{readline()} cannot be mixed.
\end{classdesc}
\strong{Optional in-place filtering:} if the keyword argument
\code{\var{inplace}=1} is passed to \function{input()} or to the
\class{FileInput} constructor, the file is moved to a backup file and
standard output is directed to the input file.
This makes it possible to write a filter that rewrites its input file
in place. If the keyword argument \code{\var{backup}='.<some
extension>'} is also given, it specifies the extension for the backup
file, and the backup file remains around; by default, the extension is
\code{'.bak'} and it is deleted when the output file is closed. In-place
filtering is disabled when standard input is read.
\strong{Caveat:} The current implementation does not work for MS-DOS
8+3 filesystems.
This diff is collapsed.
\section{Built-in Module \module{fm}}
\label{module-fm}
\bimodindex{fm}
This module provides access to the IRIS \emph{Font Manager} library.
\index{Font Manager, IRIS}
\index{IRIS Font Manager}
It is available only on Silicon Graphics machines.
See also: \emph{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:
\begin{funcdesc}{init}{}
Initialization function.
Calls \cfunction{fminit()}.
It is normally not necessary to call this function, since it is called
automatically the first time the \module{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 \cfunction{fmenumerate()}.
\end{funcdesc}
\begin{funcdesc}{prstr}{string}
Render a string using the current font (see the \function{setfont()} font
handle method below).
Calls \code{fmprstr(\var{string})}.
\end{funcdesc}
\begin{funcdesc}{setpath}{string}
Sets the font search path.
Calls \code{fmsetpath(\var{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:
\setindexsubitem{(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}\code{)}.
\end{funcdesc}
\begin{funcdesc}{getstrwidth}{string}
Returns the width, in pixels, of \var{string} when drawn in this font.
Calls \code{fmgetstrwidth(\var{fh}, \var{string})}.
\end{funcdesc}
\section{Standard Module \module{fnmatch}}
\label{module-fnmatch}
\stmodindex{fnmatch}
This module provides support for \UNIX{} shell-style wildcards, which
are \emph{not} the same as regular expressions (which are documented
in the \module{re}\refstmodindex{re} module). The special characters
used in shell-style wildcards are:
\begin{list}{}{\leftmargin 0.5in \labelwidth 0.45in}
\item[\code{*}] matches everything
\item[\code{?}] matches any single character
\item[\code{[}\var{seq}\code{]}] matches any character in \var{seq}
\item[\code{[!}\var{seq}\code{]}] matches any character not in \var{seq}
\end{list}
Note that the filename separator (\code{'/'} on \UNIX{}) is \emph{not}
special to this module. See module \code{glob}\refstmodindex{glob}
for pathname expansion (\module{glob} uses \function{fnmatch()} to
match filename segments).
\begin{funcdesc}{fnmatch}{filename, pattern}
Test whether the \var{filename} string matches the \var{pattern}
string, returning true or false. If the operating system is
case-insensitive, then both parameters will be normalized to all
lower- or upper-case before the comparision is performed. If you
require a case-sensitive comparision regardless of whether that's
standard for your operating system, use \function{fnmatchcase()}
instead.
\end{funcdesc}
\begin{funcdesc}{fnmatchcase}{filename, pattern}
Test whether \var{filename} matches \var{pattern}, returning true or
false; the comparision is case-sensitive.
\end{funcdesc}
\begin{seealso}
\seemodule{glob}{Shell-style path expansion}
\end{seealso}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment