mass changes; fix titles; add examples; correct typos; clarifications;

unified style; etc.
This commit is contained in:
Guido van Rossum 1995-03-17 16:07:09 +00:00
parent 7760cdea81
commit 470be14c8a
131 changed files with 1960 additions and 1114 deletions

View File

@ -21,8 +21,11 @@ Module \code{aifc} defines the following function:
Open an AIFF or AIFF-C file and return an object instance with Open an AIFF or AIFF-C file and return an object instance with
methods that are described below. The argument file is either a 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 string naming a file or a file object. The mode is either the string
'r' when the file must be opened for reading, or 'w' when the file \code{'r'} when the file must be opened for reading, or \code{'w'}
must be opened for writing. 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
\code{writeframesraw()} and \code{setnframes()}.
\end{funcdesc} \end{funcdesc}
Objects returned by \code{aifc.open()} when a file is opened for Objects returned by \code{aifc.open()} when a file is opened for

View File

@ -1,13 +1,15 @@
\section{Built-in Module \sectcode{al}} \section{Built-in Module \sectcode{al}}
\bimodindex{al} \bimodindex{al}
This module provides access to the audio facilities of the Indigo and This module provides access to the audio facilities of the SGI Indy
4D/35 workstations, described in section 3A of the IRIX 4.0 man pages and Indigo workstations. See section 3A of the IRIX man pages for
(and also available as an option in IRIX 3.3). You'll need to read details. You'll need to read those man pages to understand what these
those man pages to understand what these functions do! functions do! Some of the functions are not available in IRIX
Some of the functions are not available in releases below 4.0.5. releases before 4.0.5. Again, see the manual to check whether a
Again, see the manual to check whether a specific function is specific function is available on your platform.
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 \file{<audio.h>} are defined Symbolic constants from the C header file \file{<audio.h>} are defined
in the standard module \code{AL}, see below. in the standard module \code{AL}, see below.
@ -20,145 +22,138 @@ interface can provide no protection against this kind of problems.
(One example is specifying an excessive queue size --- there is no (One example is specifying an excessive queue size --- there is no
documented upper limit.) documented upper limit.)
Module \code{al} defines the following functions: The module defines the following functions:
\renewcommand{\indexsubitem}{(in module al)} \renewcommand{\indexsubitem}{(in module al)}
\begin{funcdesc}{openport}{name\, direction\optional{\, config}} \begin{funcdesc}{openport}{name\, direction\optional{\, config}}
Equivalent to the C function ALopenport(). The name and direction The name and direction arguments are strings. The optional config
arguments are strings. The optional config argument is an opaque argument is a configuration object as returned by
configuration object as returned by \code{al.newconfig()}. The return \code{al.newconfig()}. The return value is an \dfn{port object};
value is an opaque port object; methods of port objects are described methods of port objects are described below.
below.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{newconfig}{} \begin{funcdesc}{newconfig}{}
Equivalent to the C function ALnewconfig(). The return value is a new The return value is a new \dfn{configuration object}; methods of
opaque configuration object; methods of configuration objects are configuration objects are described below.
described below.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{queryparams}{device} \begin{funcdesc}{queryparams}{device}
Equivalent to the C function ALqueryparams(). The device argument is The device argument is an integer. The return value is a list of
an integer. The return value is a list of integers containing the integers containing the data returned by ALqueryparams().
data returned by ALqueryparams().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getparams}{device\, list} \begin{funcdesc}{getparams}{device\, list}
Equivalent to the C function ALgetparams(). The device argument is an The device argument is an integer. The list argument is a list such
integer. The list argument is a list such as returned by as returned by \code{queryparams}; it is modified in place (!).
\code{queryparams}; it is modified in place (!).
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setparams}{device\, list} \begin{funcdesc}{setparams}{device\, list}
Equivalent to the C function ALsetparams(). The device argument is an The device argument is an integer. The list argument is a list such
integer.The list argument is a list such as returned by as returned by \code{al.queryparams}.
\code{al.queryparams}.
\end{funcdesc} \end{funcdesc}
\subsection{Configuration Objects}
Configuration objects (returned by \code{al.newconfig()} have the Configuration objects (returned by \code{al.newconfig()} have the
following methods: following methods:
\renewcommand{\indexsubitem}{(audio configuration object method)} \renewcommand{\indexsubitem}{(audio configuration object method)}
\begin{funcdesc}{getqueuesize}{} \begin{funcdesc}{getqueuesize}{}
Return the queue size; equivalent to the C function ALgetqueuesize(). Return the queue size.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setqueuesize}{size} \begin{funcdesc}{setqueuesize}{size}
Set the queue size; equivalent to the C function ALsetqueuesize(). Set the queue size.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getwidth}{} \begin{funcdesc}{getwidth}{}
Get the sample width; equivalent to the C function ALgetwidth(). Get the sample width.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getwidth}{width} \begin{funcdesc}{setwidth}{width}
Set the sample width; equivalent to the C function ALsetwidth(). Set the sample width.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getchannels}{} \begin{funcdesc}{getchannels}{}
Get the channel count; equivalent to the C function ALgetchannels(). Get the channel count.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setchannels}{nchannels} \begin{funcdesc}{setchannels}{nchannels}
Set the channel count; equivalent to the C function ALsetchannels(). Set the channel count.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getsampfmt}{} \begin{funcdesc}{getsampfmt}{}
Get the sample format; equivalent to the C function ALgetsampfmt(). Get the sample format.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setsampfmt}{sampfmt} \begin{funcdesc}{setsampfmt}{sampfmt}
Set the sample format; equivalent to the C function ALsetsampfmt(). Set the sample format.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getfloatmax}{} \begin{funcdesc}{getfloatmax}{}
Get the maximum value for floating sample formats; Get the maximum value for floating sample formats.
equivalent to the C function ALgetfloatmax().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setfloatmax}{floatmax} \begin{funcdesc}{setfloatmax}{floatmax}
Set the maximum value for floating sample formats; Set the maximum value for floating sample formats.
equivalent to the C function ALsetfloatmax().
\end{funcdesc} \end{funcdesc}
\subsection{Port Objects}
Port objects (returned by \code{al.openport()} have the following Port objects (returned by \code{al.openport()} have the following
methods: methods:
\renewcommand{\indexsubitem}{(audio port object method)} \renewcommand{\indexsubitem}{(audio port object method)}
\begin{funcdesc}{closeport}{} \begin{funcdesc}{closeport}{}
Close the port; equivalent to the C function ALcloseport(). Close the port.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getfd}{} \begin{funcdesc}{getfd}{}
Return the file descriptor as an int; equivalent to the C function Return the file descriptor as an int.
ALgetfd().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getfilled}{} \begin{funcdesc}{getfilled}{}
Return the number of filled samples; equivalent to the C function Return the number of filled samples.
ALgetfilled().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getfillable}{} \begin{funcdesc}{getfillable}{}
Return the number of fillable samples; equivalent to the C function Return the number of fillable samples.
ALgetfillable().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{readsamps}{nsamples} \begin{funcdesc}{readsamps}{nsamples}
Read a number of samples from the queue, blocking if necessary; Read a number of samples from the queue, blocking if necessary.
equivalent to the C function ALreadsamples. The data is returned as a Return the data as a string containing the raw data, (e.g., 2 bytes per
string containing the raw data (e.g. 2 bytes per sample in big-endian sample in big-endian byte order (high byte, low byte) if you have set
byte order (high byte, low byte) if you have set the sample width to 2 the sample width to 2 bytes).
bytes.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{writesamps}{samples} \begin{funcdesc}{writesamps}{samples}
Write samples into the queue, blocking if necessary; equivalent to the Write samples into the queue, blocking if necessary. The samples are
C function ALwritesamples. The samples are encoded as described for encoded as described for the \code{readsamps} return value.
the \code{readsamps} return value.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getfillpoint}{} \begin{funcdesc}{getfillpoint}{}
Return the `fill point'; equivalent to the C function ALgetfillpoint(). Return the `fill point'.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setfillpoint}{fillpoint} \begin{funcdesc}{setfillpoint}{fillpoint}
Set the `fill point'; equivalent to the C function ALsetfillpoint(). Set the `fill point'.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getconfig}{} \begin{funcdesc}{getconfig}{}
Return a configuration object containing the current configuration of Return a configuration object containing the current configuration of
the port; equivalent to the C function ALgetconfig(). the port.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setconfig}{config} \begin{funcdesc}{setconfig}{config}
Set the configuration from the argument, a configuration object; Set the configuration from the argument, a configuration object.
equivalent to the C function ALsetconfig().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getstatus}{list} \begin{funcdesc}{getstatus}{list}
Get status information on last error Get status information on last error.
equivalent to C function ALgetstatus().
\end{funcdesc} \end{funcdesc}
\section{Standard Module \sectcode{AL}} \section{Standard Module \sectcode{AL}}

View File

@ -70,7 +70,7 @@ Initially, the timeout is set to 2 seconds by the Python interpreter.
\subsection{Capability Operations} \subsection{Capability Operations}
Capabilities are written in a convenient ASCII format, also used by the Capabilities are written in a convenient \ASCII{} format, also used by the
Amoeba utilities Amoeba utilities
{\it c2a}(U) {\it c2a}(U)
and and

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{array}} \section{Built-in Module \sectcode{array}}
\bimodindex{array} \bimodindex{array}
\index{arrays} \index{arrays}
@ -21,7 +21,7 @@ which is a single character. The following type codes are defined:
The actual representation of values is determined by the machine The actual representation of values is determined by the machine
architecture (strictly speaking, by the C implementation). The actual architecture (strictly speaking, by the C implementation). The actual
size can be accessed through the \var{typecode} attribute. size can be accessed through the \var{itemsize} attribute.
The module defines the following function: The module defines the following function:
@ -59,7 +59,9 @@ on a machine with a different byte order.
Read \var{n} items (as machine values) from the file object \var{f} 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 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 are available, \code{EOFError} is raised, but the items that were
available are still inserted into the array. available are still inserted into the array. \var{f} must be a real
built-in file object; something else with a \code{read()} method won't
do.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{fromlist}{list} \begin{funcdesc}{fromlist}{list}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{audioop}} \section{Built-in Module \sectcode{audioop}}
\bimodindex{audioop} \bimodindex{audioop}
The \code{audioop} module contains some useful operations on sound fragments. The \code{audioop} module contains some useful operations on sound fragments.
@ -19,96 +19,97 @@ per sample, etc.
\end{excdesc} \end{excdesc}
\begin{funcdesc}{add}{fragment1\, fragment2\, width} \begin{funcdesc}{add}{fragment1\, fragment2\, width}
This function returns a fragment which is the addition of the two samples Return a fragment which is the addition of the two samples passed as
passed as parameters. \var{width} is the sample width in bytes, either parameters. \var{width} is the sample width in bytes, either
\code{1}, \code{2} or \code{4}. Both fragments should have the same length. \code{1}, \code{2} or \code{4}. Both fragments should have the same
length.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{adpcm2lin}{adpcmfragment\, width\, state} \begin{funcdesc}{adpcm2lin}{adpcmfragment\, width\, state}
This routine decodes an Intel/DVI ADPCM coded fragment to a linear Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See
fragment. See the description of \code{lin2adpcm} for details on ADPCM the description of \code{lin2adpcm} for details on ADPCM coding.
coding. The routine returns a tuple Return a tuple \code{(\var{sample}, \var{newstate})} where the sample
\code{(\var{sample}, \var{newstate})} has the width specified in \var{width}.
where the sample has the width specified in \var{width}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{adpcm32lin}{adpcmfragment\, width\, state} \begin{funcdesc}{adpcm32lin}{adpcmfragment\, width\, state}
This routine decodes an alternative 3-bit ADPCM code. See Decode an alternative 3-bit ADPCM code. See \code{lin2adpcm3} for
\code{lin2adpcm3} for details. details.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{avg}{fragment\, width} \begin{funcdesc}{avg}{fragment\, width}
This function returns the average over all samples in the fragment. Return the average over all samples in the fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{avgpp}{fragment\, width} \begin{funcdesc}{avgpp}{fragment\, width}
This function returns the average peak-peak value over all samples in Return the average peak-peak value over all samples in the fragment.
the fragment. No filtering is done, so the usefulness of this routine No filtering is done, so the usefulness of this routine is
is questionable. questionable.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{bias}{fragment\, width\, bias} \begin{funcdesc}{bias}{fragment\, width\, bias}
This function returns a fragment that is the original fragment with a Return a fragment that is the original fragment with a bias added to
bias added to each sample. each sample.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{cross}{fragment\, width} \begin{funcdesc}{cross}{fragment\, width}
This function returns the number of zero crossings in the fragment Return the number of zero crossings in the fragment passed as an
passed as an argument. argument.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{findfactor}{fragment\, reference} \begin{funcdesc}{findfactor}{fragment\, reference}
This routine (which only accepts 2-byte sample fragments) calculates a Return a factor \var{F} such that
factor \var{F} such that \code{rms(add(fragment, mul(reference, -F)))} \code{rms(add(fragment, mul(reference, -F)))} is minimal, i.e.,
is minimal, i.e.\ it calculates the factor with which you should return the factor with which you should multiply \var{reference} to
multiply \var{reference} to make it match as well as possible to make it match as well as possible to \var{fragment}. The fragments
\var{fragment}. The fragments should be the same size. should both contain 2-byte samples.
The time taken by this routine is proportional to \code{len(fragment)}. The time taken by this routine is proportional to \code{len(fragment)}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{findfit}{fragment\, reference} \begin{funcdesc}{findfit}{fragment\, reference}
This routine (which only accepts 2-byte sample fragments) tries to This routine (which only accepts 2-byte sample fragments)
match \var{reference} as well as possible to a portion of
\var{fragment} (which should be the longer fragment). It Try to match \var{reference} as well as possible to a portion of
(conceptually) does this by taking slices out of \var{fragment}, using \var{fragment} (which should be the longer fragment). This is
(conceptually) done by taking slices out of \var{fragment}, using
\code{findfactor} to compute the best match, and minimizing the \code{findfactor} to compute the best match, and minimizing the
result. result. The fragments should both contain 2-byte samples. Return a
It returns a tuple \code{(\var{offset}, \var{factor})} with \var{offset} the tuple \code{(\var{offset}, \var{factor})} where \var{offset} is the
(integer) offset into \var{fragment} where the optimal match started (integer) offset into \var{fragment} where the optimal match started
and \var{factor} the floating-point factor as per \code{findfactor}. and \var{factor} is the (floating-point) factor as per
\code{findfactor}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{findmax}{fragment\, length} \begin{funcdesc}{findmax}{fragment\, length}
This routine (which only accepts 2-byte sample fragments) searches Search \var{fragment} for a slice of length \var{length} samples (not
\var{fragment} for a slice of length \var{length} samples (not bytes!)\ bytes!)\ with maximum energy, i.e., return \var{i} for which
with maximum energy, i.e.\ it returns \var{i} for which \code{rms(fragment[i*2:(i+length)*2])} is maximal. The fragments
\code{rms(fragment[i*2:(i+length)*2])} is maximal. should both contain 2-byte samples.
The routine takes time proportional to \code{len(fragment)}. The routine takes time proportional to \code{len(fragment)}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getsample}{fragment\, width\, index} \begin{funcdesc}{getsample}{fragment\, width\, index}
This function returns the value of sample \var{index} from the Return the value of sample \var{index} from the fragment.
fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{lin2lin}{fragment\, width\, newwidth} \begin{funcdesc}{lin2lin}{fragment\, width\, newwidth}
This function converts samples between 1-, 2- and 4-byte formats. Convert samples between 1-, 2- and 4-byte formats.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{lin2adpcm}{fragment\, width\, state} \begin{funcdesc}{lin2adpcm}{fragment\, width\, state}
This function converts samples to 4 bit Intel/DVI ADPCM encoding. Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an
ADPCM coding is an adaptive coding scheme, whereby each 4 bit number adaptive coding scheme, whereby each 4 bit number is the difference
is the difference between one sample and the next, divided by a between one sample and the next, divided by a (varying) step. The
(varying) step. The Intel/DVI ADPCM algorithm has been selected for Intel/DVI ADPCM algorithm has been selected for use by the IMA, so it
use by the IMA, so it may well become a standard. may well become a standard.
\code{State} is a tuple containing the state of the coder. The coder \code{State} is a tuple containing the state of the coder. The coder
returns a tuple \code{(\var{adpcmfrag}, \var{newstate})}, and the returns a tuple \code{(\var{adpcmfrag}, \var{newstate})}, and the
\var{newstate} should be passed to the next call of lin2adpcm. In 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 initial call \code{None} can be passed as the state. \var{adpcmfrag}
the ADPCM coded fragment packed 2 4-bit values per byte. is the ADPCM coded fragment packed 2 4-bit values per byte.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{lin2adpcm3}{fragment\, width\, state} \begin{funcdesc}{lin2adpcm3}{fragment\, width\, state}
@ -119,24 +120,24 @@ discouraged.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{lin2ulaw}{fragment\, width} \begin{funcdesc}{lin2ulaw}{fragment\, width}
This function converts samples in the audio fragment to U-LAW encoding Convert samples in the audio fragment to U-LAW encoding and return
and returns this as a Python string. U-LAW is an audio encoding format this as a Python string. U-LAW is an audio encoding format whereby
whereby you get a dynamic range of about 14 bits using only 8 bit you get a dynamic range of about 14 bits using only 8 bit samples. It
samples. It is used by the Sun audio hardware, among others. is used by the Sun audio hardware, among others.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{minmax}{fragment\, width} \begin{funcdesc}{minmax}{fragment\, width}
This function returns a tuple consisting of the minimum and maximum Return a tuple consisting of the minimum and maximum values of all
values of all samples in the sound fragment. samples in the sound fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{max}{fragment\, width} \begin{funcdesc}{max}{fragment\, width}
This function returns the maximum of the {\em absolute value} of all Return the maximum of the {\em absolute value} of all samples in a
samples in a fragment. fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{maxpp}{fragment\, width} \begin{funcdesc}{maxpp}{fragment\, width}
This function returns the maximum peak-peak value in the sound fragment. Return the maximum peak-peak value in the sound fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{mul}{fragment\, width\, factor} \begin{funcdesc}{mul}{fragment\, width\, factor}
@ -146,12 +147,11 @@ silently ignored.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{reverse}{fragment\, width} \begin{funcdesc}{reverse}{fragment\, width}
This function reverses the samples in a fragment and returns the Reverse the samples in a fragment and returns the modified fragment.
modified fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{rms}{fragment\, width\, factor} \begin{funcdesc}{rms}{fragment\, width}
Returns the root-mean-square of the fragment, i.e. Return the root-mean-square of the fragment, i.e.
\iftexi \iftexi
the square root of the quotient of the sum of all squared sample value, the square root of the quotient of the sum of all squared sample value,
divided by the sumber of samples. divided by the sumber of samples.
@ -166,22 +166,22 @@ This is a measure of the power in an audio signal.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{tomono}{fragment\, width\, lfactor\, rfactor} \begin{funcdesc}{tomono}{fragment\, width\, lfactor\, rfactor}
This function converts a stereo fragment to a mono fragment. The left Convert a stereo fragment to a mono fragment. The left channel is
channel is multiplied by \var{lfactor} and the right channel by multiplied by \var{lfactor} and the right channel by \var{rfactor}
\var{rfactor} before adding the two channels to give a mono signal. before adding the two channels to give a mono signal.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{tostereo}{fragment\, width\, lfactor\, rfactor} \begin{funcdesc}{tostereo}{fragment\, width\, lfactor\, rfactor}
This function generates a stereo fragment from a mono fragment. Each Generate a stereo fragment from a mono fragment. Each pair of samples
pair of samples in the stereo fragment are computed from the mono in the stereo fragment are computed from the mono sample, whereby left
sample, whereby left channel samples are multiplied by \var{lfactor} channel samples are multiplied by \var{lfactor} and right channel
and right channel samples by \var{rfactor}. samples by \var{rfactor}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{ulaw2lin}{fragment\, width} \begin{funcdesc}{ulaw2lin}{fragment\, width}
This function converts sound fragments in ULAW encoding to linearly Convert sound fragments in ULAW encoding to linearly encoded sound
encoded sound fragments. ULAW encoding always uses 8 bits samples, so fragments. ULAW encoding always uses 8 bits samples, so \var{width}
\var{width} refers only to the sample width of the output fragment here. refers only to the sample width of the output fragment here.
\end{funcdesc} \end{funcdesc}
Note that operations such as \code{mul} or \code{max} make no Note that operations such as \code{mul} or \code{max} make no
@ -215,7 +215,7 @@ standards in which case they will not be interoperable with the
respective standards. respective standards.
The \code{find...} routines might look a bit funny at first sight. The \code{find...} routines might look a bit funny at first sight.
They are primarily meant for doing echo cancellation. A reasonably They are primarily meant to do echo cancellation. A reasonably
fast way to do this is to pick the most energetic piece of the output 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, locate that in the input sample and subtract the whole output
sample from the input sample: sample from the input sample:

View File

@ -1,6 +1,7 @@
\section{Built-in Module \sectcode{__builtin__}} \section{Built-in Module \sectcode{__builtin__}}
\bimodindex{__builtin__} \bimodindex{__builtin__}
This module provides direct access to all `built-in' identifier of 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 Python; e.g. \code{__builtin__.open} is the full name for the built-in
function \code{open}. function \code{open}. See the section on Built-in Functions in the
previous chapter.

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{cgi}} \section{Standard Module \sectcode{cgi}}
\stmodindex{cgi} \stmodindex{cgi}
\indexii{WWW}{server} \indexii{WWW}{server}
\indexii{CGI}{protocol} \indexii{CGI}{protocol}
@ -134,3 +134,85 @@ The module defines the following variable:
The shell environment, exactly as received from the http server. See The shell environment, exactly as received from the http server. See
the CGI documentation for a description of the various fields. the CGI documentation for a description of the various fields.
\end{datadesc} \end{datadesc}
\subsection{Example}
This example assumes that you have a WWW server up and running,
e.g.\ NCSA's \code{httpd}.
Place the following file in a convenient spot in the WWW server's
directory tree. E.g., if you place it in the subdirectory \file{test}
of the root directory and call it \file{test.html}, its URL will be
\file{http://\var{yourservername}/test/test.html}.
\begin{verbatim}
<TITLE>Test Form Input</TITLE>
<H1>Test Form Input</H1>
<FORM METHOD="POST" ACTION="/cgi-bin/test.py">
<INPUT NAME=Name> (Name)<br>
<INPUT NAME=Address> (Address)<br>
<INPUT TYPE=SUBMIT>
</FORM>
\end{verbatim}
Selecting this file's URL from a forms-capable browser such as Mosaic
or Netscape will bring up a simple form with two text input fields and
a ``submit'' button.
But wait. Before pressing ``submit'', a script that responds to the
form must also be installed. The test file as shown assumes that the
script is called \file{test.py} and lives in the server's
\code{cgi-bin} directory. Here's the test script:
\begin{verbatim}
#!/usr/local/bin/python
import cgi
print "Content-type: text/html"
print # End of headers!
print "<TITLE>Test Form Output</TITLE>"
print "<H1>Test Form Output</H1>"
form = cgi.SvFormContentDict() # Load the form
name = addr = None # Default: no name and address
# Extract name and address from the form, if given
if form.has_key('Name'):
name = form['Name']
if form.has_key('Address'):
addr = form['Address']
# Print an unnumbered list of the name and address, if present
print "<UL>"
if name is not None:
print "<LI>Name:", cgi.escape(name)
if addr is not None:
print "<LI>Address:", cgi.escape(addr)
print "</UL>"
\end{verbatim}
The script should be made executable (\samp{chmod +x \var{script}}).
If the Python interpreter is not located at
\file{/usr/local/bin/python} but somewhere else, the first line of the
script should be modified accordingly.
Now that everything is installed correctly, we can try out the form.
Bring up the test form in your WWW browser, fill in a name and address
in the form, and press the ``submit'' button. The script should now
run and its output is sent back to your browser. This should roughly
look as follows:
\strong{Test Form Output}
\begin{itemize}
\item Name: \var{the name you entered}
\item Address: \var{the address you entered}
\end{itemize}
If you didn't enter a name or address, the corresponding line will be
missing (since the browser doesn't send empty form fields to the
server).

View File

@ -1,5 +1,6 @@
\section{Built-in module \sectcode{copy}} \section{Standard Module \sectcode{copy}}
\stmodindex{copy} \stmodindex{copy}
\renewcommand{\indexsubitem}{(copy function)}
\ttindex{copy} \ttindex{copy}
\ttindex{deepcopy} \ttindex{deepcopy}
@ -14,7 +15,7 @@ x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y x = copy.deepcopy(y) # make a deep copy of y
\end{verbatim} \end{verbatim}
For module specific errors, \code{copy.Error} is raised. For module specific errors, \code{copy.error} is raised.
The difference between shallow and deep copying is only relevant for The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or compound objects (objects that contain other objects, like lists or
@ -74,6 +75,7 @@ to control pickling: they can define methods called
\code{__setstate__()}. See the description of module \code{pickle} \code{__setstate__()}. See the description of module \code{pickle}
for information on these methods. for information on these methods.
\stmodindex{pickle} \stmodindex{pickle}
\renewcommand{\indexsubitem}{(copy protocol)}
\ttindex{__getinitargs__} \ttindex{__getinitargs__}
\ttindex{__getstate__} \ttindex{__getstate__}
\ttindex{__setstate__} \ttindex{__setstate__}

View File

@ -5,8 +5,13 @@ a cryptographic nature. They are available at the discretion of the
installation. installation.
\index{cryptography} \index{cryptography}
%Hardcore cypherpunks will probably find the Python Cryptography Kit of Hardcore cypherpunks will probably find the Python Cryptography Kit of
%further interest; the package adds built-in modules for DES and IDEA further interest; the package adds built-in modules for DES and IDEA
%encryption, and provides a Python module for reading and decrypting PGP files. encryption, and provides a Python module for reading and decrypting
%\index{PGP}\indexii{DES}{cipher}\indexii{IDEA}{cipher} PGP files. The Python Cryptography Kit is not distributed with Python
%\index{Python Cryptography Kit} but available separately. See the URL
\file{http://www.cs.mcgill.ca/\%7Efnord/crypt.html} for more information.
\index{PGP}
\indexii{DES}{cipher}
\indexii{IDEA}{cipher}
\index{Python Cryptography Kit}

View File

@ -24,7 +24,7 @@ inappropriate error.
\begin{excdesc}{AttributeError} \begin{excdesc}{AttributeError}
% xref to attribute reference? % xref to attribute reference?
Raised when an attribute reference or assignment fails. (When an Raised when an attribute reference or assignment fails. (When an
object does not support attributes references or attribute assignments object does not support attribute references or attribute assignments
at all, \code{TypeError} is raised.) at all, \code{TypeError} is raised.)
\end{excdesc} \end{excdesc}

View File

@ -1,5 +1,5 @@
% Manual text by Jaap Vermeulen % Manual text by Jaap Vermeulen
\section{Built-in module \sectcode{fcntl}} \section{Built-in Module \sectcode{fcntl}}
\bimodindex{fcntl} \bimodindex{fcntl}
\indexii{\UNIX{}}{file control} \indexii{\UNIX{}}{file control}
\indexii{\UNIX{}}{I/O control} \indexii{\UNIX{}}{I/O control}

View File

@ -2,17 +2,18 @@
\bimodindex{fl} \bimodindex{fl}
This module provides an interface to the FORMS Library by Mark This module provides an interface to the FORMS Library by Mark
Overmars, version 2.0b. For more info about FORMS, write to Overmars. The source for the library can be retrieved by anonymous
{\tt markov@cs.ruu.nl}. ftp from host \samp{ftp.cs.ruu.nl}, directory \file{SGI/FORMS}. It
was last tested with version 2.0b.
Most functions are literal translations of their C equivalents, Most functions are literal translations of their C equivalents,
dropping the initial \samp{fl_} from their name. Constants used by the dropping the initial \samp{fl_} from their name. Constants used by
library are defined in module \code{FL} described below. the library are defined in module \code{FL} described below.
The creation of objects is a little different in Python than in C: 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 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 FORMS objects are added, all functions that add a FORMS object to a
button are methods of the Python object representing the form. form are methods of the Python object representing the form.
Consequently, there are no Python equivalents for the C functions 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_addto_form} and \code{fl_end_form}, and the equivalent of
\code{fl_bgn_form} is called \code{fl.make_form}. \code{fl_bgn_form} is called \code{fl.make_form}.
@ -26,13 +27,13 @@ Hopefully this isn't too confusing...
There are no `free objects' in the Python interface to FORMS, nor is 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 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 interface to GL event handling is available, though, so you can mix
FORMS with pure GL windows. FORMS with pure GL windows.
\strong{Please note:} importing \code{fl} implies a call to the GL function \strong{Please note:} importing \code{fl} implies a call to the GL function
\code{foreground()} and to the FORMS routine \code{fl_init()}. \code{foreground()} and to the FORMS routine \code{fl_init()}.
\subsection{Functions defined in module \sectcode{fl}} \subsection{Functions Defined in Module \sectcode{fl}}
Module \code{fl} defines the following functions. For more information Module \code{fl} defines the following functions. For more information
about what they do, see the description of the equivalent C function about what they do, see the description of the equivalent C function
@ -92,7 +93,7 @@ input string. It returns the string value as edited by the user.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{show_file_selector}{message\, directory\, pattern\, default} \begin{funcdesc}{show_file_selector}{message\, directory\, pattern\, default}
Show a dialog box inm which the user can select a file. It returns Show a dialog box in which the user can select a file. It returns
the absolute filename selected by the user, or \code{None} if the user the absolute filename selected by the user, or \code{None} if the user
presses Cancel. presses Cancel.
\end{funcdesc} \end{funcdesc}
@ -130,7 +131,7 @@ See the description in the FORMS documentation of \code{fl_color},
\code{fl_mapcolor} and \code{fl_getmcolor}. \code{fl_mapcolor} and \code{fl_getmcolor}.
\end{funcdesc} \end{funcdesc}
\subsection{Form object methods and data attributes} \subsection{Form Objects}
Form objects (returned by \code{fl.make_form()} above) have the Form objects (returned by \code{fl.make_form()} above) have the
following methods. Each method corresponds to a C function whose name following methods. Each method corresponds to a C function whose name
@ -382,7 +383,7 @@ documentation:
\lineiii{doublebuf}{int}{nonzero if double buffering on} \lineiii{doublebuf}{int}{nonzero if double buffering on}
\end{tableiii} \end{tableiii}
\subsection{FORMS object methods and data attributes} \subsection{FORMS Objects}
Besides methods specific to particular kinds of FORMS objects, all Besides methods specific to particular kinds of FORMS objects, all
FORMS objects also have the following methods: FORMS objects also have the following methods:

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{ftplib}} \section{Standard Module \sectcode{ftplib}}
\stmodindex{ftplib} \stmodindex{ftplib}
\renewcommand{\indexsubitem}{(in module ftplib)} \renewcommand{\indexsubitem}{(in module ftplib)}

View File

@ -92,8 +92,8 @@ exactly one argument.)
\var{expression} argument is parsed and evaluated as a Python \var{expression} argument is parsed and evaluated as a Python
expression (technically speaking, a condition list) using the expression (technically speaking, a condition list) using the
\var{globals} and \var{locals} dictionaries as global and local name \var{globals} and \var{locals} dictionaries as global and local name
space. If the \var{globals} dictionary is omitted it defaults to space. If the \var{locals} dictionary is omitted it defaults to
the \var{locals} dictionary. If both dictionaries are omitted, the the \var{globals} dictionary. If both dictionaries are omitted, the
expression is executed in the environment where \code{eval} is expression is executed in the environment where \code{eval} is
called. The return value is the result of the evaluated expression. called. The return value is the result of the evaluated expression.
Syntax errors are reported as exceptions. Example: Syntax errors are reported as exceptions. Example:
@ -119,20 +119,21 @@ exactly one argument.)
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{execfile}{file\optional{\, globals\optional{\, locals}}} \begin{funcdesc}{execfile}{file\optional{\, globals\optional{\, locals}}}
This function is similar to the \code{eval()} function or the This function is similar to the
\code{exec} statement, but parses a file instead of a string. It is \code{exec} statement, but parses a file instead of a string. It is
different from the \code{import} statement in that it does not use different from the \code{import} statement in that it does not use
the module administration --- it reads the file unconditionally and the module administration --- it reads the file unconditionally and
does not create a new module. does not create a new module.\footnote{It is used relatively rarely
so does not warrant being made into a statement.}
The arguments are a file name and two optional dictionaries. The The arguments are a file name and two optional dictionaries. The
file is parsed and evaluated as a sequence of Python statements file is parsed and evaluated as a sequence of Python statements
(similarly to a module) using the \var{globals} and \var{locals} (similarly to a module) using the \var{globals} and \var{locals}
dictionaries as global and local name space. If the \var{globals} dictionaries as global and local name space. If the \var{locals}
dictionary is omitted it defaults to the \var{locals} dictionary. dictionary is omitted it defaults to the \var{globals} dictionary.
If both dictionaries are omitted, the expression is executed in the If both dictionaries are omitted, the expression is executed in the
environment where \code{execfile} is called. The return value is environment where \code{execfile()} is called. The return value is
None. \code{None}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{filter}{function\, list} \begin{funcdesc}{filter}{function\, list}
@ -173,8 +174,8 @@ removed.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{hex}{x} \begin{funcdesc}{hex}{x}
Convert a number to a hexadecimal string. The result is a valid Convert an integer number (of any size) to a hexadecimal string.
Python expression. The result is a valid Python expression.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{id}{object} \begin{funcdesc}{id}{object}
@ -194,7 +195,9 @@ removed.
\begin{funcdesc}{int}{x} \begin{funcdesc}{int}{x}
Convert a number to a plain integer. The argument may be a plain or Convert a number to a plain integer. The argument may be a plain or
long integer or a floating point number. long integer or a floating point number. Conversion of floating
point numbers to integers is defined by the C semantics; normally
the conversion truncates towards zero.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{len}{s} \begin{funcdesc}{len}{s}
@ -231,8 +234,8 @@ any kind of sequence; the result is always a list.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{oct}{x} \begin{funcdesc}{oct}{x}
Convert a number to an octal string. The result is a valid Python Convert an integer number (of any size) to an octal string. The
expression. result is a valid Python expression.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}} \begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}}
@ -290,7 +293,8 @@ there's no reliable way to determine whether this is the case.}
the last element is the largest \code{\var{start} + \var{i} * the last element is the largest \code{\var{start} + \var{i} *
\var{step}} less than \var{end}; if \var{step} is negative, the last \var{step}} less than \var{end}; if \var{step} is negative, the last
element is the largest \code{\var{start} + \var{i} * \var{step}} element is the largest \code{\var{start} + \var{i} * \var{step}}
greater than \var{end}. \var{step} must not be zero. Example: greater than \var{end}. \var{step} must not be zero (or else an
exception is raised). Example:
\bcode\begin{verbatim} \bcode\begin{verbatim}
>>> range(10) >>> range(10)
@ -321,7 +325,7 @@ there's no reliable way to determine whether this is the case.}
>>> s = raw_input('--> ') >>> s = raw_input('--> ')
--> Monty Python's Flying Circus --> Monty Python's Flying Circus
>>> s >>> s
'Monty Python\'s Flying Circus' "Monty Python's Flying Circus"
>>> >>>
\end{verbatim}\ecode \end{verbatim}\ecode
\end{funcdesc} \end{funcdesc}
@ -341,13 +345,44 @@ sequence.
argument must be a module object, so it must have been successfully argument must be a module object, so it must have been successfully
imported before. This is useful if you have edited the module source 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 file using an external editor and want to try out the new version
without leaving the Python interpreter. Note that if a module is without leaving the Python interpreter. The return value is the
syntactically correct but its initialization fails, the first module object (i.e.\ the same as the \var{module} argument).
\code{import} statement for it does not import the name, but does
create a (partially initialized) module object; to reload the module There are a number of caveats:
you must first \code{import} it again (this will just make the
partially initialized module object available) before you can If a module is syntactically correct but its initialization fails, the
\code{reload()} it. first \code{import} statement for it does not bind its name locally,
but does store a (partially initialized) module object in
\code{sys.modules}. To reload the module you must first
\code{import} it again (this will bind the name to the partially
initialized module object) before you can \code{reload()} it.
When a module is reloaded, its dictionary (containing the module's
global variables) is retained. Redefinitions of names will override
the old definitions, so this is generally not a problem. If the new
version of a module does not define a name that was defined by the old
version, the old definition remains. This feature can be used to the
module's advantage if it maintains a global table or cache of objects
--- with a \code{try} statement it can test for the table's presence
and skip its initialization if desired.
It is legal though generally not very useful to reload built-in or
dynamically loaded modules, except for \code{sys}, \code{__main__} and
\code{__builtin__}. In certain cases, however, extension modules are
not designed to be initialized more than once, and may fail in
arbitrary ways when reloaded.
If a module imports objects from another module using \code{from}
{\ldots} \code{import} {\ldots}, calling \code{reload()} for the other
module does not redefine the objects imported from it --- one way
around this is to re-execute the \code{from} statement, another is to
use \code{import} and qualified names (\var{module}.\var{name})
instead.
If a module instantiates instances of a class, reloading the module
that defines the class does not affect the method definitions of the
instances --- they continue to use the old class definition. The same
is true for derived classes.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{repr}{object} \begin{funcdesc}{repr}{object}
@ -385,23 +420,25 @@ always attempt to return a string that is acceptable to \code{eval()};
its goal is to return a printable string. its goal is to return a printable string.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{tuple}{object} \begin{funcdesc}{tuple}{sequence}
Return a tuple whose items are the same and in the same order as Return a tuple whose items are the same and in the same order as
\var{object}'s items. If \var{object} is alread a tuple, it \var{sequence}'s items. If \var{sequence} is alread a tuple, it
is returned unchanged. For instance, \code{tuple('abc')} returns is returned unchanged. For instance, \code{tuple('abc')} returns
returns \code{('a', 'b', 'c')} and \code{tuple([1, 2, 3])} returns returns \code{('a', 'b', 'c')} and \code{tuple([1, 2, 3])} returns
\code{(1, 2, 3)}. \code{(1, 2, 3)}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{type}{object} \begin{funcdesc}{type}{object}
% XXXJH xref to buil-in objects here?
Return the type of an \var{object}. The return value is a type 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 object. The standard module \code{types} defines names for all
them to other type objects; e.g., the following checks if a variable built-in types.
is a string: \stmodindex{types}
\obindex{type}
For instance:
\bcode\begin{verbatim} \bcode\begin{verbatim}
>>> if type(x) == type(''): print 'It is a string' >>> import types
>>> if type(x) == types.StringType: print "It's a string"
\end{verbatim}\ecode \end{verbatim}\ecode
\end{funcdesc} \end{funcdesc}
@ -424,7 +461,7 @@ which yields the same values as the corresponding list, without
actually storing them all simultaneously. The advantage of actually storing them all simultaneously. The advantage of
\code{xrange()} over \code{range()} is minimal (since \code{xrange()} \code{xrange()} over \code{range()} is minimal (since \code{xrange()}
still has to create the values when asked for them) except when a very still has to create the values when asked for them) except when a very
large range is used on a memory-starved machine (e.g. DOS) or when all large range is used on a memory-starved machine (e.g. MS-DOS) or when all
of the range's elements are never used (e.g. when the loop is usually of the range's elements are never used (e.g. when the loop is usually
terminated with \code{break}). terminated with \code{break}).
\end{funcdesc} \end{funcdesc}

View File

@ -5,7 +5,8 @@ This module helps scripts to parse the command line arguments in
\code{sys.argv}. \code{sys.argv}.
It uses the same conventions as the \UNIX{} It uses the same conventions as the \UNIX{}
\code{getopt()} \code{getopt()}
function. function (including the special meanings of arguments of the form
\samp{-} and \samp{--}).
It defines the function It defines the function
\code{getopt.getopt(args, options)} \code{getopt.getopt(args, options)}
and the exception and the exception

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{gopherlib}} \section{Standard Module \sectcode{gopherlib}}
\stmodindex{gopherlib} \stmodindex{gopherlib}
\renewcommand{\indexsubitem}{(in module gopherlib)} \renewcommand{\indexsubitem}{(in module gopherlib)}

View File

@ -13,7 +13,7 @@ following items from the group database (see \file{<grp.h>}), in order:
The gid is an integer, name and password are strings, and the member The gid is an integer, name and password are strings, and the member
list is a list of strings. list is a list of strings.
(Note that most users are not explicitly listed as members of the (Note that most users are not explicitly listed as members of the
group(s) they are in.) group they are in according to the password database.)
An exception is raised if the entry asked for cannot be found. An exception is raised if the entry asked for cannot be found.
It defines the following items: It defines the following items:

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{htmllib}} \section{Standard Module \sectcode{htmllib}}
\stmodindex{htmllib} \stmodindex{htmllib}
\index{HTML} \index{HTML}
\index{hypertext} \index{hypertext}
@ -27,12 +27,14 @@ The following is a summary of the interface defined by
\item \item
The interface to feed data to an instance is through the \code{feed()} The interface to feed data to an instance is through the \code{feed()}
method, which takes a string argument. This can be called with as method, which takes a string argument. This can be called with as
little or as much text at a time as desired. When the data contains complete little or as much text at a time as desired;
\code{p.feed(a); p.feed(b)} has the same effect as \code{p.feed(a+b)}.
When the data contains complete
HTML elements, these are processed immediately; incomplete elements HTML elements, these are processed immediately; incomplete elements
are saved in a buffer. To force processing of all unprocessed data, are saved in a buffer. To force processing of all unprocessed data,
call the \code{close()} method. call the \code{close()} method.
Example: to parse the entire contents of a file, do Example: to parse the entire contents of a file, do\\
\code{parser.feed(open(file).read()); parser.close()}. \code{parser.feed(open(file).read()); parser.close()}.
\item \item
@ -142,7 +144,7 @@ sheets are:
\index{style sheet} \index{style sheet}
\begin{datadesc}{NullStylesheet} \begin{datadesc}{NullStylesheet}
A style sheet for use on a dumb output device such as an ASCII A style sheet for use on a dumb output device such as an \ASCII{}
terminal. terminal.
\end{datadesc} \end{datadesc}
@ -242,9 +244,9 @@ spaces.
\end{funcdesc} \end{funcdesc}
\begin{datadesc}{nospace} \begin{datadesc}{nospace}
If this instance variable is true, empty words are ignored by If this instance variable is true, empty words should be ignored by
\code{addword}. It is set to false after a non-empty word has been \code{addword}. It should be set to false after a non-empty word has
added. been added.
\end{datadesc} \end{datadesc}
\begin{funcdesc}{setjust}{justification} \begin{funcdesc}{setjust}{justification}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{httplib}} \section{Standard Module \sectcode{httplib}}
\stmodindex{httplib} \stmodindex{httplib}
\index{HTTP} \index{HTTP}
@ -15,7 +15,15 @@ instantiated passing it a host and optional port number. If no port
number is passed, the port is extracted from the host string if it has number is passed, the port is extracted from the host string if it has
the form \code{host:port}, else the default HTTP port (80) is used. the form \code{host:port}, else the default HTTP port (80) is used.
If no host is passed, no connection is made, and the \code{connect} If no host is passed, no connection is made, and the \code{connect}
method should be used to connect to a server. method should be used to connect to a server. For example, the
following calls all create instances that connect to the server at the
same host and port:
\begin{verbatim}
>>> h1 = httplib.HTTP('www.cwi.nl')
>>> h2 = httplib.HTTP('www.cwi.nl:80')
>>> h3 = httplib.HTTP('www.cwi.nl', 80)
\end{verbatim}
Once an \code{HTTP} instance has been connected to an HTTP server, it Once an \code{HTTP} instance has been connected to an HTTP server, it
should be used as follows: should be used as follows:
@ -27,7 +35,7 @@ should be used as follows:
\item[2.] Make zero or more calls to the \code{putheader()} method. \item[2.] Make zero or more calls to the \code{putheader()} method.
\item[3.] Call the \code{endheaders()} method (this can be omitted if \item[3.] Call the \code{endheaders()} method (this can be omitted if
step 4. makes no calls). step 4 makes no calls).
\item[4.] Optional calls to the \code{send()} method. \item[4.] Optional calls to the \code{send()} method.
@ -93,3 +101,22 @@ Return a file object from which the data returned by the server can be
read, using the \code{read()}, \code{readline()} or \code{readlines()} read, using the \code{read()}, \code{readline()} or \code{readlines()}
methods. methods.
\end{funcdesc} \end{funcdesc}
\subsection{Example}
Here is an example session:
\begin{verbatim}
>>> import httplib
>>> h = httplib.HTTP('www.cwi.nl')
>>> h.putrequest('GET', '/index.html')
>>> h.putheader('Accept', 'text/html')
>>> h.putheader('Accept', 'text/plain')
>>> h.endheaders()
>>> errcode, errmsg, headers = h.getreply()
>>> print errcode # Should be 200
>>> f = h.getfile()
>>> data f.read() # Get the raw HTML
>>> f.close()
>>>
\end{verbatim}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{imageop}} \section{Built-in Module \sectcode{imageop}}
\bimodindex{imageop} \bimodindex{imageop}
The \code{imageop} module contains some useful operations on images. The \code{imageop} module contains some useful operations on images.
@ -17,49 +17,48 @@ per pixel, etc.
\begin{funcdesc}{crop}{image\, psize\, width\, height\, x0\, y0\, x1\, y1} \begin{funcdesc}{crop}{image\, psize\, width\, height\, x0\, y0\, x1\, y1}
This function takes the image in \var{image}, which should by Return the selected part of \var{image}, which should by
\var{width} by \var{height} in size and consist of pixels of \var{width} by \var{height} in size and consist of pixels of
\var{psize} bytes, and returns the selected part of that image. \var{x0}, \var{psize} bytes. \var{x0}, \var{y0}, \var{x1} and \var{y1} are like
\var{y0}, \var{x1} and \var{y1} are like the \code{lrectread} the \code{lrectread} parameters, i.e.\ the boundary is included in the
parameters, i.e. the boundary is included in the new image. new image. The new boundaries need not be inside the picture. Pixels
The new boundaries need not be inside the picture. Pixels that fall that fall outside the old image will have their value set to zero. If
outside the old image will have their value set to zero. \var{x0} is bigger than \var{x1} the new image is mirrored. The same
If \var{x0} is bigger than \var{x1} the new image is mirrored. The holds for the y coordinates.
same holds for the y coordinates.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{scale}{image\, psize\, width\, height\, newwidth\, newheight} \begin{funcdesc}{scale}{image\, psize\, width\, height\, newwidth\, newheight}
This function returns an \var{image} scaled to size \var{newwidth} by Return \var{image} scaled to size \var{newwidth} by \var{newheight}.
\var{newheight}. No interpolation is done, scaling is done by No interpolation is done, scaling is done by simple-minded pixel
simple-minded pixel duplication or removal. Therefore, computer-generated duplication or removal. Therefore, computer-generated images or
images or dithered images will not look nice after scaling. dithered images will not look nice after scaling.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{tovideo}{image\, psize\, width\, height} \begin{funcdesc}{tovideo}{image\, psize\, width\, height}
This function runs a vertical low-pass filter over an image. It does Run a vertical low-pass filter over an image. It does so by computing
so by computing each destination pixel as the average of two each destination pixel as the average of two vertically-aligned source
vertically-aligned source pixels. The main use of this routine is to pixels. The main use of this routine is to forestall excessive
forestall excessive flicker if the image is displayed on a video flicker if the image is displayed on a video device that uses
device that uses interlacing, hence the name. interlacing, hence the name.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{grey2mono}{image\, width\, height\, threshold} \begin{funcdesc}{grey2mono}{image\, width\, height\, threshold}
This function converts a 8-bit deep greyscale image to a 1-bit deep Convert a 8-bit deep greyscale image to a 1-bit deep image by
image by tresholding all the pixels. The resulting image is tightly tresholding all the pixels. The resulting image is tightly packed and
packed and is probably only useful as an argument to \code{mono2grey}. is probably only useful as an argument to \code{mono2grey}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{dither2mono}{image\, width\, height} \begin{funcdesc}{dither2mono}{image\, width\, height}
This function also converts an 8-bit greyscale image to a 1-bit Convert an 8-bit greyscale image to a 1-bit monochrome image using a
monochrome image but it uses a (simple-minded) dithering algorithm. (simple-minded) dithering algorithm.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{mono2grey}{image\, width\, height\, p0\, p1} \begin{funcdesc}{mono2grey}{image\, width\, height\, p0\, p1}
This function converts a 1-bit monochrome image to an 8 bit greyscale Convert a 1-bit monochrome image to an 8 bit greyscale or color image.
or color image. All pixels that are zero-valued on input get value All pixels that are zero-valued on input get value \var{p0} on output
\var{p0} on output and all one-value input pixels get value \var{p1} and all one-value input pixels get value \var{p1} on output. To
on output. To convert a monochrome black-and-white image to greyscale convert a monochrome black-and-white image to greyscale pass the
pass the values \code{0} and \code{255} respectively. values \code{0} and \code{255} respectively.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{grey2grey4}{image\, width\, height} \begin{funcdesc}{grey2grey4}{image\, width\, height}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{imgfile}} \section{Built-in Module \sectcode{imgfile}}
\bimodindex{imgfile} \bimodindex{imgfile}
The imgfile module allows python programs to access SGI imglib image The imgfile module allows python programs to access SGI imglib image

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{imp}} \section{Built-in Module \sectcode{imp}}
\bimodindex{imp} \bimodindex{imp}
\index{import} \index{import}
@ -9,7 +9,7 @@ functions:
\renewcommand{\indexsubitem}{(in module struct)} \renewcommand{\indexsubitem}{(in module struct)}
\begin{funcdesc}{get_magic}{} \begin{funcdesc}{get_magic}{}
Return the magic string used to recognize value byte-compiled code Return the magic string value used to recognize byte-compiled code
files (``\code{.pyc} files''). files (``\code{.pyc} files'').
\end{funcdesc} \end{funcdesc}
@ -22,15 +22,15 @@ string to pass to the built-in \code{open} function to open the file
(this can be \code{'r'} for text files or \code{'rb'} for binary (this can be \code{'r'} for text files or \code{'rb'} for binary
files), and \var{type} is the file type, which has one of the values files), and \var{type} is the file type, which has one of the values
\code{PY_SOURCE}, \code{PY_COMPILED} or \code{C_EXTENSION}, defined \code{PY_SOURCE}, \code{PY_COMPILED} or \code{C_EXTENSION}, defined
below. below. (System-dependent values may also be returned.)
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{find_module}{name\, \optional{path}} \begin{funcdesc}{find_module}{name\, \optional{path}}
Try to find the module \var{name} on the search path \var{path}. The Try to find the module \var{name} on the search path \var{path}. The
default \var{path} is \code{sys.path}. The return value is a triple default \var{path} is \code{sys.path}. The return value is a triple
\code{(\var{file}, \var{pathname}, \var{description})} where \code{(\var{file}, \var{pathname}, \var{description})} where
\var{file} is an open file object positioned at the beginning \var{file} is an open file object positioned at the beginning,
corresponding to the file found, \var{pathname} is the pathname of the \var{pathname} is the pathname of the
file found, and \var{description} is a triple as contained in the list file found, and \var{description} is a triple as contained in the list
returned by \code{get_suffixes} describing the kind of file found. returned by \code{get_suffixes} describing the kind of file found.
\end{funcdesc} \end{funcdesc}
@ -134,33 +134,27 @@ The following function emulates the default import statement:
\begin{verbatim} \begin{verbatim}
import imp import imp
from sys import modules import sys
def __import__(name, globals=None, locals=None, fromlist=None): def __import__(name, globals=None, locals=None, fromlist=None):
# Fast path: let's see if it's already in sys.modules. # Fast path: see if the module has already been imported.
# Two speed optimizations are worth mentioning: if sys.modules.has_key(name):
# - We use 'modules' instead of 'sys.modules'; this saves a return sys.modules[name]
# dictionary look-up per call.
# - It's also faster to use a try-except statement than
# to use modules.has_key(name) to check if it's there.
try:
return modules[name]
except KeyError:
pass
# See if it's a built-in module # If any of the following calls raises an exception,
# there's a problem we con't handle -- let the caller handle it.
# See if it's a built-in module.
m = imp.init_builtin(name) m = imp.init_builtin(name)
if m: if m:
return m return m
# See if it's a frozen module # See if it's a frozen module.
m = imp.init_frozen(name) m = imp.init_frozen(name)
if m: if m:
return m return m
# Search the default path (i.e. sys.path). # Search the default path (i.e. sys.path).
# If this raises an exception, the module is not found --
# let the caller handle the exception.
fp, pathname, (suffix, mode, type) = imp.find_module(name) fp, pathname, (suffix, mode, type) = imp.find_module(name)
# See what we got. # See what we got.
@ -170,7 +164,7 @@ def __import__(name, globals=None, locals=None, fromlist=None):
if type == imp.PY_SOURCE: if type == imp.PY_SOURCE:
return imp.load_source(name, pathname, fp) return imp.load_source(name, pathname, fp)
if type == imp.PY_COMPILED: if type == imp.PY_COMPILED:
return imp.load_source(name, pathname, fp) return imp.load_compiled(name, pathname, fp)
# Shouldn't get here at all. # Shouldn't get here at all.
raise ImportError, '%s: unknown module type (%d)' % (name, type) raise ImportError, '%s: unknown module type (%d)' % (name, type)

View File

@ -4,9 +4,9 @@
This module contains functions that can read and write Python This module contains functions that can read and write Python
values in a binary format. The format is specific to Python, but values in a binary format. The format is specific to Python, but
independent of machine architecture issues (e.g., you can write a 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 Python value to a file on a PC, transport the file to a Sun, and read
it back there). Details of the format not explained here; read the it back there). Details of the format are undocumented on purpose;
source if you're interested.% it may change between Python versions (although it rarely does).%
\footnote{The name of this module stems from a bit of terminology used \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 by the designers of Modula-3 (amongst others), who use the term
``marshalling'' for shipping of data around in a self-contained form. ``marshalling'' for shipping of data around in a self-contained form.
@ -14,6 +14,14 @@ Strictly speaking, ``to marshal'' means to convert some data from
internal to external form (in an RPC buffer for instance) and internal to external form (in an RPC buffer for instance) and
``unmarshalling'' for the reverse process.} ``unmarshalling'' for the reverse process.}
This is not a general ``persistency'' module. For general persistency
and transfer of Python objects through RPC calls, see the modules
\code{pickle} and \code{shelve}. The \code{marshal} module exists
mainly to support reading and writing the ``pseudo-compiled'' code for
Python modules of \samp{.pyc} files.
\stmodindex{pickle}
\stmodindex{shelve}
\obindex{code}
Not all Python object types are supported; in general, only objects Not all Python object types are supported; in general, only objects
whose value is independent from a particular invocation of Python can whose value is independent from a particular invocation of Python can
@ -23,7 +31,22 @@ strings, tuples, lists, dictionaries, and code objects, where it
should be understood that tuples, lists and dictionaries are only should be understood that tuples, lists and dictionaries are only
supported as long as the values contained therein are themselves supported as long as the values contained therein are themselves
supported; and recursive lists and dictionaries should not be written supported; and recursive lists and dictionaries should not be written
(they will cause an infinite loop). (they will cause infinite loops).
{\bf Caveat:} On machines where C's \code{long int} type has more than
32 bits (such as the DEC Alpha or the HP Precision Architecture), it
is possible to create plain Python integers that are longer than 32
bits. Since the current \code{marshal} module uses 32 bits to
transfer plain Python integers, such values are silently truncated.
This particularly affects the use of very long integer literals in
Python modules --- these will be accepted by the parser on such
machines, but will be silently be truncated when the module is read
from the \code{.pyc} instead.%
\footnote{A solution would be to refuse such literals in the parser,
since they are inherently non-portable. Another solution would be to
let the \code{marshal} module raise an exception when an integer value
would be truncated. At least one of these solutions will be
implemented in a future version.}
There are functions that read/write files as well as functions There are functions that read/write files as well as functions
operating on strings. operating on strings.
@ -31,6 +54,7 @@ operating on strings.
The module defines these functions: The module defines these functions:
\renewcommand{\indexsubitem}{(in module marshal)} \renewcommand{\indexsubitem}{(in module marshal)}
\begin{funcdesc}{dump}{value\, file} \begin{funcdesc}{dump}{value\, file}
Write the value on the open file. The value must be a supported Write the value on the open file. The value must be a supported
type. The file must be an open file object such as type. The file must be an open file object such as

View File

@ -1,61 +1,64 @@
\section{Built-in module \sectcode{md5}} \section{Built-in Module \sectcode{md5}}
\bimodindex{md5} \bimodindex{md5}
This module implements the interface to RSA's MD5 message digest This module implements the interface to RSA's MD5 message digest
algorithm (see also the file \file{md5.doc}). Its use is quite algorithm (see also Internet RFC 1321). Its use is quite
straightforward:\ use the function \code{new} to create an straightforward:\ use the \code{md5.new()} to create an md5 object.
\dfn{md5}-object. You can now ``feed'' this object with arbitrary You can now feed this object with arbitrary strings using the
strings. \code{update()} method, and at any point you can ask it for the
\dfn{digest} (a strong kind of 128-bit checksum,
a.k.a. ``fingerprint'') of the contatenation of the strings fed to it
so far using the \code{digest()} method.
At any time you can ask for the ``final'' digest of the object. Internally, For example, to obtain the digest of the string {\tt"Nobody inspects
a temporary copy of the object is made and the digest is computed and the spammish repetition"}:
returned. Because of the copy, the digest operation is not destructive
for the object. Before a more exact description of the module's use, a small
example will be helpful:
to obtain the digest of the string \code{'abc'}, use \ldots
\bcode\begin{verbatim} \bcode\begin{verbatim}
>>> import md5 >>> import md5
>>> m = md5.new() >>> m = md5.new()
>>> m.update('abc') >>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest() >>> m.digest()
'\220\001P\230<\322O\260\326\226?}(\341\177r' '\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
\end{verbatim}\ecode \end{verbatim}\ecode
More condensed: More condensed:
\bcode\begin{verbatim} \bcode\begin{verbatim}
>>> md5.new('abc').digest() >>> md5.new("Nobody inspects the spammish repetition").digest()
'\220\001P\230<\322O\260\326\226?}(\341\177r' '\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
\end{verbatim}\ecode \end{verbatim}\ecode
\renewcommand{\indexsubitem}{(in module md5)} \renewcommand{\indexsubitem}{(in module md5)}
\begin{funcdesc}{new}{\optional{arg}} \begin{funcdesc}{new}{\optional{arg}}
Create a new md5-object. If \var{arg} is present, an initial Return a new md5 object. If \var{arg} is present, the method call
\code{update} method is called with \var{arg} as argument. \code{update(\var{arg})} is made.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{md5}{\optional{arg}} \begin{funcdesc}{md5}{\optional{arg}}
For backward compatibility reasons, this is an alternative name for the For backward compatibility reasons, this is an alternative name for the
\code{new} function. \code{new()} function.
\end{funcdesc} \end{funcdesc}
An md5-object has the following methods: An md5 object has the following methods:
\renewcommand{\indexsubitem}{(md5 method)} \renewcommand{\indexsubitem}{(md5 method)}
\begin{funcdesc}{update}{arg} \begin{funcdesc}{update}{arg}
Update this md5-object with the string \var{arg}. Update the md5 object with the string \var{arg}. Repeated calls are
equivalent to a single call with the concatenation of all the
arguments, i.e.\ \code{m.update(a); m.update(b)} is equivalent to
\code{m.update(a+b)}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{digest}{} \begin{funcdesc}{digest}{}
% XXX The following is not quite clear; what does MD5Final do? Return the digest of the strings passed to the \code{update()}
Return the \dfn{digest} of this md5-object. Internally, a copy is made method so far. This is an 8-byte string which may contain
and the \C-function \code{MD5Final} is called. Finally the digest is non-\ASCII{} characters, including null bytes.
returned.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{copy}{} \begin{funcdesc}{copy}{}
Return a separate copy of this md5-object. An \code{update} to this Return a copy (``clone'') of the md5 object. This can be used to
copy won't affect the original object. efficiently compute the digests of strings that share a common initial
substring.
\end{funcdesc} \end{funcdesc}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{mimetools}} \section{Standard Module \sectcode{mimetools}}
\stmodindex{mimetools} \stmodindex{mimetools}
\renewcommand{\indexsubitem}{(in module mimetools)} \renewcommand{\indexsubitem}{(in module mimetools)}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{mpz}} \section{Built-in Module \sectcode{mpz}}
\bimodindex{mpz} \bimodindex{mpz}
This module implements the interface to part of the GNU MP library. This module implements the interface to part of the GNU MP library.

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{nntplib}} \section{Standard Module \sectcode{nntplib}}
\stmodindex{nntplib} \stmodindex{nntplib}
\renewcommand{\indexsubitem}{(in module nntplib)} \renewcommand{\indexsubitem}{(in module nntplib)}

View File

@ -26,9 +26,11 @@ In addition to whatever the correct OS dependent module exports, the
following variables and functions are always exported by \code{os}: following variables and functions are always exported by \code{os}:
\renewcommand{\indexsubitem}{(in module os)} \renewcommand{\indexsubitem}{(in module os)}
\begin{datadesc}{name} \begin{datadesc}{name}
The name of the OS dependent module imported, e.g. \code{'posix'} or The name of the OS dependent module imported. The following names
\code{'mac'}. have currently been registered: \code{'posix'}, \code{'nt'},
\code{'dos'}, \code{'mac'}.
\end{datadesc} \end{datadesc}
\begin{datadesc}{path} \begin{datadesc}{path}
@ -49,29 +51,54 @@ e.g. \code{'..'} for POSIX or \code{'::'} for the Mac.
\end{datadesc} \end{datadesc}
\begin{datadesc}{sep} \begin{datadesc}{sep}
The character used by the OS to separate pathname components, e.g. The character used by the OS to separate pathname components, e.g.\
\code{'/'} for POSIX or \code{':'} for the Mac. Note that knowing this \code{'/'} for POSIX or \code{':'} for the Mac. Note that knowing this
is not sufficient to be able to parse or concatenate pathnames---better 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 use \code{os.path.split()} and \code{os.path.join()}---but it is
occasionally useful. occasionally useful.
\end{datadesc} \end{datadesc}
\begin{datadesc}{pathsep}
The character conventionally used by the OS to separate search patch
components (as in \code{\$PATH}), e.g.\ \code{':'} for POSIX or
\code{';'} for MS-DOS.
\end{datadesc}
\begin{datadesc}{defpath}
The default search path used by \code{os.exec*p*()} if the environment
doesn't have a \code{'PATH'} key.
\end{datadesc}
\begin{funcdesc}{execl}{path\, arg0\, arg1\, ...} \begin{funcdesc}{execl}{path\, arg0\, arg1\, ...}
This is equivalent to a call to \code{os.execv} with an \var{argv} This is equivalent to
of \code{[\var{arg0}, \var{arg1}, ...]}. \code{os.execv(\var{path}, (\var{arg0}, \var{arg1}, ...))}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{execle}{path\, arg0\, arg1\, ...\, env} \begin{funcdesc}{execle}{path\, arg0\, arg1\, ...\, env}
This is equivalent to a call to \code{os.execve} with an \var{argv} This is equivalent to
of \code{[\var{arg0}, \var{arg1}, ...]}. \code{os.execve(\var{path}, (\var{arg0}, \var{arg1}, ...), \var{env})}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{execlp}{path\, arg0\, arg1\, ...} \begin{funcdesc}{execlp}{path\, arg0\, arg1\, ...}
This is like \code{execl} but duplicates the shell's actions in This is equivalent to
searching for an executable file in a list of directories. The \code{os.execvp(\var{path}, (\var{arg0}, \var{arg1}, ...))}.
directory list is obtained from \code{environ['PATH']}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{execvp}{path\, arg0\, arg1\, ...} \begin{funcdesc}{execvp}{path\, args}
\code{execvp} is for \code{execv} what \code{execlp} is for \code{execl}. This is like \code{os.execv(\var{path}, \var{args})} but duplicates
the shell's actions in searching for an executable file in a list of
directories. The directory list is obtained from
\code{os.environ['PATH']}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{execvpe}{path\, args\, env}
This is a cross between \code{os.execve()} and \code{os.execvp()}.
The directory list is obtained from \code{\var{env}['PATH']}.
\end{funcdesc}
(The functions \code{os.execv()} and \code{execve()} are not
documented here, since they are implemented by the OS dependent
module. If the OS dependent module doesn't define either of these,
the functions that rely on it will raise an exception. They are
documented in the section on module \code{posix}, together with all
other functions that \code{os} imports from the OS dependent module.)

View File

@ -91,7 +91,7 @@ Enter post-mortem debugging of the traceback found in
\code{sys.last_traceback}. \code{sys.last_traceback}.
\end{funcdesc} \end{funcdesc}
\subsection{Debugger Commands} \section{Debugger Commands}
The debugger recognizes the following commands. Most commands can be The debugger recognizes the following commands. Most commands can be
abbreviated to one or two letters; e.g. ``\code{h(elp)}'' means that abbreviated to one or two letters; e.g. ``\code{h(elp)}'' means that
@ -117,7 +117,7 @@ but the debugger's state is not changed.
\begin{description} \begin{description}
\item[{h(elp) [\var{command}]}] \item[h(elp) [\var{command}]]
Without argument, print the list of available commands. Without argument, print the list of available commands.
With a \var{command} as argument, print help about that command. With a \var{command} as argument, print help about that command.
@ -127,40 +127,40 @@ through that command instead. Since the \var{command} argument must be
an identifier, ``\code{help exec}'' must be entered to get help on the an identifier, ``\code{help exec}'' must be entered to get help on the
``\code{!}'' command. ``\code{!}'' command.
\item[{w(here)}] \item[w(here)]
Print a stack trace, with the most recent frame at the bottom. Print a stack trace, with the most recent frame at the bottom.
An arrow indicates the current frame, which determines the An arrow indicates the current frame, which determines the
context of most commands. context of most commands.
\item[{d(own)}] \item[d(own)]
Move the current frame one level down in the stack trace Move the current frame one level down in the stack trace
(to an older frame). (to an older frame).
\item[{u(p)}] \item[u(p)]
Move the current frame one level up in the stack trace Move the current frame one level up in the stack trace
(to a newer frame). (to a newer frame).
\item[{b(reak) [\var{lineno}\code{|}\var{function}]}] \item[b(reak) [\var{lineno}\code{|}\var{function}]]
With a \var{lineno} argument, set a break there in the current With a \var{lineno} argument, set a break there in the current
file. With a \var{function} argument, set a break at the entry of file. With a \var{function} argument, set a break at the entry of
that function. Without argument, list all breaks. that function. Without argument, list all breaks.
\item[{cl(ear) [\var{lineno}]}] \item[cl(ear) [\var{lineno}]]
With a \var{lineno} argument, clear that break in the current file. With a \var{lineno} argument, clear that break in the current file.
Without argument, clear all breaks (but first ask confirmation). Without argument, clear all breaks (but first ask confirmation).
\item[{s(tep)}] \item[s(tep)]
Execute the current line, stop at the first possible occasion Execute the current line, stop at the first possible occasion
(either in a function that is called or on the next line in the (either in a function that is called or on the next line in the
current function). current function).
\item[{n(ext)}] \item[n(ext)]
Continue execution until the next line in the current function Continue execution until the next line in the current function
is reached or it returns. (The difference between \code{next} and is reached or it returns. (The difference between \code{next} and
@ -168,15 +168,15 @@ is reached or it returns. (The difference between \code{next} and
\code{next} executes called functions at (nearly) full speed, only \code{next} executes called functions at (nearly) full speed, only
stopping at the next line in the current function.) stopping at the next line in the current function.)
\item[{r(eturn)}] \item[r(eturn)]
Continue execution until the current function returns. Continue execution until the current function returns.
\item[{c(ont(inue))}] \item[c(ont(inue))]
Continue execution, only stop when a breakpoint is encountered. Continue execution, only stop when a breakpoint is encountered.
\item[{l(ist) [\var{first} [, \var{last}]]}] \item[l(ist) [\var{first} [, \var{last}]]]
List source code for the current file. Without arguments, list 11 List source code for the current file. Without arguments, list 11
lines around the current line or continue the previous listing. With lines around the current line or continue the previous listing. With
@ -184,17 +184,17 @@ one argument, list 11 lines around at that line. With two arguments,
list the given range; if the second argument is less than the first, list the given range; if the second argument is less than the first,
it is interpreted as a count. it is interpreted as a count.
\item[{a(rgs)}] \item[a(rgs)]
Print the argument list of the current function. Print the argument list of the current function.
\item[{p \var{expression}}] \item[p \var{expression}]
Evaluate the \var{expression} in the current context and print its Evaluate the \var{expression} in the current context and print its
value. (Note: \code{print} can also be used, but is not a debugger value. (Note: \code{print} can also be used, but is not a debugger
command --- this executes the Python \code{print} statement.) command --- this executes the Python \code{print} statement.)
\item[{[!] \var{statement}}] \item[[!] \var{statement}]
Execute the (one-line) \var{statement} in the context of Execute the (one-line) \var{statement} in the context of
the current stack frame. the current stack frame.
@ -207,9 +207,83 @@ command with a ``\code{global}'' command on the same line, e.g.:
(Pdb) (Pdb)
\end{verbatim} \end{verbatim}
\item[{q(uit)}] \item[q(uit)]
Quit from the debugger. Quit from the debugger.
The program being executed is aborted. The program being executed is aborted.
\end{description} \end{description}
\section{How It Works}
Some changes were made to the interpreter:
\begin{itemize}
\item sys.settrace(func) sets the global trace function
\item there can also a local trace function (see later)
\end{itemize}
Trace functions have three arguments: (\var{frame}, \var{event}, \var{arg})
\begin{description}
\item[\var{frame}] is the current stack frame
\item[\var{event}] is a string: \code{'call'}, \code{'line'}, \code{'return'}
or \code{'exception'}
\item[\var{arg}] is dependent on the event type
\end{description}
A trace function should return a new trace function or None.
Class methods are accepted (and most useful!) as trace methods.
The events have the following meaning:
\begin{description}
\item[\code{'call'}]
A function is called (or some other code block entered). The global
trace function is called; arg is the argument list to the function;
the return value specifies the local trace function.
\item[\code{'line'}]
The interpreter is about to execute a new line of code (sometimes
multiple line events on one line exist). The local trace function is
called; arg in None; the return value specifies the new local trace
function.
\item[\code{'return'}]
A function (or other code block) is about to return. The local trace
function is called; arg is the value that will be returned. The trace
function's return value is ignored.
\item[\code{'exception'}]
An exception has occurred. The local trace function is called; arg is
a triple (exception, value, traceback); the return value specifies the
new local trace function
\end{description}
Note that as an exception is propagated down the chain of callers, an
\code{'exception'} event is generated at each level.
Stack frame objects have the following read-only attributes:
\begin{description}
\item[f_code] the code object being executed
\item[f_lineno] the current line number (\code{-1} for \code{'call'} events)
\item[f_back] the stack frame of the caller, or None
\item[f_locals] dictionary containing local name bindings
\item[f_globals] dictionary containing global name bindings
\end{description}
Code objects have the following read-only attributes:
\begin{description}
\item[co_code] the code string
\item[co_names] the list of names used by the code
\item[co_consts] the list of (literal) constants used by the code
\item[co_filename] the filename from which the code was compiled
\end{description}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{pickle}} \section{Standard Module \sectcode{pickle}}
\stmodindex{pickle} \stmodindex{pickle}
\index{persistency} \index{persistency}
\indexii{persistent}{objects} \indexii{persistent}{objects}
@ -7,6 +7,8 @@
\indexii{flattening}{objects} \indexii{flattening}{objects}
\indexii{pickling}{objects} \indexii{pickling}{objects}
\renewcommand{\indexsubitem}{(in module pickle)}
The \code{pickle} module implements a basic but powerful algorithm for The \code{pickle} module implements a basic but powerful algorithm for
``pickling'' (a.k.a.\ serializing, marshalling or flattening) nearly ``pickling'' (a.k.a.\ serializing, marshalling or flattening) nearly
arbitrary Python objects. This is a more primitive notion than arbitrary Python objects. This is a more primitive notion than
@ -28,11 +30,11 @@ following correctly:
\begin{itemize} \begin{itemize}
\item recursive objects \item recursive objects (objects containing references to themselves)
\item pointer sharing \item object sharing (references to the same object in different places)
\item instances of user-defined classes \item user-defined classes and their instances
\end{itemize} \end{itemize}
@ -42,13 +44,13 @@ standards such as CORBA (which probably can't represent pointer
sharing or recursive objects); however it means that non-Python sharing or recursive objects); however it means that non-Python
programs may not be able to reconstruct pickled Python objects. programs may not be able to reconstruct pickled Python objects.
The \code{pickle} data format uses a printable ASCII representation. The \code{pickle} data format uses a printable \ASCII{} representation.
This is slightly more voluminous than a binary representation. This is slightly more voluminous than a binary representation.
However, small integers actually take {\em less} space when However, small integers actually take {\em less} space when
represented as minimal-size decimal strings than when represented as represented as minimal-size decimal strings than when represented as
32-bit binary numbers, and strings are only much longer if they 32-bit binary numbers, and strings are only much longer if they
contain many control characters or 8-bit characters. The big contain many control characters or 8-bit characters. The big
advantage of using printable ASCII (and of some other characteristics advantage of using printable \ASCII{} (and of some other characteristics
of \code{pickle}'s representation) is that for debugging or recovery of \code{pickle}'s representation) is that for debugging or recovery
purposes it is possible for a human to read the pickled file with a purposes it is possible for a human to read the pickled file with a
standard text editor. (I could have gone a step further and used a standard text editor. (I could have gone a step further and used a
@ -67,7 +69,7 @@ Trojan horses into a program.
For the benefit of persistency modules written using \code{pickle}, it For the benefit of persistency modules written using \code{pickle}, it
supports the notion of a reference to an object outside the pickled supports the notion of a reference to an object outside the pickled
data stream. Such objects are referenced by a name, which is an data stream. Such objects are referenced by a name, which is an
arbitrary string of printable ASCII characters. The resolution of arbitrary string of printable \ASCII{} characters. The resolution of
such names is not defined by the \code{pickle} module --- the such names is not defined by the \code{pickle} module --- the
persistent object module will have to implement a method persistent object module will have to implement a method
\code{persistent_load}. To write references to persistent objects, \code{persistent_load}. To write references to persistent objects,
@ -78,6 +80,8 @@ There are some restrictions on the pickling of class instances.
First of all, the class must be defined at the top level in a module. First of all, the class must be defined at the top level in a module.
\renewcommand{\indexsubitem}{(pickle protocol)}
Next, it must normally be possible to create class instances by Next, it must normally be possible to create class instances by
calling the class without arguments. If this is undesirable, the calling the class without arguments. If this is undesirable, the
class can define a method \code{__getinitargs__()}, which should class can define a method \code{__getinitargs__()}, which should
@ -86,7 +90,7 @@ class constructor (\code{__init__()}).
\ttindex{__getinitargs__} \ttindex{__getinitargs__}
\ttindex{__init__} \ttindex{__init__}
Classes can further influence how they are pickled --- if the class Classes can further influence how their instances are pickled --- if the class
defines the method \code{__getstate__()}, it is called and the return defines the method \code{__getstate__()}, it is called and the return
state is pickled as the contents for the instance, and if the class state is pickled as the contents for the instance, and if the class
defines the method \code{__setstate__()}, it is called with the defines the method \code{__setstate__()}, it is called with the
@ -113,6 +117,13 @@ will see many versions of a class, it may be worthwhile to put a version
number in the objects so that suitable conversions can be made by the number in the objects so that suitable conversions can be made by the
class's \code{__setstate__()} method. class's \code{__setstate__()} method.
When a class itself is pickled, only its name is pickled --- the class
definition is not pickled, but re-imported by the unpickling process.
Therefore, the restriction that the class must be defined at the top
level in a module applies to pickled classes as well.
\renewcommand{\indexsubitem}{(in module pickle)}
The interface can be summarized as follows. The interface can be summarized as follows.
To pickle an object \code{x} onto a file \code{f}, open for writing: To pickle an object \code{x} onto a file \code{f}, open for writing:
@ -122,6 +133,12 @@ p = pickle.Pickler(f)
p.dump(x) p.dump(x)
\end{verbatim} \end{verbatim}
A shorthand for this is:
\begin{verbatim}
pickle.dump(x, f)
\end{verbatim}
To unpickle an object \code{x} from a file \code{f}, open for reading: To unpickle an object \code{x} from a file \code{f}, open for reading:
\begin{verbatim} \begin{verbatim}
@ -129,11 +146,19 @@ u = pickle.Unpickler(f)
x = u.load(x) x = u.load(x)
\end{verbatim} \end{verbatim}
A shorthand is:
\begin{verbatim}
x = pickle.load(f)
\end{verbatim}
The \code{Pickler} class only calls the method \code{f.write} with a The \code{Pickler} class only calls the method \code{f.write} with a
string argument. The \code{Unpickler} calls the methods \code{f.read} string argument. The \code{Unpickler} calls the methods \code{f.read}
(with an integer argument) and \code{f.readline} (without argument), (with an integer argument) and \code{f.readline} (without argument),
both returning a string. It is explicitly allowed to pass non-file both returning a string. It is explicitly allowed to pass non-file
objects here, as long as they have the right methods. objects here, as long as they have the right methods.
\ttindex{Unpickler}
\ttindex{Pickler}
The following types can be pickled: The following types can be pickled:
\begin{itemize} \begin{itemize}
@ -146,25 +171,56 @@ The following types can be pickled:
\item tuples, lists and dictionaries containing only picklable objects \item tuples, lists and dictionaries containing only picklable objects
\item class instances whose \code{__dict__} or \code{__setstate__()} \item classes that are defined at the top level in a module
is picklable
\item instances of such classes whose \code{__dict__} or
\code{__setstate__()} is picklable
\end{itemize} \end{itemize}
Attempts to pickle unpicklable objects will raise an exception; when Attempts to pickle unpicklable objects will raise the
this happens, an unspecified number of bytes may have been written to \code{PicklingError} exception; when this happens, an unspecified
the file argument. number of bytes may have been written to the file.
It is possible to make multiple calls to \code{Pickler.dump()} or to It is possible to make multiple calls to the \code{dump()} method of
\code{Unpickler.load()}, as long as there is a one-to-one the same \code{Pickler} instance. These must then be matched to the
correspondence between \code{Pickler} and \code{Unpickler} objects and same number of calls to the \code{load()} instance of the
between \code{dump} and \code{load} calls for any pair of corresponding \code{Unpickler} instance. If the same object is
corresponding \code{Pickler} and \code{Unpicklers}. {\em Warning}: pickled by multiple \code{dump()} calls, the \code{load()} will all
this is intended for pickling multiple objects without intervening yield references to the same object. {\em Warning}: this is intended
modifications to the objects or their parts. If you modify an object for pickling multiple objects without intervening modifications to the
and then pickle it again using the same \code{Pickler} instance, the objects or their parts. If you modify an object and then pickle it
object is not pickled again --- a reference to it is pickled and the again using the same \code{Pickler} instance, the object is not
\code{Unpickler} will return the old value, not the modified one. (There pickled again --- a reference to it is pickled and the
are two problems here: (a) detecting changes, and (b) marshalling a \code{Unpickler} will return the old value, not the modified one.
minimal set of changes. I have no answers. Garbage Collection may (There are two problems here: (a) detecting changes, and (b)
also become a problem here.) marshalling a minimal set of changes. I have no answers. Garbage
Collection may also become a problem here.)
Apart from the \code{Pickler} and \code{Unpickler} classes, the
module defines the following functions, and an exception:
\begin{funcdesc}{dump}{object\, file}
Write a pickled representation of \var{obect} to the open file object
\var{file}. This is equivalent to \code{Pickler(file).dump(object)}.
\end{funcdesc}
\begin{funcdesc}{load}{file}
Read a pickled object from the open file object \var{file}. This is
equivalent to \code{Unpickler(file).load()}.
\end{funcdesc}
\begin{funcdesc}{dumps}{object}
Return the pickled representation of the object as a string, instead
of writing it to a file.
\end{funcdesc}
\begin{funcdesc}{loads}{string}
Read a pickled object from a string instead of a file. Characters in
the string past the pickled object's representation are ignored.
\end{funcdesc}
\begin{excdesc}{PicklingError}
This exception is raised when an unpicklable object is passed to
\code{Pickler.dump()}.
\end{excdesc}

View File

@ -1,12 +1,20 @@
\section{Built-in Module \sectcode{posix}} \section{Built-in Module \sectcode{posix}}
\bimodindex{posix} \bimodindex{posix}
This module provides access to operating system functionality that is This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly disguised standardized by the C Standard and the POSIX standard (a thinly disguised
\UNIX{} interface). \UNIX{} interface).
It is available in all Python versions except on the Macintosh;
the MS-DOS version does not support certain functions. \strong{Do not import this module directly.} Instead, import the
module \code{os}, which provides a \emph{portable} version of this
interface. On \UNIX{}, the \code{os} module provides a superset of
the \code{posix} interface. On non-\UNIX{} operating systems the
\code{posix} module is not available, but a subset is always available
through the \code{os} interface. Once \code{os} is imported, there is
\emph{no} performance penalty in using it instead of
\code{posix}.
\stmodindex{os}
The descriptions below are very terse; refer to the The descriptions below are very terse; refer to the
corresponding \UNIX{} manual entry for more information. corresponding \UNIX{} manual entry for more information.
@ -20,13 +28,18 @@ Module \code{posix} defines the following data items:
\begin{datadesc}{environ} \begin{datadesc}{environ}
A dictionary representing the string environment at the time A dictionary representing the string environment at the time
the interpreter was started. the interpreter was started.
(Modifying this dictionary does not affect the string environment of the
interpreter.)
For example, For example,
\code{posix.environ['HOME']} \code{posix.environ['HOME']}
is the pathname of your home directory, equivalent to is the pathname of your home directory, equivalent to
\code{getenv("HOME")} \code{getenv("HOME")}
in C. in C.
Modifying this dictionary does not affect the string environment
passed on by \code{execv()}, \code{popen()} or \code{system()}; if you
need to change the environment, pass \code{environ} to \code{execve()}
or add variable assignments and export statements to the command
string for \code{system()} or \code{popen()}.%
\footnote{The problem with automatically passing on \code{environ} is
that there is no portable way of changing the environment.}
\end{datadesc} \end{datadesc}
\renewcommand{\indexsubitem}{(exception in module posix)} \renewcommand{\indexsubitem}{(exception in module posix)}

View File

@ -7,12 +7,13 @@ This module implements some additional functionality over the built-in
file objects. In particular, it implements file locking, control over file objects. In particular, it implements file locking, control over
the file flags, and an easy interface to duplicate the file object. the file flags, and an easy interface to duplicate the file object.
The module defines a new file object, the posixfile object. It The module defines a new file object, the posixfile object. It
inherits all the standard file object methods and adds the methods has all the standard file object methods and adds the methods
described below. described below. This module only works for certain flavors of
\UNIX{}, since it uses \code{fcntl()} for file locking.
To instantiate a posixfile object, use the \code{open()} function in To instantiate a posixfile object, use the \code{open()} function in
the posixfile module. The resulting object looks and feels the same as the posixfile module. The resulting object looks and feels roughly
a standard file object. the same as a standard file object.
The posixfile module defines the following constants: The posixfile module defines the following constants:
@ -32,10 +33,11 @@ offset is calculated from the end of the file
The posixfile module defines the following functions: The posixfile module defines the following functions:
\renewcommand{\indexsubitem}{(in module posixfile)} \renewcommand{\indexsubitem}{(in module posixfile)}
\begin{funcdesc}{open}{filename\, mode}
\begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}}
Create a new posixfile object with the given filename and mode. The Create a new posixfile object with the given filename and mode. The
filename and mode are interpreted the same way as the \code{open()} \var{filename}, \var{mode} and \var{bufsize} arguments are
builtin function. interpreted the same way as by the \code{open()} builtin function.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{fileopen}{fileobject} \begin{funcdesc}{fileopen}{fileobject}
@ -102,8 +104,8 @@ In addition the following modifiers can be added to the format:
\begin{tableiii}{|c|l|c|}{samp}{Modifier}{Meaning}{Notes} \begin{tableiii}{|c|l|c|}{samp}{Modifier}{Meaning}{Notes}
\lineiii{|}{wait until the lock has been granted}{} \lineiii{|}{wait until the lock has been granted}{}
\lineiii{?}{return the first lock conflicting with the requested lock,}{(1)} \lineiii{?}{return the first lock conflicting with the requested lock, or
{}&{\hskip0.5cm or \code{None} if there is no conflict.}&{}\\ \code{None} if there is no conflict.}{(1)}
\end{tableiii} \end{tableiii}
Note: Note:

View File

@ -1,9 +1,14 @@
\section{Standard Module \sectcode{posixpath}} \section{Standard Module \sectcode{posixpath}}
\stmodindex{posixpath} \stmodindex{posixpath}
This module implements some useful functions on POSIX pathnames. This module implements some useful functions on POSIX pathnames.
\strong{Do not import this module directly.} Instead, import the
module \code{os} and use \code{os.path}.
\stmodindex{os}
\renewcommand{\indexsubitem}{(in module posixpath)} \renewcommand{\indexsubitem}{(in module posixpath)}
\begin{funcdesc}{basename}{p} \begin{funcdesc}{basename}{p}
Return the base name of pathname Return the base name of pathname
\var{p}. \var{p}.
@ -66,10 +71,12 @@ Always false if symbolic links are not supported.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{ismount}{p} \begin{funcdesc}{ismount}{p}
Return true if \var{p} is a mount point. (This currently checks whether Return true if pathname \var{p} is a \dfn{mount point}: a point in a
\code{\var{p}/..} is on a different device from \var{p} or whether file system where a different file system has been mounted. The
\code{\var{p}/..} and \var{p} point to the same i-node on the same function checks whether \var{p}'s parent, \file{\var{p}/..}, is on a
device --- is this test correct for all \UNIX{} and POSIX variants?) different device than \var{p}, or whether \file{\var{p}/..} and
\var{p} point to the same i-node on the same device --- this should
detect mount points for all \UNIX{} and POSIX variants.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{join}{p\, q} \begin{funcdesc}{join}{p\, q}
@ -128,9 +135,10 @@ Calls the function \var{visit} with arguments
directory tree rooted at \var{p} (including \var{p} itself, if it is a directory tree rooted at \var{p} (including \var{p} itself, if it is a
directory). The argument \var{dirname} specifies the visited directory, directory). The argument \var{dirname} specifies the visited directory,
the argument \var{names} lists the files in the directory (gotten from the argument \var{names} lists the files in the directory (gotten from
\code{posix.listdir(\var{dirname})}). The \var{visit} function may \code{posix.listdir(\var{dirname})}, so including \samp{.} and
modify \var{names} to influence the set of directories visited below \samp{..}). The \var{visit} function may modify \var{names} to
\var{dirname}, e.g., to avoid visiting certain parts of the tree. (The influence the set of directories visited below \var{dirname}, e.g., to
object referred to by \var{names} must be modified in place, using avoid visiting certain parts of the tree. (The object referred to by
\code{del} or slice assignment.) \var{names} must be modified in place, using \code{del} or slice
assignment.)
\end{funcdesc} \end{funcdesc}

View File

@ -2,7 +2,7 @@
\stmodindex{profile} \stmodindex{profile}
\stmodindex{pstats} \stmodindex{pstats}
Copyright 1994, by InfoSeek Corporation, all rights reserved. Copyright \copyright\ 1994, by InfoSeek Corporation, all rights reserved.
Written by James Roskind% Written by James Roskind%
\footnote{ \footnote{
@ -42,7 +42,7 @@ ways at times. Please send suggestions for improvements to:
I'd appreciate the feedback. I'd appreciate the feedback.
\section{Introduction} \section{Introduction to the profiler}
A \dfn{profiler} is a program that describes the run time performance A \dfn{profiler} is a program that describes the run time performance
of a program, providing a variety of statistics. This documentation of a program, providing a variety of statistics. This documentation
@ -242,7 +242,7 @@ of algorithms to be directly compared to iterative implementations.
\section{Reference Manual} \section{Reference Manual}
\renewcommand{\indexsubitem}{} \renewcommand{\indexsubitem}{(profiler function)}
The primary entry point for the profiler is the global function The primary entry point for the profiler is the global function
\code{profile.run()}. It is typically used to create any profile \code{profile.run()}. It is typically used to create any profile
@ -254,7 +254,7 @@ Profiler Extensions, which includes discussion of how to derive
``better'' profilers from the classes presented, or reading the source ``better'' profilers from the classes presented, or reading the source
code for these modules. code for these modules.
\begin{funcdesc}{profile.run}{string\optional{\, filename}} \begin{funcdesc}{profile.run}{string\optional{\, filename\optional{\, ...}}}
This function takes a single argument that has can be passed to the This function takes a single argument that has can be passed to the
\code{exec} statement, and an optional file name. In all cases this \code{exec} statement, and an optional file name. In all cases this
@ -336,12 +336,12 @@ need to be combined with data in an existing \code{Stats} object, the
\end{funcdesc} \end{funcdesc}
\subsection{Methods Of The \sectcode{Stats} Class} \subsection{The \sectcode{Stats} Class}
\renewcommand{\indexsubitem}{(Stats method)} \renewcommand{\indexsubitem}{(Stats method)}
\begin{funcdesc}{strip_dirs}{} \begin{funcdesc}{strip_dirs}{}
This method for the code{Stats} class removes all leading path information This method for the \code{Stats} class removes all leading path information
from file names. It is very useful in reducing the size of the from file names. It is very useful in reducing the size of the
printout to fit within (close to) 80 columns. This method modifies printout to fit within (close to) 80 columns. This method modifies
the object, and the stripped information is lost. After performing a the object, and the stripped information is lost. After performing a
@ -355,7 +355,7 @@ these two entries are accumulated into a single entry.
\begin{funcdesc}{add}{filename\optional{\, ...}} \begin{funcdesc}{add}{filename\optional{\, ...}}
This method of the code{Stats} class accumulates additional profiling This method of the \code{Stats} class accumulates additional profiling
information into the current profiling object. Its arguments should information into the current profiling object. Its arguments should
refer to filenames created by the corresponding version of refer to filenames created by the corresponding version of
\code{profile.run()}. Statistics for identically named (re: file, \code{profile.run()}. Statistics for identically named (re: file,
@ -364,7 +364,7 @@ function statistics.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{sort_stats}{key\optional{\, ...}} \begin{funcdesc}{sort_stats}{key\optional{\, ...}}
This method modifies the code{Stats} object by sorting it according to the This method modifies the \code{Stats} object by sorting it according to the
supplied criteria. The argument is typically a string identifying the supplied criteria. The argument is typically a string identifying the
basis of a sort (example: \code{"time"} or \code{"name"}). basis of a sort (example: \code{"time"} or \code{"name"}).
@ -412,7 +412,7 @@ additional arguments will be silently ignored.
\begin{funcdesc}{reverse_order}{} \begin{funcdesc}{reverse_order}{}
This method for the code{Stats} class reverses the ordering of the basic This method for the \code{Stats} class reverses the ordering of the basic
list within the object. This method is provided primarily for list within the object. This method is provided primarily for
compatibility with the old profiler. Its utility is questionable compatibility with the old profiler. Its utility is questionable
now that ascending vs descending order is properly selected based on now that ascending vs descending order is properly selected based on
@ -420,7 +420,7 @@ the sort key of choice.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{print_stats}{restriction\optional{\, ...}} \begin{funcdesc}{print_stats}{restriction\optional{\, ...}}
This method for the code{Stats} class prints out a report as described This method for the \code{Stats} class prints out a report as described
in the \code{profile.run()} definition. in the \code{profile.run()} definition.
The order of the printing is based on the last \code{sort_stats()} The order of the printing is based on the last \code{sort_stats()}
@ -454,7 +454,7 @@ and then proceed to only print the first 10\% of them.
\begin{funcdesc}{print_callers}{restrictions\optional{\, ...}} \begin{funcdesc}{print_callers}{restrictions\optional{\, ...}}
This method for the code{Stats} class prints a list of all functions This method for the \code{Stats} class prints a list of all functions
that called each function in the profiled database. The ordering is that called each function in the profiled database. The ordering is
identical to that provided by \code{print_stats()}, and the definition identical to that provided by \code{print_stats()}, and the definition
of the restricting argument is also identical. For convenience, a of the restricting argument is also identical. For convenience, a
@ -464,14 +464,14 @@ is the cumulative time spent in the function at the right.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{print_callees}{restrictions\optional{\, ...}} \begin{funcdesc}{print_callees}{restrictions\optional{\, ...}}
This method for the code{Stats} class prints a list of all function This method for the \code{Stats} class prints a list of all function
that were called by the indicated function. Aside from this reversal that were called by the indicated function. Aside from this reversal
of direction of calls (re: called vs was called by), the arguments and of direction of calls (re: called vs was called by), the arguments and
ordering are identical to the \code{print_callers()} method. ordering are identical to the \code{print_callers()} method.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{ignore}{} \begin{funcdesc}{ignore}{}
This method of the code{Stats} class is used to dispose of the value This method of the \code{Stats} class is used to dispose of the value
returned by earlier methods. All standard methods in this class returned by earlier methods. All standard methods in this class
return the instance that is being processed, so that the commands can return the instance that is being processed, so that the commands can
be strung together. For example: be strung together. For example:
@ -481,7 +481,7 @@ pstats.Stats('foofile').strip_dirs().sort_stats('cum').print_stats().ignore()
\end{verbatim} \end{verbatim}
would perform all the indicated functions, but it would not return would perform all the indicated functions, but it would not return
the final reference to the code{Stats} instance.% the final reference to the \code{Stats} instance.%
\footnote{ \footnote{
This was once necessary, when Python would print any unused expression This was once necessary, when Python would print any unused expression
result that was not \code{None}. The method is still defined for result that was not \code{None}. The method is still defined for
@ -604,7 +604,7 @@ performance section, and there is no reason to use a variable lookup
at this point, when a constant can be used. at this point, when a constant can be used.
\section{Extensions: Deriving Better Profilers} \section{Extensions - Deriving Better Profilers}
The \code{Profile} class of module \code{profile} was written so that The \code{Profile} class of module \code{profile} was written so that
derived classes could be developed to extend the profiler. Rather derived classes could be developed to extend the profiler. Rather

View File

@ -44,12 +44,13 @@ The module defines these functions, and an exception:
\begin{funcdesc}{compile}{pattern\optional{\, translate}} \begin{funcdesc}{compile}{pattern\optional{\, translate}}
Compile a regular expression pattern into a regular expression Compile a regular expression pattern into a regular expression
object, which can be used for matching using its \code{match} and object, which can be used for matching using its \code{match} and
\code{search} methods, described below. The optional \code{search} methods, described below. The optional argument
\var{translate}, if present, must be a 256-character string \var{translate}, if present, must be a 256-character string
indicating how characters (both of the pattern and of the strings to indicating how characters (both of the pattern and of the strings to
be matched) are translated before comparing them; the \code{i}-th be matched) are translated before comparing them; the \code{i}-th
element of the string gives the translation for the character with element of the string gives the translation for the character with
ASCII code \code{i}. \ASCII{} code \code{i}. This can be used to implement
case-insensitive matching; see the \code{casefold} data item below.
The sequence The sequence

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{rfc822}} \section{Standard Module \sectcode{rfc822}}
\stmodindex{rfc822} \stmodindex{rfc822}
\renewcommand{\indexsubitem}{(in module rfc822)} \renewcommand{\indexsubitem}{(in module rfc822)}
@ -60,12 +60,12 @@ returned by \code{getheader(\var{name})}. If no header matching
\var{name} exists, return \code{None, None}; otherwise both the full \var{name} exists, return \code{None, None}; otherwise both the full
name and the address are (possibly empty )strings. name and the address are (possibly empty )strings.
Example: If \code{m}'s first \code{From} header contains the string Example: If \code{m}'s first \code{From} header contains the string\\
\code{'guido@cwi.nl (Guido van Rossum)'}, then \code{'jack@cwi.nl (Jack Jansen)'}, then
\code{m.getaddr('From')} will yield the pair \code{m.getaddr('From')} will yield the pair
\code{('Guido van Rossum', 'guido@cwi.nl')}. \code{('Jack Jansen', 'jack@cwi.nl')}.
If the header contained If the header contained
\code{'Guido van Rossum <guido@cwi.nl>'} instead, it would yield the \code{'Jack Jansen <jack@cwi.nl>'} instead, it would yield the
exact same result. exact same result.
\end{funcdesc} \end{funcdesc}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{rgbimg}} \section{Built-in Module \sectcode{rgbimg}}
\bimodindex{rgbimg} \bimodindex{rgbimg}
The rgbimg module allows python programs to access SGI imglib image The rgbimg module allows python programs to access SGI imglib image

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{rotor}} \section{Built-in Module \sectcode{rotor}}
\bimodindex{rotor} \bimodindex{rotor}
This module implements a rotor-based encryption algorithm, contributed by This module implements a rotor-based encryption algorithm, contributed by

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{select}} \section{Built-in Module \sectcode{select}}
\bimodindex{select} \bimodindex{select}
This module provides access to the function \code{select} available in This module provides access to the function \code{select} available in

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{sgmllib}} \section{Standard Module \sectcode{sgmllib}}
\stmodindex{sgmllib} \stmodindex{sgmllib}
\index{SGML} \index{SGML}
@ -66,7 +66,7 @@ redefined version should always call \code{SGMLParser.close()}.
\begin{funcdesc}{handle_charref}{ref} \begin{funcdesc}{handle_charref}{ref}
This method is called to process a character reference of the form This method is called to process a character reference of the form
``\code{\&\#\var{ref};}'' where \var{ref} is a decimal number in the ``\code{\&\#\var{ref};}'' where \var{ref} is a decimal number in the
range 0-255. It translates the character to ASCII and calls the range 0-255. It translates the character to \ASCII{} and calls the
method \code{handle_data()} with the character as argument. If method \code{handle_data()} with the character as argument. If
\var{ref} is invalid or out of range, the method \var{ref} is invalid or out of range, the method
\code{unknown_charref(\var{ref})} is called instead. \code{unknown_charref(\var{ref})} is called instead.

View File

@ -1,7 +1,8 @@
\section{Built-in module \sectcode{shelve}} \section{Standard Module \sectcode{shelve}}
\stmodindex{shelve} \stmodindex{shelve}
\stmodindex{pickle} \stmodindex{pickle}
\bimodindex{dbm} \bimodindex{dbm}
\bimodindex{gdbm}
A ``shelf'' is a persistent, dictionary-like object. The difference A ``shelf'' is a persistent, dictionary-like object. The difference
with ``dbm'' databases is that the values (not the keys!) in a shelf with ``dbm'' databases is that the values (not the keys!) in a shelf
@ -48,8 +49,11 @@ Dependent on the implementation, closing a persistent dictionary may
or may not be necessary to flush changes to disk. or may not be necessary to flush changes to disk.
\item \item
The \code{shelve} module does not support {\em concurrent} access to The \code{shelve} module does not support {\em concurrent} read/write
shelved objects. Two programs should not try to simultaneously access access to shelved objects. (Multiple simultaneous read accesses are
the same shelf. safe.) When a program has a shelf open for writing, no other program
should have it open for reading or writing. \UNIX{} file locking can
be used to solve this, but this differs across \UNIX{} versions and
requires knowledge about the database implementation used.
\end{itemize} \end{itemize}

View File

@ -20,7 +20,7 @@ the Python user is concerned, they can only occur between the
``atomic'' instructions of the Python interpreter. This means that ``atomic'' instructions of the Python interpreter. This means that
signals arriving during long calculations implemented purely in C signals arriving during long calculations implemented purely in C
(e.g.\ regular expression matches on large bodies of text) may be (e.g.\ regular expression matches on large bodies of text) may be
delayed for an arbitrary time. delayed for an arbitrary amount of time.
\item \item
When a signal arrives during an I/O operation, it is possible that the When a signal arrives during an I/O operation, it is possible that the
@ -48,8 +48,10 @@ threads simultaneously is:\ always perform \code{signal()} operations
in the main thread of execution. Any thread can perform an in the main thread of execution. Any thread can perform an
\code{alarm()}, \code{getsignal()}, or \code{pause()}; only the main \code{alarm()}, \code{getsignal()}, or \code{pause()}; only the main
thread can set a new signal handler, and the main thread will be the thread can set a new signal handler, and the main thread will be the
only one to receive signals. This means that signals can't be used as only one to receive signals (this is enforced by the Python signal
a means of interthread communication. Use locks instead. module, even if the underlying thread implementation supports sending
signals to individual threads). This means that signals can't be used
as a means of interthread communication. Use locks instead.
\end{itemize} \end{itemize}
@ -126,4 +128,9 @@ The signal module defines the following functions:
When threads are enabled, this function can only be called from the When threads are enabled, this function can only be called from the
main thread; attempting to call it from other threads will cause a main thread; attempting to call it from other threads will cause a
\code{ValueError} exception to be raised. \code{ValueError} exception to be raised.
The \var{handler} is called with two arguments: the signal number
and the current stack frame (\code{None} or a frame object; see the
reference manual for a description of frame objects).
\obindex{frame}
\end{funcdesc} \end{funcdesc}

View File

@ -37,8 +37,8 @@ All errors raise exceptions. The normal exceptions for invalid
argument types and out-of-memory conditions can be raised; errors argument types and out-of-memory conditions can be raised; errors
related to socket or address semantics raise the error \code{socket.error}. related to socket or address semantics raise the error \code{socket.error}.
Non-blocking and asynchronous mode are not supported; see module Non-blocking mode is supported through the \code{setblocking()}
\code{select} for a way to do non-blocking socket I/O. method.
The module \code{socket} exports the following constants and functions: The module \code{socket} exports the following constants and functions:
@ -95,7 +95,7 @@ is an IP address itself it is returned unchanged.
Return a string containing the hostname of the machine where Return a string containing the hostname of the machine where
the Python interpreter is currently executing. If you want to know the the Python interpreter is currently executing. If you want to know the
current machine's IP address, use current machine's IP address, use
\code{socket.gethostbyname(socket.gethostname())} instead. \code{socket.gethostbyname(socket.gethostname())}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{gethostbyaddr}{ip_address} \begin{funcdesc}{gethostbyaddr}{ip_address}
@ -133,7 +133,7 @@ standard input or output (e.g.\ a server started by the \UNIX{} inet
daemon). daemon).
\end{funcdesc} \end{funcdesc}
\subsection{Socket Object Methods} \subsection{Socket Objects}
\noindent \noindent
Socket objects have the following methods. Except for Socket objects have the following methods. Except for
@ -187,28 +187,30 @@ see above.)
\begin{funcdesc}{getsockopt}{level\, optname\optional{\, buflen}} \begin{funcdesc}{getsockopt}{level\, optname\optional{\, buflen}}
Return the value of the given socket option (see the \UNIX{} man page Return the value of the given socket option (see the \UNIX{} man page
{\it getsockopt}(2)). The needed symbolic constants are defined in {\it getsockopt}(2)). The needed symbolic constants (\code{SO_*} etc.)
the \code{socket} module (\code{SO_*} etc.). If the optional third are defined in this module. If \var{buflen}
argument is absent, an integer option is assumed and its integer value is absent, an integer option is assumed and its integer value
is returned by the function. If \var{buflen} is present, it specifies 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 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 this buffer is returned as a string. It is up to the caller to decode
the contents of the buffer (see the optional built-in module the contents of the buffer (see the optional built-in module
\code{struct} for a way to decode C structures encoded as strings). \code{struct} for a way to decode C structures encoded as strings).
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{listen}{backlog} \begin{funcdesc}{listen}{backlog}
Listen for connections made to the socket. Listen for connections made to the socket. The \var{backlog} argument
The argument specifies the maximum number of queued connections and specifies the maximum number of queued connections and should be at
should be at least 1; the maximum value is system-dependent. least 1; the maximum value is system-dependent (usually 5).
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{makefile}{mode} \begin{funcdesc}{makefile}{\optional{mode\optional{\, bufsize}}}
Return a \dfn{file object} associated with the socket. Return a \dfn{file object} associated with the socket. (File objects
(File objects were described earlier under Built-in Types.) were described earlier under Built-in Types.) The file object
The file object references a \code{dup}ped version of the socket file references a \code{dup()}ped version of the socket file descriptor, so
descriptor, so the file object and socket object may be closed or the file object and socket object may be closed or garbage-collected
garbage-collected independently. independently. The optional \var{mode} and \var{bufsize} arguments
are interpreted the same way as by the built-in
\code{open()} function.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{recv}{bufsize\optional{\, flags}} \begin{funcdesc}{recv}{bufsize\optional{\, flags}}
@ -219,23 +221,26 @@ for the meaning of the optional argument \var{flags}; it defaults to
zero. zero.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{recvfrom}{bufsize} \begin{funcdesc}{recvfrom}{bufsize\optional{\, flags}}
Receive data from the socket. The return value is a pair Receive data from the socket. The return value is a pair
\code{(\var{string}, \var{address})} where \var{string} is a string \code{(\var{string}, \var{address})} where \var{string} is a string
representing the data received and \var{address} is the address of the representing the data received and \var{address} is the address of the
socket sending the data. socket sending the data. The optional \var{flags} argument has the
same meaning as for \code{recv()} above.
(The format of \var{address} depends on the address family --- see above.) (The format of \var{address} depends on the address family --- see above.)
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{send}{string} \begin{funcdesc}{send}{string\optional{\, flags}}
Send data to the socket. The socket must be connected to a remote Send data to the socket. The socket must be connected to a remote
socket. Return the number of bytes sent. socket. The optional \var{flags} argument has the same meaning as for
\code{recv()} above. Return the number of bytes sent.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{sendto}{string\, address} \begin{funcdesc}{sendto}{string\optional{\, flags}\, address}
Send data to the socket. The socket should not be connected to a Send data to the socket. The socket should not be connected to a
remote socket, since the destination socket is specified by remote socket, since the destination socket is specified by
\code{address}. Return the number of bytes sent. \code{address}. The optional \var{flags} argument has the same
meaning as for \code{recv()} above. Return the number of bytes sent.
(The format of \var{address} depends on the address family --- see above.) (The format of \var{address} depends on the address family --- see above.)
\end{funcdesc} \end{funcdesc}

View File

@ -8,9 +8,10 @@ provide access to the functionality of the Standard Window System
Interface, STDWIN [CWI report CR-R8817]. Interface, STDWIN [CWI report CR-R8817].
It is available on systems to which STDWIN has been ported (which is It is available on systems to which STDWIN has been ported (which is
most systems). 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 On Unix running X11, it can only be used if the \code{DISPLAY}
the interpreter. environment variable is set or an explicit \samp{-display
\var{displayname}} argument is passed to the Python interpreter.
Functions have names that usually resemble their C STDWIN counterparts Functions have names that usually resemble their C STDWIN counterparts
with the initial `w' dropped. with the initial `w' dropped.
@ -63,6 +64,7 @@ patterns follow the standard X11 font selection syntax (as used e.g.
in resource definitions), i.e. the wildcard character \code{'*'} in resource definitions), i.e. the wildcard character \code{'*'}
matches any sequence of characters (including none) and \code{'?'} matches any sequence of characters (including none) and \code{'?'}
matches any single character. matches any single character.
On the Macintosh this function currently returns an empty list.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setdefscrollbars}{hflag\, vflag} \begin{funcdesc}{setdefscrollbars}{hflag\, vflag}
@ -164,6 +166,7 @@ returned by this call exists.
\begin{funcdesc}{newbitmap}{width\, height} \begin{funcdesc}{newbitmap}{width\, height}
Create a new bitmap object of the given dimensions. Create a new bitmap object of the given dimensions.
Methods of bitmap objects are described below. Methods of bitmap objects are described below.
Not available on the Macintosh.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{fleep}{} \begin{funcdesc}{fleep}{}
@ -294,7 +297,7 @@ a blocking \code{select()} call.
\ttindex{select} \ttindex{select}
\end{funcdesc} \end{funcdesc}
\subsection{Window Object Methods} \subsection{Window Objects}
Window objects are created by \code{stdwin.open()}. They are closed Window objects are created by \code{stdwin.open()}. They are closed
by their \code{close()} method or when they are garbage-collected. by their \code{close()} method or when they are garbage-collected.
@ -440,7 +443,7 @@ another window in this application became inactive).
Discard the window object. It should not be used again. Discard the window object. It should not be used again.
\end{funcdesc} \end{funcdesc}
\subsection{Drawing Object Methods} \subsection{Drawing Objects}
Drawing objects are created exclusively by the window method Drawing objects are created exclusively by the window method
\code{begindrawing()}. \code{begindrawing()}.
@ -560,6 +563,7 @@ 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 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 bits (ones are drawn in the foreground color, zeros in the background
color). color).
Not available on the Macintosh.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{cliprect}{rect} \begin{funcdesc}{cliprect}{rect}
@ -582,7 +586,7 @@ Reset the clipping region to the entire window.
Discard the drawing object. It should not be used again. Discard the drawing object. It should not be used again.
\end{funcdesc} \end{funcdesc}
\subsection{Menu Object Methods} \subsection{Menu Objects}
A menu object represents a menu. A menu object represents a menu.
The menu is destroyed when the menu object is deleted. The menu is destroyed when the menu object is deleted.
@ -617,11 +621,13 @@ for item
Discard the menu object. It should not be used again. Discard the menu object. It should not be used again.
\end{funcdesc} \end{funcdesc}
\subsection{Bitmap Object Methods} \subsection{Bitmap Objects}
A bitmap represents a rectangular array of bits. A bitmap represents a rectangular array of bits.
The top left bit has coordinate (0, 0). The top left bit has coordinate (0, 0).
A bitmap can be drawn with the \code{bitmap} method of a drawing object. A bitmap can be drawn with the \code{bitmap} method of a drawing object.
Bitmaps are currently not available on the Macintosh.
The following methods are defined: The following methods are defined:
\renewcommand{\indexsubitem}{(bitmap method)} \renewcommand{\indexsubitem}{(bitmap method)}
@ -644,7 +650,7 @@ Return the value of the bit indicated by \var{point}.
Discard the bitmap object. It should not be used again. Discard the bitmap object. It should not be used again.
\end{funcdesc} \end{funcdesc}
\subsection{Text-edit Object Methods} \subsection{Text-edit Objects}
A text-edit object represents a text-edit block. A text-edit object represents a text-edit block.
For semantics, see the STDWIN documentation for C programmers. For semantics, see the STDWIN documentation for C programmers.

View File

@ -61,14 +61,25 @@ the standard syntax for a floating point literal in Python, optionally
preceded by a sign (\samp{+} or \samp{-}). preceded by a sign (\samp{+} or \samp{-}).
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{atoi}{s} \begin{funcdesc}{atoi}{s\optional{\, base}}
Convert a string to an integer. The string must consist of one or more Convert string \var{s} to an integer in the given \var{base}. The
digits, optionally preceded by a sign (\samp{+} or \samp{-}). string must consist of one or more digits, optionally preceded by a
sign (\samp{+} or \samp{-}). The \var{base} defaults to 10. If it is
0, a default base is chosen depending on the leading characters of the
string (after stripping the sign): \samp{0x} or \samp{0X} means 16,
\samp{0} means 8, anything else means 10. If \var{base} is 16, a
leading \samp{0x} or \samp{0X} is always accepted. (Note: for a more
flexible interpretation of numeric literals, use the built-in function
\code{eval()}.
\bifuncindex{eval}
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{atol}{s} \begin{funcdesc}{atol}{s\optional{\, base}}
Convert a string to a long integer. The string must consist of one Convert string \var{s} to a long integer in the given \var{base}. The
or more digits, optionally preceded by a sign (\samp{+} or \samp{-}). string must consist of one or more digits, optionally preceded by a
sign (\samp{+} or \samp{-}). The \var{base} argument has the same
meaning as for \code{atoi()}. A trailing \samp{l} or \samp{L} is not
allowed.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{expandtabs}{s\, tabsize} \begin{funcdesc}{expandtabs}{s\, tabsize}
@ -101,10 +112,11 @@ Like \code{rfind} but raise \code{ValueError} when the substring is
not found. not found.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{count}{s\, sub\optional{\, i}} \begin{funcdesc}{count}{s\, sub\optional{\, start}}
Return the number of (non-overlapping) occurrences of substring Return the number of (non-overlapping) occurrences of substring
\var{sub} in string \var{s} with index at least \var{i}. \var{sub} in string \var{s} with index at least \var{start}.
If \var{i} is omitted, it defaults to \code{0}. If \var{start} is omitted, it defaults to \code{0}. If \var{start} is
negative, \code{len(\var{s})} is added.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{lower}{s} \begin{funcdesc}{lower}{s}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{struct}} \section{Built-in Module \sectcode{struct}}
\bimodindex{struct} \bimodindex{struct}
\indexii{C}{structures} \indexii{C}{structures}

View File

@ -4,7 +4,7 @@ The modules described in this chapter provide interfaces to features
that are unique to the SunOS operating system (versions 4 and 5; the that are unique to the SunOS operating system (versions 4 and 5; the
latter is also known as SOLARIS version 2). latter is also known as SOLARIS version 2).
\section{Built-in module \sectcode{sunaudiodev}} \section{Built-in Module \sectcode{sunaudiodev}}
\bimodindex{sunaudiodev} \bimodindex{sunaudiodev}
This module allows you to access the sun audio interface. The sun This module allows you to access the sun audio interface. The sun
@ -30,7 +30,7 @@ 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. only for the activity needed. See the audio manpage for details.
\end{funcdesc} \end{funcdesc}
\subsection{Audio device object methods} \subsection{Audio Device Objects}
The audio device objects are returned by \code{open} define the The audio device objects are returned by \code{open} define the
following methods (except \code{control} objects which only provide following methods (except \code{control} objects which only provide
@ -108,6 +108,5 @@ the constants are the same names as used in the C include file
\file{<sun/audioio.h>}, with the leading string \samp{AUDIO_} stripped. \file{<sun/audioio.h>}, with the leading string \samp{AUDIO_} stripped.
Useability of the control device is limited at the moment, since there 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 is no way to use the ``wait for something to happen'' feature the
provides. This is because that feature makes heavy use of signals, and device provides.
these do not map too well onto Python.

View File

@ -6,11 +6,16 @@ interpreter and to functions that interact strongly with the interpreter.
It is always available. It is always available.
\renewcommand{\indexsubitem}{(in module sys)} \renewcommand{\indexsubitem}{(in module sys)}
\begin{datadesc}{argv} \begin{datadesc}{argv}
The list of command line arguments passed to a Python script. The list of command line arguments passed to a Python script.
\code{sys.argv[0]} is the script name. \code{sys.argv[0]} is the script name (it is operating system
dependent whether this is a full pathname or not).
If the command was executed using the \samp{-c} command line option
to the interpreter, \code{sys.argv[0]} is set to the string
\code{"-c"}.
If no script name was passed to the Python interpreter, If no script name was passed to the Python interpreter,
\code{sys.argv} is empty. \code{sys.argv} has zero length.
\end{datadesc} \end{datadesc}
\begin{datadesc}{builtin_module_names} \begin{datadesc}{builtin_module_names}
@ -28,9 +33,11 @@ It is always available.
invoked. Their meaning is: \code{exc_type} gets the exception type of invoked. Their meaning is: \code{exc_type} gets the exception type of
the exception being handled; \code{exc_value} gets the exception the exception being handled; \code{exc_value} gets the exception
parameter (its \dfn{associated value} or the second argument to parameter (its \dfn{associated value} or the second argument to
\code{raise}); \code{exc_traceback} gets a traceback object which \code{raise}); \code{exc_traceback} gets a traceback object (see the
Reference Manual) which
encapsulates the call stack at the point where the exception encapsulates the call stack at the point where the exception
originally occurred. originally occurred.
\obindex{traceback}
\end{datadesc} \end{datadesc}
\begin{funcdesc}{exit}{n} \begin{funcdesc}{exit}{n}
@ -45,7 +52,7 @@ It is always available.
This value is not actually defined by the module, but can be set by 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 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 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 will be called when the interpreter exits in any way (except not when a
fatal error occurs: in that case the interpreter's internal state fatal error occurs: in that case the interpreter's internal state
cannot be trusted). cannot be trusted).
\end{datadesc} \end{datadesc}
@ -94,26 +101,23 @@ maximizing responsiveness as well as overhead.
\begin{funcdesc}{settrace}{tracefunc} \begin{funcdesc}{settrace}{tracefunc}
Set the system's trace function, which allows you to implement a Set the system's trace function, which allows you to implement a
Python source code debugger in Python. The standard modules Python source code debugger in Python. See section ``How It Works''
\code{pdb} and \code{wdb} are such debuggers; the difference is that in the chapter on the Python Debugger.
\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} \end{funcdesc}
\ttindex{pdb}
\ttindex{wdb}
\index{trace function} \index{trace function}
\index{debugger}
\begin{funcdesc}{setprofile}{profilefunc} \begin{funcdesc}{setprofile}{profilefunc}
Set the system's profile function, which allows you to implement a Set the system's profile function, which allows you to implement a
Python source code profiler in Python. The system's profile function Python source code profiler in Python. See the chapter on the
Python Profiler. The system's profile function
is called similarly to the system's trace function (see is called similarly to the system's trace function (see
\code{sys.settrace}), but it isn't called for each executed line of \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, 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}. its return value is not used, so it can just return \code{None}.
\end{funcdesc} \end{funcdesc}
\index{profile function} \index{profile function}
\index{profiler}
\begin{datadesc}{stdin} \begin{datadesc}{stdin}
\dataline{stdout} \dataline{stdout}
@ -127,7 +131,11 @@ maximizing responsiveness as well as overhead.
own prompts and (almost all of) its error messages go to own prompts and (almost all of) its error messages go to
\code{sys.stderr}. \code{sys.stdout} and \code{sys.stderr} needn't \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 be built-in file objects: any object is acceptable as long as it has
a \code{write} method that takes a string argument. a \code{write} method that takes a string argument. (Changing these
objects doesn't affect the standard I/O streams of processes
executed by \code{popen()}, \code{system()} or the \code{exec*()}
family of functions in the \code{os} module.)
\stmodindex{os}
\end{datadesc} \end{datadesc}
\begin{datadesc}{tracebacklimit} \begin{datadesc}{tracebacklimit}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{tempfile}} \section{Standard Module \sectcode{tempfile}}
\stmodindex{tempfile} \stmodindex{tempfile}
\indexii{temporary}{file name} \indexii{temporary}{file name}
\indexii{temporary}{file} \indexii{temporary}{file}

View File

@ -7,7 +7,7 @@
% \section{} generates the section header, % \section{} generates the section header,
% \bimodindex{} or \stmodundex{} generates an index entry for this module % \bimodindex{} or \stmodundex{} generates an index entry for this module
\section{Built-in module \sectcode{spam}} % If implemented in C \section{Built-in Module \sectcode{spam}} % If implemented in C
\bimodindex[spam} \bimodindex[spam}
\section{Standard module \sectcode{spam}} % If implemented in Python \section{Standard module \sectcode{spam}} % If implemented in Python
@ -110,7 +110,7 @@ Example:
% separate subsection. It is important to redefine ``indexsubitem'' % separate subsection. It is important to redefine ``indexsubitem''
% for each subsection. % for each subsection.
\subsection{Spam methods} \subsection{Spam Objects}
Spam objects (returned by \code{open()} above) have the following Spam objects (returned by \code{open()} above) have the following
methods. methods.

View File

@ -26,18 +26,22 @@ terminates with an unhandled exception, a stack trace is printed and
then the thread exits (but other threads continue to run). then the thread exits (but other threads continue to run).
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{exit_thread}{} \begin{funcdesc}{exit}{}
Exit the current thread silently. Other threads continue to run. This is a shorthand for \code{thread.exit_thread()}.
\strong{Caveat:} code in pending \code{finally} clauses is not executed.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{exit_prog}{status} \begin{funcdesc}{exit_thread}{}
Exit all threads and report the value of the integer argument Raise the \code{SystemExit} exception. When not caught, this will
\var{status} as the exit status of the entire program. cause the thread to exit silently.
\strong{Caveat:} code in pending \code{finally} clauses, in this thread
or in other threads, is not executed.
\end{funcdesc} \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}{} \begin{funcdesc}{allocate_lock}{}
Return a new lock object. Methods of locks are described below. The Return a new lock object. Methods of locks are described below. The
lock is initially unlocked. lock is initially unlocked.
@ -82,18 +86,16 @@ thread, 0 if not.
\item \item
Threads interact strangely with interrupts: the Threads interact strangely with interrupts: the
\code{KeyboardInterrupt} exception will be received by an arbitrary \code{KeyboardInterrupt} exception will be received by an arbitrary
thread. thread. (When the \code{signal} module is available, interrupts
always go to the main thread.)
\item \item
Calling \code{sys.exit(\var{status})} or executing Calling \code{sys.exit()} or raising the \code{SystemExit} is
\code{raise SystemExit, \var{status}} is almost equivalent to calling equivalent to calling \code{thread.exit_thread()}.
\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 \item
Not all built-in functions that may block waiting for I/O allow other Not all built-in functions that may block waiting for I/O allow other
threads to run, although the most popular ones (\code{sleep}, threads to run. (The most popular ones (\code{sleep}, \code{read},
\code{read}, \code{select}) work as expected. \code{select}) work as expected.)
\end{itemize} \end{itemize}

View File

@ -11,8 +11,7 @@ An explanation of some terminology and conventions is in order.
\item \item
The ``epoch'' is the point where the time starts. On January 1st of that The ``epoch'' is the point where the time starts. On January 1st of that
year, at 0 hours, the ``time since the epoch'' is zero. For UNIX, the 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 epoch is 1970. To find out what the epoch is, look at \code{gmtime(0)}.
element of \code{gmtime(0)}.
\item \item
UTC is Coordinated Universal Time (formerly known as Greenwich Mean UTC is Coordinated Universal Time (formerly known as Greenwich Mean
@ -30,19 +29,20 @@ in this respect.
\item \item
The precision of the various real-time functions may be less than The precision of the various real-time functions may be less than
suggested by the units in which their value or argument is expressed. 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 E.g.\ on most UNIX systems, the clock ``ticks'' only 50 or 100 times a
1/100th of a second, and on the Mac, it ticks 60 times a second. second, and on the Mac, times are only accurate to whole seconds.
\end{itemize} \end{itemize}
Functions and data items are: The module defines the following functions and data items:
\renewcommand{\indexsubitem}{(in module time)} \renewcommand{\indexsubitem}{(in module time)}
\begin{datadesc}{altzone} \begin{datadesc}{altzone}
The offset of the local DST timezone, in seconds west of the 0th 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 meridian, if one is defined. Negative if the local DST timezone is
nonzero. east of the 0th meridian (as in Western Europe, including the UK).
Only use this if \code{daylight} is nonzero.
\end{datadesc} \end{datadesc}
@ -56,8 +56,8 @@ the same name, there is no trailing newline.
\begin{funcdesc}{clock}{} \begin{funcdesc}{clock}{}
Return the current CPU time as a floating point number expressed in Return the current CPU time as a floating point number expressed in
seconds. The precision depends on that of the C function by the same seconds. The precision, and in fact the very definiton of the meaning
name. of ``CPU time'', depends on that of the C function of the same name.
\end{funcdesc} \end{funcdesc}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{traceback}} \section{Standard Module \sectcode{traceback}}
\stmodindex{traceback} \stmodindex{traceback}
\renewcommand{\indexsubitem}{(in module traceback)} \renewcommand{\indexsubitem}{(in module traceback)}

View File

@ -189,7 +189,7 @@ Conversion from floating point to (long or plain) integer may round or
truncate as in \C{}; see functions \code{floor} and \code{ceil} in module truncate as in \C{}; see functions \code{floor} and \code{ceil} in module
\code{math} for well-defined conversions. \code{math} for well-defined conversions.
\indexii{numeric}{conversions} \indexii{numeric}{conversions}
\ttindex{math} \stmodindex{math}
\indexii{\C{}}{language} \indexii{\C{}}{language}
\item[(2)] \item[(2)]
@ -205,7 +205,7 @@ See the section on built-in functions for an exact definition.
\end{description} \end{description}
% XXXJH exceptions: overflow (when? what operations?) zerodivision % XXXJH exceptions: overflow (when? what operations?) zerodivision
\subsubsection{Bit-string Operations on Integer Types.} \subsubsection{Bit-string Operations on Integer Types}
Plain and long integer types support additional operations that make Plain and long integer types support additional operations that make
sense only for bit-strings. Negative numbers are treated as their 2's sense only for bit-strings. Negative numbers are treated as their 2's
@ -287,7 +287,7 @@ Notes:
\end{description} \end{description}
\subsubsection{More String Operations.} \subsubsection{More String Operations}
String objects have one unique built-in operation: the \code{\%} String objects have one unique built-in operation: the \code{\%}
operator (modulo) with a string left argument interprets this string operator (modulo) with a string left argument interprets this string
@ -307,7 +307,7 @@ present but are ignored. The \code{\%s} conversion takes any Python
object and converts it to a string using \code{str()} before object and converts it to a string using \code{str()} before
formatting it. The ANSI features \code{\%p} and \code{\%n} formatting it. The ANSI features \code{\%p} and \code{\%n}
are not supported. Since Python strings have an explicit length, are not supported. Since Python strings have an explicit length,
\code{\%s} conversions don't assume that \code{'\\0'} is the end of \code{\%s} conversions don't assume that \code{'\e0'} is the end of
the string. the string.
For safety reasons, floating point precisions are clipped to 50; For safety reasons, floating point precisions are clipped to 50;
@ -330,14 +330,15 @@ each format formats the corresponding entry from the mapping. E.g.
Python has 002 quote types. Python has 002 quote types.
>>> >>>
\end{verbatim} \end{verbatim}
In this case no * specifiers may occur in a format. In this case no * specifiers may occur in a format (since they a
require sequential parameter list).
Additional string operations are defined in standard module Additional string operations are defined in standard module
\code{string} and in built-in module \code{regex}. \code{string} and in built-in module \code{regex}.
\index{string} \index{string}
\index{regex} \index{regex}
\subsubsection{Mutable Sequence Types.} \subsubsection{Mutable Sequence Types}
List objects support additional operations that allow in-place List objects support additional operations that allow in-place
modification of the object. modification of the object.
@ -399,7 +400,7 @@ Notes:
should return \code{-1}, \code{0} or \code{1} depending on whether the 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 first argument is considered smaller than, equal to, or larger than the
second argument. Note that this slows the sorting process down second argument. Note that this slows the sorting process down
considerably; e.g. to sort an array in reverse order it is much faster considerably; e.g. to sort a list in reverse order it is much faster
to use calls to \code{sort()} and \code{reverse()} than to use to use calls to \code{sort()} and \code{reverse()} than to use
\code{sort()} with a comparison function that reverses the ordering of \code{sort()} with a comparison function that reverses the ordering of
the elements. the elements.
@ -409,7 +410,7 @@ Notes:
A \dfn{mapping} object maps values of one type (the key type) to A \dfn{mapping} object maps values of one type (the key type) to
arbitrary objects. Mappings are mutable objects. There is currently arbitrary objects. Mappings are mutable objects. There is currently
only one mapping type, the \dfn{dictionary}. A dictionary's keys are only one standard mapping type, the \dfn{dictionary}. A dictionary's keys are
almost arbitrary values. The only types of values not acceptable as almost arbitrary values. The only types of values not acceptable as
keys are values containing lists or dictionaries or other mutable keys are values containing lists or dictionaries or other mutable
types that are compared by value rather than by object identity. types that are compared by value rather than by object identity.
@ -421,9 +422,9 @@ can be used interchangeably to index the same dictionary entry.
\indexii{dictionary}{type} \indexii{dictionary}{type}
Dictionaries are created by placing a comma-separated list of Dictionaries are created by placing a comma-separated list of
\code{\var{key}: \var{value}} pairs within braces, for example: \code{\var{key}:\ \var{value}} pairs within braces, for example:
\code{\{'jack': 4098, 'sjoerd: 4127\}} or \code{\{'jack':\ 4098, 'sjoerd':\ 4127\}} or
\code{\{4098: 'jack', 4127: 'sjoerd\}}. \code{\{4098:\ 'jack', 4127:\ 'sjoerd'\}}.
The following operations are defined on mappings (where \var{a} is a 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): mapping, \var{k} is a key and \var{x} is an arbitrary object):
@ -453,9 +454,7 @@ Notes:
\begin{description} \begin{description}
\item[(1)] Raises an exception if \var{k} is not in the map. \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 \item[(2)] Keys and values are listed in random order.
moment the ordering of the \code{keys()}, \code{values()} and
\code{items()} lists is the consistent with each other.
\end{description} \end{description}
\subsection{Other Built-in Types} \subsection{Other Built-in Types}
@ -463,7 +462,7 @@ moment the ordering of the \code{keys()}, \code{values()} and
The interpreter supports several other kinds of objects. The interpreter supports several other kinds of objects.
Most of these support only one or two operations. Most of these support only one or two operations.
\subsubsection{Modules.} \subsubsection{Modules}
The only special operation on a module is attribute access: 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 \code{\var{m}.\var{name}}, where \var{m} is a module and \var{name} accesses
@ -483,11 +482,11 @@ defines \code{\var{m}.a} to be \code{1}, but you can't write \code{\var{m}.__dic
Modules are written like this: \code{<module 'sys'>}. Modules are written like this: \code{<module 'sys'>}.
\subsubsection{Classes and Class Instances.} \subsubsection{Classes and Class Instances}
% XXXJH cross ref here % XXXJH cross ref here
(See the Python Reference Manual for these.) (See the Python Reference Manual for these.)
\subsubsection{Functions.} \subsubsection{Functions}
Function objects are created by function definitions. The only Function objects are created by function definitions. The only
operation on a function object is to call it: operation on a function object is to call it:
@ -504,7 +503,7 @@ The implementation adds two special read-only attributes:
global name space (this is the same as \code{\var{m}.__dict__} where 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). \var{m} is the module in which the function \var{f} was defined).
\subsubsection{Methods.} \subsubsection{Methods}
\obindex{method} \obindex{method}
Methods are functions that are called using the attribute notation. Methods are functions that are called using the attribute notation.
@ -522,7 +521,7 @@ Calling \code{\var{m}(\var{arg-1}, \var{arg-2}, {\rm \ldots},
(See the Python Reference Manual for more info.) (See the Python Reference Manual for more info.)
\subsubsection{Code Objects.} \subsubsection{Code Objects}
\obindex{code} \obindex{code}
Code objects are used by the implementation to represent Code objects are used by the implementation to represent
@ -543,7 +542,7 @@ source string) to the \code{exec} statement or the built-in
(See the Python Reference Manual for more info.) (See the Python Reference Manual for more info.)
\subsubsection{Type Objects.} \subsubsection{Type Objects}
Type objects represent the various object types. An object's type is Type objects represent the various object types. An object's type is
% XXXJH xref here % XXXJH xref here
@ -552,7 +551,7 @@ operations on types.
Types are written like this: \code{<type 'int'>}. Types are written like this: \code{<type 'int'>}.
\subsubsection{The Null Object.} \subsubsection{The Null Object}
This object is returned by functions that don't explicitly return a This object is returned by functions that don't explicitly return a
value. It supports no special operations. There is exactly one null value. It supports no special operations. There is exactly one null
@ -560,7 +559,7 @@ object, named \code{None} (a built-in name).
It is written as \code{None}. It is written as \code{None}.
\subsubsection{File Objects.} \subsubsection{File Objects}
File objects are implemented using \C{}'s \code{stdio} package and can be File objects are implemented using \C{}'s \code{stdio} package and can be
% XXXJH xref here % XXXJH xref here
@ -643,7 +642,7 @@ Write a list of strings to the file. There is no return value.
does not add line separators.) does not add line separators.)
\end{funcdesc} \end{funcdesc}
\subsubsection{Internal Objects.} \subsubsection{Internal Objects}
(See the Python Reference Manual for these.) (See the Python Reference Manual for these.)

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{types}} \section{Standard Module \sectcode{types}}
\stmodindex{types} \stmodindex{types}
\renewcommand{\indexsubitem}{(in module types)} \renewcommand{\indexsubitem}{(in module types)}

View File

@ -1,7 +1,7 @@
\section{Built-in module \sectcode{urllib}} \section{Standard Module \sectcode{urllib}}
\stmodindex{urllib} \stmodindex{urllib}
\index{WWW} \index{WWW}
\indexii{World-Wide}{Web} \index{World-Wide Web}
\index{URL} \index{URL}
\renewcommand{\indexsubitem}{(in module urllib)} \renewcommand{\indexsubitem}{(in module urllib)}
@ -17,7 +17,7 @@ it defines the following public functions:
\begin{funcdesc}{urlopen}{url} \begin{funcdesc}{urlopen}{url}
Open a network object denoted by a URL for reading. If the URL does Open a network object denoted by a URL for reading. If the URL does
not have a scheme identifier, or if it has \code{file:} as its scheme not have a scheme identifier, or if it has \samp{file:} as its scheme
identifier, this opens a local file; otherwise it opens a socket to a identifier, this opens a local file; otherwise it opens a socket to a
server somewhere on the network. If the connection cannot be made, or server somewhere on the network. If the connection cannot be made, or
if the server returns an error code, the \code{IOError} exception is if the server returns an error code, the \code{IOError} exception is
@ -26,7 +26,9 @@ supports the following methods: \code{read()}, \code{readline()},
\code{readlines()}, \code{fileno()}, \code{close()} and \code{info()}. \code{readlines()}, \code{fileno()}, \code{close()} and \code{info()}.
Except for the last one, these methods have the same interface as for Except for the last one, these methods have the same interface as for
file objects --- see the section on File Objects earlier in this file objects --- see the section on File Objects earlier in this
manual. manual. (It's not a built-in file object, however, so it can't be
used at those few places where a true built-in file object is
required.)
The \code{info()} method returns an instance of the class The \code{info()} method returns an instance of the class
\code{rfc822.Message} containing the headers received from the server, \code{rfc822.Message} containing the headers received from the server,

View File

@ -1,7 +1,7 @@
\section{Built-in module \sectcode{urlparse}} \section{Standard Module \sectcode{urlparse}}
\stmodindex{urlparse} \stmodindex{urlparse}
\index{WWW} \index{WWW}
\indexii{World-Wide}{Web} \index{World-Wide Web}
\index{URL} \index{URL}
\indexii{URL}{parsing} \indexii{URL}{parsing}
\indexii{relative}{URL} \indexii{relative}{URL}
@ -28,14 +28,14 @@ identifier). This corresponds to the general structure of a URL:
Each tuple item is a string, possibly empty. Each tuple item is a string, possibly empty.
The components are not broken up in smaller parts (e.g. the network The components are not broken up in smaller parts (e.g. the network
location is a single string), and \% escapes are not expanded. location is a single string), and \% escapes are not expanded.
The delimiters as shown above are not part of the tuple items, {\em The delimiters as shown above are not part of the tuple items,
except} for a leading slash in the \var{path} component, which is except for a leading slash in the \var{path} component, which is
kept if present. retained if present.
Example: Example:
\code{urlparse('http://www.cwi.nl:80/\%7eguido/Python.html')} \code{urlparse('http://www.cwi.nl:80/\%7eguido/Python.html')}
yields the tuple yields the tuple
\code{('http', 'www.cwi.nl:80', '/\%e7guido/Python.html', '', '', '')}. \code{('http', 'www.cwi.nl:80', '/\%7eguido/Python.html', '', '', '')}.
If the \var{default_scheme} argument is specified, it gives the If the \var{default_scheme} argument is specified, it gives the
default addressing scheme, to be used only if the URL string does not default addressing scheme, to be used only if the URL string does not

View File

@ -1,6 +1,7 @@
\chapter{WORLD-WIDE WEB EXTENSIONS} \chapter{THE INTERNET AND THE WORLD-WIDE WEB}
\index{WWW} \index{WWW}
\indexii{World-Wide}{Web} \index{Internet}
\index{World-Wide Web}
The modules described in this chapter provide various services to The modules described in this chapter provide various services to
World-Wide Web (WWW) clients and/or services, and a few modules World-Wide Web (WWW) clients and/or services, and a few modules

View File

@ -21,8 +21,11 @@ Module \code{aifc} defines the following function:
Open an AIFF or AIFF-C file and return an object instance with Open an AIFF or AIFF-C file and return an object instance with
methods that are described below. The argument file is either a 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 string naming a file or a file object. The mode is either the string
'r' when the file must be opened for reading, or 'w' when the file \code{'r'} when the file must be opened for reading, or \code{'w'}
must be opened for writing. 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
\code{writeframesraw()} and \code{setnframes()}.
\end{funcdesc} \end{funcdesc}
Objects returned by \code{aifc.open()} when a file is opened for Objects returned by \code{aifc.open()} when a file is opened for

View File

@ -1,13 +1,15 @@
\section{Built-in Module \sectcode{al}} \section{Built-in Module \sectcode{al}}
\bimodindex{al} \bimodindex{al}
This module provides access to the audio facilities of the Indigo and This module provides access to the audio facilities of the SGI Indy
4D/35 workstations, described in section 3A of the IRIX 4.0 man pages and Indigo workstations. See section 3A of the IRIX man pages for
(and also available as an option in IRIX 3.3). You'll need to read details. You'll need to read those man pages to understand what these
those man pages to understand what these functions do! functions do! Some of the functions are not available in IRIX
Some of the functions are not available in releases below 4.0.5. releases before 4.0.5. Again, see the manual to check whether a
Again, see the manual to check whether a specific function is specific function is available on your platform.
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 \file{<audio.h>} are defined Symbolic constants from the C header file \file{<audio.h>} are defined
in the standard module \code{AL}, see below. in the standard module \code{AL}, see below.
@ -20,145 +22,138 @@ interface can provide no protection against this kind of problems.
(One example is specifying an excessive queue size --- there is no (One example is specifying an excessive queue size --- there is no
documented upper limit.) documented upper limit.)
Module \code{al} defines the following functions: The module defines the following functions:
\renewcommand{\indexsubitem}{(in module al)} \renewcommand{\indexsubitem}{(in module al)}
\begin{funcdesc}{openport}{name\, direction\optional{\, config}} \begin{funcdesc}{openport}{name\, direction\optional{\, config}}
Equivalent to the C function ALopenport(). The name and direction The name and direction arguments are strings. The optional config
arguments are strings. The optional config argument is an opaque argument is a configuration object as returned by
configuration object as returned by \code{al.newconfig()}. The return \code{al.newconfig()}. The return value is an \dfn{port object};
value is an opaque port object; methods of port objects are described methods of port objects are described below.
below.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{newconfig}{} \begin{funcdesc}{newconfig}{}
Equivalent to the C function ALnewconfig(). The return value is a new The return value is a new \dfn{configuration object}; methods of
opaque configuration object; methods of configuration objects are configuration objects are described below.
described below.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{queryparams}{device} \begin{funcdesc}{queryparams}{device}
Equivalent to the C function ALqueryparams(). The device argument is The device argument is an integer. The return value is a list of
an integer. The return value is a list of integers containing the integers containing the data returned by ALqueryparams().
data returned by ALqueryparams().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getparams}{device\, list} \begin{funcdesc}{getparams}{device\, list}
Equivalent to the C function ALgetparams(). The device argument is an The device argument is an integer. The list argument is a list such
integer. The list argument is a list such as returned by as returned by \code{queryparams}; it is modified in place (!).
\code{queryparams}; it is modified in place (!).
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setparams}{device\, list} \begin{funcdesc}{setparams}{device\, list}
Equivalent to the C function ALsetparams(). The device argument is an The device argument is an integer. The list argument is a list such
integer.The list argument is a list such as returned by as returned by \code{al.queryparams}.
\code{al.queryparams}.
\end{funcdesc} \end{funcdesc}
\subsection{Configuration Objects}
Configuration objects (returned by \code{al.newconfig()} have the Configuration objects (returned by \code{al.newconfig()} have the
following methods: following methods:
\renewcommand{\indexsubitem}{(audio configuration object method)} \renewcommand{\indexsubitem}{(audio configuration object method)}
\begin{funcdesc}{getqueuesize}{} \begin{funcdesc}{getqueuesize}{}
Return the queue size; equivalent to the C function ALgetqueuesize(). Return the queue size.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setqueuesize}{size} \begin{funcdesc}{setqueuesize}{size}
Set the queue size; equivalent to the C function ALsetqueuesize(). Set the queue size.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getwidth}{} \begin{funcdesc}{getwidth}{}
Get the sample width; equivalent to the C function ALgetwidth(). Get the sample width.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getwidth}{width} \begin{funcdesc}{setwidth}{width}
Set the sample width; equivalent to the C function ALsetwidth(). Set the sample width.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getchannels}{} \begin{funcdesc}{getchannels}{}
Get the channel count; equivalent to the C function ALgetchannels(). Get the channel count.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setchannels}{nchannels} \begin{funcdesc}{setchannels}{nchannels}
Set the channel count; equivalent to the C function ALsetchannels(). Set the channel count.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getsampfmt}{} \begin{funcdesc}{getsampfmt}{}
Get the sample format; equivalent to the C function ALgetsampfmt(). Get the sample format.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setsampfmt}{sampfmt} \begin{funcdesc}{setsampfmt}{sampfmt}
Set the sample format; equivalent to the C function ALsetsampfmt(). Set the sample format.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getfloatmax}{} \begin{funcdesc}{getfloatmax}{}
Get the maximum value for floating sample formats; Get the maximum value for floating sample formats.
equivalent to the C function ALgetfloatmax().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setfloatmax}{floatmax} \begin{funcdesc}{setfloatmax}{floatmax}
Set the maximum value for floating sample formats; Set the maximum value for floating sample formats.
equivalent to the C function ALsetfloatmax().
\end{funcdesc} \end{funcdesc}
\subsection{Port Objects}
Port objects (returned by \code{al.openport()} have the following Port objects (returned by \code{al.openport()} have the following
methods: methods:
\renewcommand{\indexsubitem}{(audio port object method)} \renewcommand{\indexsubitem}{(audio port object method)}
\begin{funcdesc}{closeport}{} \begin{funcdesc}{closeport}{}
Close the port; equivalent to the C function ALcloseport(). Close the port.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getfd}{} \begin{funcdesc}{getfd}{}
Return the file descriptor as an int; equivalent to the C function Return the file descriptor as an int.
ALgetfd().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getfilled}{} \begin{funcdesc}{getfilled}{}
Return the number of filled samples; equivalent to the C function Return the number of filled samples.
ALgetfilled().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getfillable}{} \begin{funcdesc}{getfillable}{}
Return the number of fillable samples; equivalent to the C function Return the number of fillable samples.
ALgetfillable().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{readsamps}{nsamples} \begin{funcdesc}{readsamps}{nsamples}
Read a number of samples from the queue, blocking if necessary; Read a number of samples from the queue, blocking if necessary.
equivalent to the C function ALreadsamples. The data is returned as a Return the data as a string containing the raw data, (e.g., 2 bytes per
string containing the raw data (e.g. 2 bytes per sample in big-endian sample in big-endian byte order (high byte, low byte) if you have set
byte order (high byte, low byte) if you have set the sample width to 2 the sample width to 2 bytes).
bytes.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{writesamps}{samples} \begin{funcdesc}{writesamps}{samples}
Write samples into the queue, blocking if necessary; equivalent to the Write samples into the queue, blocking if necessary. The samples are
C function ALwritesamples. The samples are encoded as described for encoded as described for the \code{readsamps} return value.
the \code{readsamps} return value.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getfillpoint}{} \begin{funcdesc}{getfillpoint}{}
Return the `fill point'; equivalent to the C function ALgetfillpoint(). Return the `fill point'.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setfillpoint}{fillpoint} \begin{funcdesc}{setfillpoint}{fillpoint}
Set the `fill point'; equivalent to the C function ALsetfillpoint(). Set the `fill point'.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getconfig}{} \begin{funcdesc}{getconfig}{}
Return a configuration object containing the current configuration of Return a configuration object containing the current configuration of
the port; equivalent to the C function ALgetconfig(). the port.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{setconfig}{config} \begin{funcdesc}{setconfig}{config}
Set the configuration from the argument, a configuration object; Set the configuration from the argument, a configuration object.
equivalent to the C function ALsetconfig().
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getstatus}{list} \begin{funcdesc}{getstatus}{list}
Get status information on last error Get status information on last error.
equivalent to C function ALgetstatus().
\end{funcdesc} \end{funcdesc}
\section{Standard Module \sectcode{AL}} \section{Standard Module \sectcode{AL}}

View File

@ -70,7 +70,7 @@ Initially, the timeout is set to 2 seconds by the Python interpreter.
\subsection{Capability Operations} \subsection{Capability Operations}
Capabilities are written in a convenient ASCII format, also used by the Capabilities are written in a convenient \ASCII{} format, also used by the
Amoeba utilities Amoeba utilities
{\it c2a}(U) {\it c2a}(U)
and and

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{array}} \section{Built-in Module \sectcode{array}}
\bimodindex{array} \bimodindex{array}
\index{arrays} \index{arrays}
@ -21,7 +21,7 @@ which is a single character. The following type codes are defined:
The actual representation of values is determined by the machine The actual representation of values is determined by the machine
architecture (strictly speaking, by the C implementation). The actual architecture (strictly speaking, by the C implementation). The actual
size can be accessed through the \var{typecode} attribute. size can be accessed through the \var{itemsize} attribute.
The module defines the following function: The module defines the following function:
@ -59,7 +59,9 @@ on a machine with a different byte order.
Read \var{n} items (as machine values) from the file object \var{f} 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 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 are available, \code{EOFError} is raised, but the items that were
available are still inserted into the array. available are still inserted into the array. \var{f} must be a real
built-in file object; something else with a \code{read()} method won't
do.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{fromlist}{list} \begin{funcdesc}{fromlist}{list}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{audioop}} \section{Built-in Module \sectcode{audioop}}
\bimodindex{audioop} \bimodindex{audioop}
The \code{audioop} module contains some useful operations on sound fragments. The \code{audioop} module contains some useful operations on sound fragments.
@ -19,96 +19,97 @@ per sample, etc.
\end{excdesc} \end{excdesc}
\begin{funcdesc}{add}{fragment1\, fragment2\, width} \begin{funcdesc}{add}{fragment1\, fragment2\, width}
This function returns a fragment which is the addition of the two samples Return a fragment which is the addition of the two samples passed as
passed as parameters. \var{width} is the sample width in bytes, either parameters. \var{width} is the sample width in bytes, either
\code{1}, \code{2} or \code{4}. Both fragments should have the same length. \code{1}, \code{2} or \code{4}. Both fragments should have the same
length.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{adpcm2lin}{adpcmfragment\, width\, state} \begin{funcdesc}{adpcm2lin}{adpcmfragment\, width\, state}
This routine decodes an Intel/DVI ADPCM coded fragment to a linear Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See
fragment. See the description of \code{lin2adpcm} for details on ADPCM the description of \code{lin2adpcm} for details on ADPCM coding.
coding. The routine returns a tuple Return a tuple \code{(\var{sample}, \var{newstate})} where the sample
\code{(\var{sample}, \var{newstate})} has the width specified in \var{width}.
where the sample has the width specified in \var{width}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{adpcm32lin}{adpcmfragment\, width\, state} \begin{funcdesc}{adpcm32lin}{adpcmfragment\, width\, state}
This routine decodes an alternative 3-bit ADPCM code. See Decode an alternative 3-bit ADPCM code. See \code{lin2adpcm3} for
\code{lin2adpcm3} for details. details.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{avg}{fragment\, width} \begin{funcdesc}{avg}{fragment\, width}
This function returns the average over all samples in the fragment. Return the average over all samples in the fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{avgpp}{fragment\, width} \begin{funcdesc}{avgpp}{fragment\, width}
This function returns the average peak-peak value over all samples in Return the average peak-peak value over all samples in the fragment.
the fragment. No filtering is done, so the usefulness of this routine No filtering is done, so the usefulness of this routine is
is questionable. questionable.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{bias}{fragment\, width\, bias} \begin{funcdesc}{bias}{fragment\, width\, bias}
This function returns a fragment that is the original fragment with a Return a fragment that is the original fragment with a bias added to
bias added to each sample. each sample.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{cross}{fragment\, width} \begin{funcdesc}{cross}{fragment\, width}
This function returns the number of zero crossings in the fragment Return the number of zero crossings in the fragment passed as an
passed as an argument. argument.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{findfactor}{fragment\, reference} \begin{funcdesc}{findfactor}{fragment\, reference}
This routine (which only accepts 2-byte sample fragments) calculates a Return a factor \var{F} such that
factor \var{F} such that \code{rms(add(fragment, mul(reference, -F)))} \code{rms(add(fragment, mul(reference, -F)))} is minimal, i.e.,
is minimal, i.e.\ it calculates the factor with which you should return the factor with which you should multiply \var{reference} to
multiply \var{reference} to make it match as well as possible to make it match as well as possible to \var{fragment}. The fragments
\var{fragment}. The fragments should be the same size. should both contain 2-byte samples.
The time taken by this routine is proportional to \code{len(fragment)}. The time taken by this routine is proportional to \code{len(fragment)}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{findfit}{fragment\, reference} \begin{funcdesc}{findfit}{fragment\, reference}
This routine (which only accepts 2-byte sample fragments) tries to This routine (which only accepts 2-byte sample fragments)
match \var{reference} as well as possible to a portion of
\var{fragment} (which should be the longer fragment). It Try to match \var{reference} as well as possible to a portion of
(conceptually) does this by taking slices out of \var{fragment}, using \var{fragment} (which should be the longer fragment). This is
(conceptually) done by taking slices out of \var{fragment}, using
\code{findfactor} to compute the best match, and minimizing the \code{findfactor} to compute the best match, and minimizing the
result. result. The fragments should both contain 2-byte samples. Return a
It returns a tuple \code{(\var{offset}, \var{factor})} with \var{offset} the tuple \code{(\var{offset}, \var{factor})} where \var{offset} is the
(integer) offset into \var{fragment} where the optimal match started (integer) offset into \var{fragment} where the optimal match started
and \var{factor} the floating-point factor as per \code{findfactor}. and \var{factor} is the (floating-point) factor as per
\code{findfactor}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{findmax}{fragment\, length} \begin{funcdesc}{findmax}{fragment\, length}
This routine (which only accepts 2-byte sample fragments) searches Search \var{fragment} for a slice of length \var{length} samples (not
\var{fragment} for a slice of length \var{length} samples (not bytes!)\ bytes!)\ with maximum energy, i.e., return \var{i} for which
with maximum energy, i.e.\ it returns \var{i} for which \code{rms(fragment[i*2:(i+length)*2])} is maximal. The fragments
\code{rms(fragment[i*2:(i+length)*2])} is maximal. should both contain 2-byte samples.
The routine takes time proportional to \code{len(fragment)}. The routine takes time proportional to \code{len(fragment)}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{getsample}{fragment\, width\, index} \begin{funcdesc}{getsample}{fragment\, width\, index}
This function returns the value of sample \var{index} from the Return the value of sample \var{index} from the fragment.
fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{lin2lin}{fragment\, width\, newwidth} \begin{funcdesc}{lin2lin}{fragment\, width\, newwidth}
This function converts samples between 1-, 2- and 4-byte formats. Convert samples between 1-, 2- and 4-byte formats.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{lin2adpcm}{fragment\, width\, state} \begin{funcdesc}{lin2adpcm}{fragment\, width\, state}
This function converts samples to 4 bit Intel/DVI ADPCM encoding. Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an
ADPCM coding is an adaptive coding scheme, whereby each 4 bit number adaptive coding scheme, whereby each 4 bit number is the difference
is the difference between one sample and the next, divided by a between one sample and the next, divided by a (varying) step. The
(varying) step. The Intel/DVI ADPCM algorithm has been selected for Intel/DVI ADPCM algorithm has been selected for use by the IMA, so it
use by the IMA, so it may well become a standard. may well become a standard.
\code{State} is a tuple containing the state of the coder. The coder \code{State} is a tuple containing the state of the coder. The coder
returns a tuple \code{(\var{adpcmfrag}, \var{newstate})}, and the returns a tuple \code{(\var{adpcmfrag}, \var{newstate})}, and the
\var{newstate} should be passed to the next call of lin2adpcm. In 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 initial call \code{None} can be passed as the state. \var{adpcmfrag}
the ADPCM coded fragment packed 2 4-bit values per byte. is the ADPCM coded fragment packed 2 4-bit values per byte.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{lin2adpcm3}{fragment\, width\, state} \begin{funcdesc}{lin2adpcm3}{fragment\, width\, state}
@ -119,24 +120,24 @@ discouraged.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{lin2ulaw}{fragment\, width} \begin{funcdesc}{lin2ulaw}{fragment\, width}
This function converts samples in the audio fragment to U-LAW encoding Convert samples in the audio fragment to U-LAW encoding and return
and returns this as a Python string. U-LAW is an audio encoding format this as a Python string. U-LAW is an audio encoding format whereby
whereby you get a dynamic range of about 14 bits using only 8 bit you get a dynamic range of about 14 bits using only 8 bit samples. It
samples. It is used by the Sun audio hardware, among others. is used by the Sun audio hardware, among others.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{minmax}{fragment\, width} \begin{funcdesc}{minmax}{fragment\, width}
This function returns a tuple consisting of the minimum and maximum Return a tuple consisting of the minimum and maximum values of all
values of all samples in the sound fragment. samples in the sound fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{max}{fragment\, width} \begin{funcdesc}{max}{fragment\, width}
This function returns the maximum of the {\em absolute value} of all Return the maximum of the {\em absolute value} of all samples in a
samples in a fragment. fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{maxpp}{fragment\, width} \begin{funcdesc}{maxpp}{fragment\, width}
This function returns the maximum peak-peak value in the sound fragment. Return the maximum peak-peak value in the sound fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{mul}{fragment\, width\, factor} \begin{funcdesc}{mul}{fragment\, width\, factor}
@ -146,12 +147,11 @@ silently ignored.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{reverse}{fragment\, width} \begin{funcdesc}{reverse}{fragment\, width}
This function reverses the samples in a fragment and returns the Reverse the samples in a fragment and returns the modified fragment.
modified fragment.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{rms}{fragment\, width\, factor} \begin{funcdesc}{rms}{fragment\, width}
Returns the root-mean-square of the fragment, i.e. Return the root-mean-square of the fragment, i.e.
\iftexi \iftexi
the square root of the quotient of the sum of all squared sample value, the square root of the quotient of the sum of all squared sample value,
divided by the sumber of samples. divided by the sumber of samples.
@ -166,22 +166,22 @@ This is a measure of the power in an audio signal.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{tomono}{fragment\, width\, lfactor\, rfactor} \begin{funcdesc}{tomono}{fragment\, width\, lfactor\, rfactor}
This function converts a stereo fragment to a mono fragment. The left Convert a stereo fragment to a mono fragment. The left channel is
channel is multiplied by \var{lfactor} and the right channel by multiplied by \var{lfactor} and the right channel by \var{rfactor}
\var{rfactor} before adding the two channels to give a mono signal. before adding the two channels to give a mono signal.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{tostereo}{fragment\, width\, lfactor\, rfactor} \begin{funcdesc}{tostereo}{fragment\, width\, lfactor\, rfactor}
This function generates a stereo fragment from a mono fragment. Each Generate a stereo fragment from a mono fragment. Each pair of samples
pair of samples in the stereo fragment are computed from the mono in the stereo fragment are computed from the mono sample, whereby left
sample, whereby left channel samples are multiplied by \var{lfactor} channel samples are multiplied by \var{lfactor} and right channel
and right channel samples by \var{rfactor}. samples by \var{rfactor}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{ulaw2lin}{fragment\, width} \begin{funcdesc}{ulaw2lin}{fragment\, width}
This function converts sound fragments in ULAW encoding to linearly Convert sound fragments in ULAW encoding to linearly encoded sound
encoded sound fragments. ULAW encoding always uses 8 bits samples, so fragments. ULAW encoding always uses 8 bits samples, so \var{width}
\var{width} refers only to the sample width of the output fragment here. refers only to the sample width of the output fragment here.
\end{funcdesc} \end{funcdesc}
Note that operations such as \code{mul} or \code{max} make no Note that operations such as \code{mul} or \code{max} make no
@ -215,7 +215,7 @@ standards in which case they will not be interoperable with the
respective standards. respective standards.
The \code{find...} routines might look a bit funny at first sight. The \code{find...} routines might look a bit funny at first sight.
They are primarily meant for doing echo cancellation. A reasonably They are primarily meant to do echo cancellation. A reasonably
fast way to do this is to pick the most energetic piece of the output 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, locate that in the input sample and subtract the whole output
sample from the input sample: sample from the input sample:

View File

@ -1,6 +1,7 @@
\section{Built-in Module \sectcode{__builtin__}} \section{Built-in Module \sectcode{__builtin__}}
\bimodindex{__builtin__} \bimodindex{__builtin__}
This module provides direct access to all `built-in' identifier of 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 Python; e.g. \code{__builtin__.open} is the full name for the built-in
function \code{open}. function \code{open}. See the section on Built-in Functions in the
previous chapter.

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{cgi}} \section{Standard Module \sectcode{cgi}}
\stmodindex{cgi} \stmodindex{cgi}
\indexii{WWW}{server} \indexii{WWW}{server}
\indexii{CGI}{protocol} \indexii{CGI}{protocol}
@ -134,3 +134,85 @@ The module defines the following variable:
The shell environment, exactly as received from the http server. See The shell environment, exactly as received from the http server. See
the CGI documentation for a description of the various fields. the CGI documentation for a description of the various fields.
\end{datadesc} \end{datadesc}
\subsection{Example}
This example assumes that you have a WWW server up and running,
e.g.\ NCSA's \code{httpd}.
Place the following file in a convenient spot in the WWW server's
directory tree. E.g., if you place it in the subdirectory \file{test}
of the root directory and call it \file{test.html}, its URL will be
\file{http://\var{yourservername}/test/test.html}.
\begin{verbatim}
<TITLE>Test Form Input</TITLE>
<H1>Test Form Input</H1>
<FORM METHOD="POST" ACTION="/cgi-bin/test.py">
<INPUT NAME=Name> (Name)<br>
<INPUT NAME=Address> (Address)<br>
<INPUT TYPE=SUBMIT>
</FORM>
\end{verbatim}
Selecting this file's URL from a forms-capable browser such as Mosaic
or Netscape will bring up a simple form with two text input fields and
a ``submit'' button.
But wait. Before pressing ``submit'', a script that responds to the
form must also be installed. The test file as shown assumes that the
script is called \file{test.py} and lives in the server's
\code{cgi-bin} directory. Here's the test script:
\begin{verbatim}
#!/usr/local/bin/python
import cgi
print "Content-type: text/html"
print # End of headers!
print "<TITLE>Test Form Output</TITLE>"
print "<H1>Test Form Output</H1>"
form = cgi.SvFormContentDict() # Load the form
name = addr = None # Default: no name and address
# Extract name and address from the form, if given
if form.has_key('Name'):
name = form['Name']
if form.has_key('Address'):
addr = form['Address']
# Print an unnumbered list of the name and address, if present
print "<UL>"
if name is not None:
print "<LI>Name:", cgi.escape(name)
if addr is not None:
print "<LI>Address:", cgi.escape(addr)
print "</UL>"
\end{verbatim}
The script should be made executable (\samp{chmod +x \var{script}}).
If the Python interpreter is not located at
\file{/usr/local/bin/python} but somewhere else, the first line of the
script should be modified accordingly.
Now that everything is installed correctly, we can try out the form.
Bring up the test form in your WWW browser, fill in a name and address
in the form, and press the ``submit'' button. The script should now
run and its output is sent back to your browser. This should roughly
look as follows:
\strong{Test Form Output}
\begin{itemize}
\item Name: \var{the name you entered}
\item Address: \var{the address you entered}
\end{itemize}
If you didn't enter a name or address, the corresponding line will be
missing (since the browser doesn't send empty form fields to the
server).

View File

@ -1,5 +1,6 @@
\section{Built-in module \sectcode{copy}} \section{Standard Module \sectcode{copy}}
\stmodindex{copy} \stmodindex{copy}
\renewcommand{\indexsubitem}{(copy function)}
\ttindex{copy} \ttindex{copy}
\ttindex{deepcopy} \ttindex{deepcopy}
@ -14,7 +15,7 @@ x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y x = copy.deepcopy(y) # make a deep copy of y
\end{verbatim} \end{verbatim}
For module specific errors, \code{copy.Error} is raised. For module specific errors, \code{copy.error} is raised.
The difference between shallow and deep copying is only relevant for The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or compound objects (objects that contain other objects, like lists or
@ -74,6 +75,7 @@ to control pickling: they can define methods called
\code{__setstate__()}. See the description of module \code{pickle} \code{__setstate__()}. See the description of module \code{pickle}
for information on these methods. for information on these methods.
\stmodindex{pickle} \stmodindex{pickle}
\renewcommand{\indexsubitem}{(copy protocol)}
\ttindex{__getinitargs__} \ttindex{__getinitargs__}
\ttindex{__getstate__} \ttindex{__getstate__}
\ttindex{__setstate__} \ttindex{__setstate__}

View File

@ -5,8 +5,13 @@ a cryptographic nature. They are available at the discretion of the
installation. installation.
\index{cryptography} \index{cryptography}
%Hardcore cypherpunks will probably find the Python Cryptography Kit of Hardcore cypherpunks will probably find the Python Cryptography Kit of
%further interest; the package adds built-in modules for DES and IDEA further interest; the package adds built-in modules for DES and IDEA
%encryption, and provides a Python module for reading and decrypting PGP files. encryption, and provides a Python module for reading and decrypting
%\index{PGP}\indexii{DES}{cipher}\indexii{IDEA}{cipher} PGP files. The Python Cryptography Kit is not distributed with Python
%\index{Python Cryptography Kit} but available separately. See the URL
\file{http://www.cs.mcgill.ca/\%7Efnord/crypt.html} for more information.
\index{PGP}
\indexii{DES}{cipher}
\indexii{IDEA}{cipher}
\index{Python Cryptography Kit}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{ctb}} \section{Built-in Module \sectcode{ctb}}
\bimodindex{ctb} \bimodindex{ctb}
\renewcommand{\indexsubitem}{(in module ctb)} \renewcommand{\indexsubitem}{(in module ctb)}
@ -44,7 +44,7 @@ Alternatively, passing \code{None} will result in default buffer sizes.
For all connection methods that take a \var{timeout} argument, a value For all connection methods that take a \var{timeout} argument, a value
of \code{-1} is indefinite, meaning that the command runs to completion. of \code{-1} is indefinite, meaning that the command runs to completion.
\renewcommand{\indexsubitem}{(connection object method)} \renewcommand{\indexsubitem}{(connection object attribute)}
\begin{datadesc}{callback} \begin{datadesc}{callback}
If this member is set to a value other than \code{None} it should point If this member is set to a value other than \code{None} it should point
@ -59,6 +59,8 @@ calls for the time being.
\end{datadesc} \end{datadesc}
\renewcommand{\indexsubitem}{(connection object method)}
\begin{funcdesc}{Open}{timeout} \begin{funcdesc}{Open}{timeout}
Open an outgoing connection, waiting at most \var{timeout} seconds for Open an outgoing connection, waiting at most \var{timeout} seconds for
the connection to be established. the connection to be established.

View File

@ -24,7 +24,7 @@ inappropriate error.
\begin{excdesc}{AttributeError} \begin{excdesc}{AttributeError}
% xref to attribute reference? % xref to attribute reference?
Raised when an attribute reference or assignment fails. (When an Raised when an attribute reference or assignment fails. (When an
object does not support attributes references or attribute assignments object does not support attribute references or attribute assignments
at all, \code{TypeError} is raised.) at all, \code{TypeError} is raised.)
\end{excdesc} \end{excdesc}

View File

@ -1,5 +1,5 @@
% Manual text by Jaap Vermeulen % Manual text by Jaap Vermeulen
\section{Built-in module \sectcode{fcntl}} \section{Built-in Module \sectcode{fcntl}}
\bimodindex{fcntl} \bimodindex{fcntl}
\indexii{\UNIX{}}{file control} \indexii{\UNIX{}}{file control}
\indexii{\UNIX{}}{I/O control} \indexii{\UNIX{}}{I/O control}

View File

@ -2,17 +2,18 @@
\bimodindex{fl} \bimodindex{fl}
This module provides an interface to the FORMS Library by Mark This module provides an interface to the FORMS Library by Mark
Overmars, version 2.0b. For more info about FORMS, write to Overmars. The source for the library can be retrieved by anonymous
{\tt markov@cs.ruu.nl}. ftp from host \samp{ftp.cs.ruu.nl}, directory \file{SGI/FORMS}. It
was last tested with version 2.0b.
Most functions are literal translations of their C equivalents, Most functions are literal translations of their C equivalents,
dropping the initial \samp{fl_} from their name. Constants used by the dropping the initial \samp{fl_} from their name. Constants used by
library are defined in module \code{FL} described below. the library are defined in module \code{FL} described below.
The creation of objects is a little different in Python than in C: 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 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 FORMS objects are added, all functions that add a FORMS object to a
button are methods of the Python object representing the form. form are methods of the Python object representing the form.
Consequently, there are no Python equivalents for the C functions 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_addto_form} and \code{fl_end_form}, and the equivalent of
\code{fl_bgn_form} is called \code{fl.make_form}. \code{fl_bgn_form} is called \code{fl.make_form}.
@ -26,13 +27,13 @@ Hopefully this isn't too confusing...
There are no `free objects' in the Python interface to FORMS, nor is 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 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 interface to GL event handling is available, though, so you can mix
FORMS with pure GL windows. FORMS with pure GL windows.
\strong{Please note:} importing \code{fl} implies a call to the GL function \strong{Please note:} importing \code{fl} implies a call to the GL function
\code{foreground()} and to the FORMS routine \code{fl_init()}. \code{foreground()} and to the FORMS routine \code{fl_init()}.
\subsection{Functions defined in module \sectcode{fl}} \subsection{Functions Defined in Module \sectcode{fl}}
Module \code{fl} defines the following functions. For more information Module \code{fl} defines the following functions. For more information
about what they do, see the description of the equivalent C function about what they do, see the description of the equivalent C function
@ -92,7 +93,7 @@ input string. It returns the string value as edited by the user.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{show_file_selector}{message\, directory\, pattern\, default} \begin{funcdesc}{show_file_selector}{message\, directory\, pattern\, default}
Show a dialog box inm which the user can select a file. It returns Show a dialog box in which the user can select a file. It returns
the absolute filename selected by the user, or \code{None} if the user the absolute filename selected by the user, or \code{None} if the user
presses Cancel. presses Cancel.
\end{funcdesc} \end{funcdesc}
@ -130,7 +131,7 @@ See the description in the FORMS documentation of \code{fl_color},
\code{fl_mapcolor} and \code{fl_getmcolor}. \code{fl_mapcolor} and \code{fl_getmcolor}.
\end{funcdesc} \end{funcdesc}
\subsection{Form object methods and data attributes} \subsection{Form Objects}
Form objects (returned by \code{fl.make_form()} above) have the Form objects (returned by \code{fl.make_form()} above) have the
following methods. Each method corresponds to a C function whose name following methods. Each method corresponds to a C function whose name
@ -382,7 +383,7 @@ documentation:
\lineiii{doublebuf}{int}{nonzero if double buffering on} \lineiii{doublebuf}{int}{nonzero if double buffering on}
\end{tableiii} \end{tableiii}
\subsection{FORMS object methods and data attributes} \subsection{FORMS Objects}
Besides methods specific to particular kinds of FORMS objects, all Besides methods specific to particular kinds of FORMS objects, all
FORMS objects also have the following methods: FORMS objects also have the following methods:

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{ftplib}} \section{Standard Module \sectcode{ftplib}}
\stmodindex{ftplib} \stmodindex{ftplib}
\renewcommand{\indexsubitem}{(in module ftplib)} \renewcommand{\indexsubitem}{(in module ftplib)}

View File

@ -92,8 +92,8 @@ exactly one argument.)
\var{expression} argument is parsed and evaluated as a Python \var{expression} argument is parsed and evaluated as a Python
expression (technically speaking, a condition list) using the expression (technically speaking, a condition list) using the
\var{globals} and \var{locals} dictionaries as global and local name \var{globals} and \var{locals} dictionaries as global and local name
space. If the \var{globals} dictionary is omitted it defaults to space. If the \var{locals} dictionary is omitted it defaults to
the \var{locals} dictionary. If both dictionaries are omitted, the the \var{globals} dictionary. If both dictionaries are omitted, the
expression is executed in the environment where \code{eval} is expression is executed in the environment where \code{eval} is
called. The return value is the result of the evaluated expression. called. The return value is the result of the evaluated expression.
Syntax errors are reported as exceptions. Example: Syntax errors are reported as exceptions. Example:
@ -119,20 +119,21 @@ exactly one argument.)
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{execfile}{file\optional{\, globals\optional{\, locals}}} \begin{funcdesc}{execfile}{file\optional{\, globals\optional{\, locals}}}
This function is similar to the \code{eval()} function or the This function is similar to the
\code{exec} statement, but parses a file instead of a string. It is \code{exec} statement, but parses a file instead of a string. It is
different from the \code{import} statement in that it does not use different from the \code{import} statement in that it does not use
the module administration --- it reads the file unconditionally and the module administration --- it reads the file unconditionally and
does not create a new module. does not create a new module.\footnote{It is used relatively rarely
so does not warrant being made into a statement.}
The arguments are a file name and two optional dictionaries. The The arguments are a file name and two optional dictionaries. The
file is parsed and evaluated as a sequence of Python statements file is parsed and evaluated as a sequence of Python statements
(similarly to a module) using the \var{globals} and \var{locals} (similarly to a module) using the \var{globals} and \var{locals}
dictionaries as global and local name space. If the \var{globals} dictionaries as global and local name space. If the \var{locals}
dictionary is omitted it defaults to the \var{locals} dictionary. dictionary is omitted it defaults to the \var{globals} dictionary.
If both dictionaries are omitted, the expression is executed in the If both dictionaries are omitted, the expression is executed in the
environment where \code{execfile} is called. The return value is environment where \code{execfile()} is called. The return value is
None. \code{None}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{filter}{function\, list} \begin{funcdesc}{filter}{function\, list}
@ -173,8 +174,8 @@ removed.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{hex}{x} \begin{funcdesc}{hex}{x}
Convert a number to a hexadecimal string. The result is a valid Convert an integer number (of any size) to a hexadecimal string.
Python expression. The result is a valid Python expression.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{id}{object} \begin{funcdesc}{id}{object}
@ -194,7 +195,9 @@ removed.
\begin{funcdesc}{int}{x} \begin{funcdesc}{int}{x}
Convert a number to a plain integer. The argument may be a plain or Convert a number to a plain integer. The argument may be a plain or
long integer or a floating point number. long integer or a floating point number. Conversion of floating
point numbers to integers is defined by the C semantics; normally
the conversion truncates towards zero.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{len}{s} \begin{funcdesc}{len}{s}
@ -231,8 +234,8 @@ any kind of sequence; the result is always a list.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{oct}{x} \begin{funcdesc}{oct}{x}
Convert a number to an octal string. The result is a valid Python Convert an integer number (of any size) to an octal string. The
expression. result is a valid Python expression.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}} \begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}}
@ -290,7 +293,8 @@ there's no reliable way to determine whether this is the case.}
the last element is the largest \code{\var{start} + \var{i} * the last element is the largest \code{\var{start} + \var{i} *
\var{step}} less than \var{end}; if \var{step} is negative, the last \var{step}} less than \var{end}; if \var{step} is negative, the last
element is the largest \code{\var{start} + \var{i} * \var{step}} element is the largest \code{\var{start} + \var{i} * \var{step}}
greater than \var{end}. \var{step} must not be zero. Example: greater than \var{end}. \var{step} must not be zero (or else an
exception is raised). Example:
\bcode\begin{verbatim} \bcode\begin{verbatim}
>>> range(10) >>> range(10)
@ -321,7 +325,7 @@ there's no reliable way to determine whether this is the case.}
>>> s = raw_input('--> ') >>> s = raw_input('--> ')
--> Monty Python's Flying Circus --> Monty Python's Flying Circus
>>> s >>> s
'Monty Python\'s Flying Circus' "Monty Python's Flying Circus"
>>> >>>
\end{verbatim}\ecode \end{verbatim}\ecode
\end{funcdesc} \end{funcdesc}
@ -341,13 +345,44 @@ sequence.
argument must be a module object, so it must have been successfully argument must be a module object, so it must have been successfully
imported before. This is useful if you have edited the module source 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 file using an external editor and want to try out the new version
without leaving the Python interpreter. Note that if a module is without leaving the Python interpreter. The return value is the
syntactically correct but its initialization fails, the first module object (i.e.\ the same as the \var{module} argument).
\code{import} statement for it does not import the name, but does
create a (partially initialized) module object; to reload the module There are a number of caveats:
you must first \code{import} it again (this will just make the
partially initialized module object available) before you can If a module is syntactically correct but its initialization fails, the
\code{reload()} it. first \code{import} statement for it does not bind its name locally,
but does store a (partially initialized) module object in
\code{sys.modules}. To reload the module you must first
\code{import} it again (this will bind the name to the partially
initialized module object) before you can \code{reload()} it.
When a module is reloaded, its dictionary (containing the module's
global variables) is retained. Redefinitions of names will override
the old definitions, so this is generally not a problem. If the new
version of a module does not define a name that was defined by the old
version, the old definition remains. This feature can be used to the
module's advantage if it maintains a global table or cache of objects
--- with a \code{try} statement it can test for the table's presence
and skip its initialization if desired.
It is legal though generally not very useful to reload built-in or
dynamically loaded modules, except for \code{sys}, \code{__main__} and
\code{__builtin__}. In certain cases, however, extension modules are
not designed to be initialized more than once, and may fail in
arbitrary ways when reloaded.
If a module imports objects from another module using \code{from}
{\ldots} \code{import} {\ldots}, calling \code{reload()} for the other
module does not redefine the objects imported from it --- one way
around this is to re-execute the \code{from} statement, another is to
use \code{import} and qualified names (\var{module}.\var{name})
instead.
If a module instantiates instances of a class, reloading the module
that defines the class does not affect the method definitions of the
instances --- they continue to use the old class definition. The same
is true for derived classes.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{repr}{object} \begin{funcdesc}{repr}{object}
@ -385,23 +420,25 @@ always attempt to return a string that is acceptable to \code{eval()};
its goal is to return a printable string. its goal is to return a printable string.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{tuple}{object} \begin{funcdesc}{tuple}{sequence}
Return a tuple whose items are the same and in the same order as Return a tuple whose items are the same and in the same order as
\var{object}'s items. If \var{object} is alread a tuple, it \var{sequence}'s items. If \var{sequence} is alread a tuple, it
is returned unchanged. For instance, \code{tuple('abc')} returns is returned unchanged. For instance, \code{tuple('abc')} returns
returns \code{('a', 'b', 'c')} and \code{tuple([1, 2, 3])} returns returns \code{('a', 'b', 'c')} and \code{tuple([1, 2, 3])} returns
\code{(1, 2, 3)}. \code{(1, 2, 3)}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{type}{object} \begin{funcdesc}{type}{object}
% XXXJH xref to buil-in objects here?
Return the type of an \var{object}. The return value is a type 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 object. The standard module \code{types} defines names for all
them to other type objects; e.g., the following checks if a variable built-in types.
is a string: \stmodindex{types}
\obindex{type}
For instance:
\bcode\begin{verbatim} \bcode\begin{verbatim}
>>> if type(x) == type(''): print 'It is a string' >>> import types
>>> if type(x) == types.StringType: print "It's a string"
\end{verbatim}\ecode \end{verbatim}\ecode
\end{funcdesc} \end{funcdesc}
@ -424,7 +461,7 @@ which yields the same values as the corresponding list, without
actually storing them all simultaneously. The advantage of actually storing them all simultaneously. The advantage of
\code{xrange()} over \code{range()} is minimal (since \code{xrange()} \code{xrange()} over \code{range()} is minimal (since \code{xrange()}
still has to create the values when asked for them) except when a very still has to create the values when asked for them) except when a very
large range is used on a memory-starved machine (e.g. DOS) or when all large range is used on a memory-starved machine (e.g. MS-DOS) or when all
of the range's elements are never used (e.g. when the loop is usually of the range's elements are never used (e.g. when the loop is usually
terminated with \code{break}). terminated with \code{break}).
\end{funcdesc} \end{funcdesc}

View File

@ -5,7 +5,8 @@ This module helps scripts to parse the command line arguments in
\code{sys.argv}. \code{sys.argv}.
It uses the same conventions as the \UNIX{} It uses the same conventions as the \UNIX{}
\code{getopt()} \code{getopt()}
function. function (including the special meanings of arguments of the form
\samp{-} and \samp{--}).
It defines the function It defines the function
\code{getopt.getopt(args, options)} \code{getopt.getopt(args, options)}
and the exception and the exception

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{gopherlib}} \section{Standard Module \sectcode{gopherlib}}
\stmodindex{gopherlib} \stmodindex{gopherlib}
\renewcommand{\indexsubitem}{(in module gopherlib)} \renewcommand{\indexsubitem}{(in module gopherlib)}

View File

@ -13,7 +13,7 @@ following items from the group database (see \file{<grp.h>}), in order:
The gid is an integer, name and password are strings, and the member The gid is an integer, name and password are strings, and the member
list is a list of strings. list is a list of strings.
(Note that most users are not explicitly listed as members of the (Note that most users are not explicitly listed as members of the
group(s) they are in.) group they are in according to the password database.)
An exception is raised if the entry asked for cannot be found. An exception is raised if the entry asked for cannot be found.
It defines the following items: It defines the following items:

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{htmllib}} \section{Standard Module \sectcode{htmllib}}
\stmodindex{htmllib} \stmodindex{htmllib}
\index{HTML} \index{HTML}
\index{hypertext} \index{hypertext}
@ -27,12 +27,14 @@ The following is a summary of the interface defined by
\item \item
The interface to feed data to an instance is through the \code{feed()} The interface to feed data to an instance is through the \code{feed()}
method, which takes a string argument. This can be called with as method, which takes a string argument. This can be called with as
little or as much text at a time as desired. When the data contains complete little or as much text at a time as desired;
\code{p.feed(a); p.feed(b)} has the same effect as \code{p.feed(a+b)}.
When the data contains complete
HTML elements, these are processed immediately; incomplete elements HTML elements, these are processed immediately; incomplete elements
are saved in a buffer. To force processing of all unprocessed data, are saved in a buffer. To force processing of all unprocessed data,
call the \code{close()} method. call the \code{close()} method.
Example: to parse the entire contents of a file, do Example: to parse the entire contents of a file, do\\
\code{parser.feed(open(file).read()); parser.close()}. \code{parser.feed(open(file).read()); parser.close()}.
\item \item
@ -142,7 +144,7 @@ sheets are:
\index{style sheet} \index{style sheet}
\begin{datadesc}{NullStylesheet} \begin{datadesc}{NullStylesheet}
A style sheet for use on a dumb output device such as an ASCII A style sheet for use on a dumb output device such as an \ASCII{}
terminal. terminal.
\end{datadesc} \end{datadesc}
@ -242,9 +244,9 @@ spaces.
\end{funcdesc} \end{funcdesc}
\begin{datadesc}{nospace} \begin{datadesc}{nospace}
If this instance variable is true, empty words are ignored by If this instance variable is true, empty words should be ignored by
\code{addword}. It is set to false after a non-empty word has been \code{addword}. It should be set to false after a non-empty word has
added. been added.
\end{datadesc} \end{datadesc}
\begin{funcdesc}{setjust}{justification} \begin{funcdesc}{setjust}{justification}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{httplib}} \section{Standard Module \sectcode{httplib}}
\stmodindex{httplib} \stmodindex{httplib}
\index{HTTP} \index{HTTP}
@ -15,7 +15,15 @@ instantiated passing it a host and optional port number. If no port
number is passed, the port is extracted from the host string if it has number is passed, the port is extracted from the host string if it has
the form \code{host:port}, else the default HTTP port (80) is used. the form \code{host:port}, else the default HTTP port (80) is used.
If no host is passed, no connection is made, and the \code{connect} If no host is passed, no connection is made, and the \code{connect}
method should be used to connect to a server. method should be used to connect to a server. For example, the
following calls all create instances that connect to the server at the
same host and port:
\begin{verbatim}
>>> h1 = httplib.HTTP('www.cwi.nl')
>>> h2 = httplib.HTTP('www.cwi.nl:80')
>>> h3 = httplib.HTTP('www.cwi.nl', 80)
\end{verbatim}
Once an \code{HTTP} instance has been connected to an HTTP server, it Once an \code{HTTP} instance has been connected to an HTTP server, it
should be used as follows: should be used as follows:
@ -27,7 +35,7 @@ should be used as follows:
\item[2.] Make zero or more calls to the \code{putheader()} method. \item[2.] Make zero or more calls to the \code{putheader()} method.
\item[3.] Call the \code{endheaders()} method (this can be omitted if \item[3.] Call the \code{endheaders()} method (this can be omitted if
step 4. makes no calls). step 4 makes no calls).
\item[4.] Optional calls to the \code{send()} method. \item[4.] Optional calls to the \code{send()} method.
@ -93,3 +101,22 @@ Return a file object from which the data returned by the server can be
read, using the \code{read()}, \code{readline()} or \code{readlines()} read, using the \code{read()}, \code{readline()} or \code{readlines()}
methods. methods.
\end{funcdesc} \end{funcdesc}
\subsection{Example}
Here is an example session:
\begin{verbatim}
>>> import httplib
>>> h = httplib.HTTP('www.cwi.nl')
>>> h.putrequest('GET', '/index.html')
>>> h.putheader('Accept', 'text/html')
>>> h.putheader('Accept', 'text/plain')
>>> h.endheaders()
>>> errcode, errmsg, headers = h.getreply()
>>> print errcode # Should be 200
>>> f = h.getfile()
>>> data f.read() # Get the raw HTML
>>> f.close()
>>>
\end{verbatim}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{imageop}} \section{Built-in Module \sectcode{imageop}}
\bimodindex{imageop} \bimodindex{imageop}
The \code{imageop} module contains some useful operations on images. The \code{imageop} module contains some useful operations on images.
@ -17,49 +17,48 @@ per pixel, etc.
\begin{funcdesc}{crop}{image\, psize\, width\, height\, x0\, y0\, x1\, y1} \begin{funcdesc}{crop}{image\, psize\, width\, height\, x0\, y0\, x1\, y1}
This function takes the image in \var{image}, which should by Return the selected part of \var{image}, which should by
\var{width} by \var{height} in size and consist of pixels of \var{width} by \var{height} in size and consist of pixels of
\var{psize} bytes, and returns the selected part of that image. \var{x0}, \var{psize} bytes. \var{x0}, \var{y0}, \var{x1} and \var{y1} are like
\var{y0}, \var{x1} and \var{y1} are like the \code{lrectread} the \code{lrectread} parameters, i.e.\ the boundary is included in the
parameters, i.e. the boundary is included in the new image. new image. The new boundaries need not be inside the picture. Pixels
The new boundaries need not be inside the picture. Pixels that fall that fall outside the old image will have their value set to zero. If
outside the old image will have their value set to zero. \var{x0} is bigger than \var{x1} the new image is mirrored. The same
If \var{x0} is bigger than \var{x1} the new image is mirrored. The holds for the y coordinates.
same holds for the y coordinates.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{scale}{image\, psize\, width\, height\, newwidth\, newheight} \begin{funcdesc}{scale}{image\, psize\, width\, height\, newwidth\, newheight}
This function returns an \var{image} scaled to size \var{newwidth} by Return \var{image} scaled to size \var{newwidth} by \var{newheight}.
\var{newheight}. No interpolation is done, scaling is done by No interpolation is done, scaling is done by simple-minded pixel
simple-minded pixel duplication or removal. Therefore, computer-generated duplication or removal. Therefore, computer-generated images or
images or dithered images will not look nice after scaling. dithered images will not look nice after scaling.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{tovideo}{image\, psize\, width\, height} \begin{funcdesc}{tovideo}{image\, psize\, width\, height}
This function runs a vertical low-pass filter over an image. It does Run a vertical low-pass filter over an image. It does so by computing
so by computing each destination pixel as the average of two each destination pixel as the average of two vertically-aligned source
vertically-aligned source pixels. The main use of this routine is to pixels. The main use of this routine is to forestall excessive
forestall excessive flicker if the image is displayed on a video flicker if the image is displayed on a video device that uses
device that uses interlacing, hence the name. interlacing, hence the name.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{grey2mono}{image\, width\, height\, threshold} \begin{funcdesc}{grey2mono}{image\, width\, height\, threshold}
This function converts a 8-bit deep greyscale image to a 1-bit deep Convert a 8-bit deep greyscale image to a 1-bit deep image by
image by tresholding all the pixels. The resulting image is tightly tresholding all the pixels. The resulting image is tightly packed and
packed and is probably only useful as an argument to \code{mono2grey}. is probably only useful as an argument to \code{mono2grey}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{dither2mono}{image\, width\, height} \begin{funcdesc}{dither2mono}{image\, width\, height}
This function also converts an 8-bit greyscale image to a 1-bit Convert an 8-bit greyscale image to a 1-bit monochrome image using a
monochrome image but it uses a (simple-minded) dithering algorithm. (simple-minded) dithering algorithm.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{mono2grey}{image\, width\, height\, p0\, p1} \begin{funcdesc}{mono2grey}{image\, width\, height\, p0\, p1}
This function converts a 1-bit monochrome image to an 8 bit greyscale Convert a 1-bit monochrome image to an 8 bit greyscale or color image.
or color image. All pixels that are zero-valued on input get value All pixels that are zero-valued on input get value \var{p0} on output
\var{p0} on output and all one-value input pixels get value \var{p1} and all one-value input pixels get value \var{p1} on output. To
on output. To convert a monochrome black-and-white image to greyscale convert a monochrome black-and-white image to greyscale pass the
pass the values \code{0} and \code{255} respectively. values \code{0} and \code{255} respectively.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{grey2grey4}{image\, width\, height} \begin{funcdesc}{grey2grey4}{image\, width\, height}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{imgfile}} \section{Built-in Module \sectcode{imgfile}}
\bimodindex{imgfile} \bimodindex{imgfile}
The imgfile module allows python programs to access SGI imglib image The imgfile module allows python programs to access SGI imglib image

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{imp}} \section{Built-in Module \sectcode{imp}}
\bimodindex{imp} \bimodindex{imp}
\index{import} \index{import}
@ -9,7 +9,7 @@ functions:
\renewcommand{\indexsubitem}{(in module struct)} \renewcommand{\indexsubitem}{(in module struct)}
\begin{funcdesc}{get_magic}{} \begin{funcdesc}{get_magic}{}
Return the magic string used to recognize value byte-compiled code Return the magic string value used to recognize byte-compiled code
files (``\code{.pyc} files''). files (``\code{.pyc} files'').
\end{funcdesc} \end{funcdesc}
@ -22,15 +22,15 @@ string to pass to the built-in \code{open} function to open the file
(this can be \code{'r'} for text files or \code{'rb'} for binary (this can be \code{'r'} for text files or \code{'rb'} for binary
files), and \var{type} is the file type, which has one of the values files), and \var{type} is the file type, which has one of the values
\code{PY_SOURCE}, \code{PY_COMPILED} or \code{C_EXTENSION}, defined \code{PY_SOURCE}, \code{PY_COMPILED} or \code{C_EXTENSION}, defined
below. below. (System-dependent values may also be returned.)
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{find_module}{name\, \optional{path}} \begin{funcdesc}{find_module}{name\, \optional{path}}
Try to find the module \var{name} on the search path \var{path}. The Try to find the module \var{name} on the search path \var{path}. The
default \var{path} is \code{sys.path}. The return value is a triple default \var{path} is \code{sys.path}. The return value is a triple
\code{(\var{file}, \var{pathname}, \var{description})} where \code{(\var{file}, \var{pathname}, \var{description})} where
\var{file} is an open file object positioned at the beginning \var{file} is an open file object positioned at the beginning,
corresponding to the file found, \var{pathname} is the pathname of the \var{pathname} is the pathname of the
file found, and \var{description} is a triple as contained in the list file found, and \var{description} is a triple as contained in the list
returned by \code{get_suffixes} describing the kind of file found. returned by \code{get_suffixes} describing the kind of file found.
\end{funcdesc} \end{funcdesc}
@ -134,33 +134,27 @@ The following function emulates the default import statement:
\begin{verbatim} \begin{verbatim}
import imp import imp
from sys import modules import sys
def __import__(name, globals=None, locals=None, fromlist=None): def __import__(name, globals=None, locals=None, fromlist=None):
# Fast path: let's see if it's already in sys.modules. # Fast path: see if the module has already been imported.
# Two speed optimizations are worth mentioning: if sys.modules.has_key(name):
# - We use 'modules' instead of 'sys.modules'; this saves a return sys.modules[name]
# dictionary look-up per call.
# - It's also faster to use a try-except statement than
# to use modules.has_key(name) to check if it's there.
try:
return modules[name]
except KeyError:
pass
# See if it's a built-in module # If any of the following calls raises an exception,
# there's a problem we con't handle -- let the caller handle it.
# See if it's a built-in module.
m = imp.init_builtin(name) m = imp.init_builtin(name)
if m: if m:
return m return m
# See if it's a frozen module # See if it's a frozen module.
m = imp.init_frozen(name) m = imp.init_frozen(name)
if m: if m:
return m return m
# Search the default path (i.e. sys.path). # Search the default path (i.e. sys.path).
# If this raises an exception, the module is not found --
# let the caller handle the exception.
fp, pathname, (suffix, mode, type) = imp.find_module(name) fp, pathname, (suffix, mode, type) = imp.find_module(name)
# See what we got. # See what we got.
@ -170,7 +164,7 @@ def __import__(name, globals=None, locals=None, fromlist=None):
if type == imp.PY_SOURCE: if type == imp.PY_SOURCE:
return imp.load_source(name, pathname, fp) return imp.load_source(name, pathname, fp)
if type == imp.PY_COMPILED: if type == imp.PY_COMPILED:
return imp.load_source(name, pathname, fp) return imp.load_compiled(name, pathname, fp)
# Shouldn't get here at all. # Shouldn't get here at all.
raise ImportError, '%s: unknown module type (%d)' % (name, type) raise ImportError, '%s: unknown module type (%d)' % (name, type)

View File

@ -2,7 +2,7 @@
The modules in this chapter are available on the Apple Macintosh only. The modules in this chapter are available on the Apple Macintosh only.
\section{Built-in module \sectcode{mac}} \section{Built-in Module \sectcode{mac}}
\bimodindex{mac} \bimodindex{mac}
This module provides a subset of the operating system dependent This module provides a subset of the operating system dependent
@ -22,7 +22,7 @@ The following functions are available in this module:
\code{unlink}, \code{unlink},
as well as the exception \code{error}. as well as the exception \code{error}.
\section{Standard module \sectcode{macpath}} \section{Standard Module \sectcode{macpath}}
\stmodindex{macpath} \stmodindex{macpath}
This module provides a subset of the pathname manipulation functions This module provides a subset of the pathname manipulation functions

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{macconsole}} \section{Built-in Module \sectcode{macconsole}}
\bimodindex{macconsole} \bimodindex{macconsole}
\renewcommand{\indexsubitem}{(in module macconsole)} \renewcommand{\indexsubitem}{(in module macconsole)}
@ -62,7 +62,7 @@ If set non-zero, the window will wait for user action before closing.
\subsection{console window object} \subsection{console window object}
\renewcommand{\indexsubitem}{(console window method)} \renewcommand{\indexsubitem}{(console window attribute)}
\begin{datadesc}{file} \begin{datadesc}{file}
The file object corresponding to this console window. If the file is The file object corresponding to this console window. If the file is
@ -70,6 +70,8 @@ buffered, you should call \code{file.flush()} between \code{write()}
and \code{read()} calls. and \code{read()} calls.
\end{datadesc} \end{datadesc}
\renewcommand{\indexsubitem}{(console window method)}
\begin{funcdesc}{setmode}{mode} \begin{funcdesc}{setmode}{mode}
Set the input mode of the console to \var{C_ECHO}, etc. Set the input mode of the console to \var{C_ECHO}, etc.
\end{funcdesc} \end{funcdesc}

View File

@ -1,5 +1,5 @@
\section{Built-in module \sectcode{macdnr}} \section{Built-in Module \sectcode{macdnr}}
\bimodindex{macdnr} \bimodindex{macdnr}
This module provides an interface to the Macintosh Domain Name This module provides an interface to the Macintosh Domain Name
@ -75,6 +75,8 @@ Wait for the query to complete.
Return 1 if the query is complete. Return 1 if the query is complete.
\end{funcdesc} \end{funcdesc}
\renewcommand{\indexsubitem}{(dnr result object attribute)}
\begin{datadesc}{rtnCode} \begin{datadesc}{rtnCode}
The error code returned by the query. The error code returned by the query.
\end{datadesc} \end{datadesc}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{macfs}} \section{Built-in Module \sectcode{macfs}}
\bimodindex{macfs} \bimodindex{macfs}
\renewcommand{\indexsubitem}{(in module macfs)} \renewcommand{\indexsubitem}{(in module macfs)}
@ -18,11 +18,14 @@ Create an FSSpec object for the specified file.
\begin{funcdesc}{RawFSSpec}{data} \begin{funcdesc}{RawFSSpec}{data}
Create an FSSpec object given the raw data for the C structure for the Create an FSSpec object given the raw data for the C structure for the
FSSpec. FSSpec as a string. This is mainly useful if you have obtained an
FSSpec structure over a network.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{RawAlias}{data} \begin{funcdesc}{RawAlias}{data}
Create an Alias object given the raw data for the alias. Create an Alias object given the raw data for the C structure for the
alias as a string. This is mainly useful if you have obtained an
FSSpec structure over a network.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{ResolveAliasFile}{file} \begin{funcdesc}{ResolveAliasFile}{file}
@ -56,12 +59,13 @@ dialog. Return an FSSpec object and a success-indicator.
\subsection{FSSpec objects} \subsection{FSSpec objects}
\renewcommand{\indexsubitem}{(FSSpec object method)} \renewcommand{\indexsubitem}{(FSSpec object attribute)}
\begin{datadesc}{data} \begin{datadesc}{data}
The raw data from the FSSpec object, suitable for passing The raw data from the FSSpec object, suitable for passing
to other applications, for instance. to other applications, for instance.
\end{datadesc} \end{datadesc}
\renewcommand{\indexsubitem}{(FSSpec object method)}
\begin{funcdesc}{as_pathname}{} \begin{funcdesc}{as_pathname}{}
Return the full pathname of the file described by the FSSpec object. Return the full pathname of the file described by the FSSpec object.
\end{funcdesc} \end{funcdesc}
@ -91,12 +95,13 @@ Set the 4-char creator and type of the file.
\subsection{alias objects} \subsection{alias objects}
\renewcommand{\indexsubitem}{(alias object method)} \renewcommand{\indexsubitem}{(alias object attribute)}
\begin{datadesc}{data} \begin{datadesc}{data}
The raw data for the Alias record, suitable for storing in a resource The raw data for the Alias record, suitable for storing in a resource
or transmitting to other programs. or transmitting to other programs.
\end{datadesc} \end{datadesc}
\renewcommand{\indexsubitem}{(alias object method)}
\begin{funcdesc}{Resolve}{\optional{file}} \begin{funcdesc}{Resolve}{\optional{file}}
Resolve the alias. If the alias was created as a relative alias you Resolve the alias. If the alias was created as a relative alias you
should pass the file relative to which it is. Return the FSSpec for should pass the file relative to which it is. Return the FSSpec for

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{macspeech}} \section{Built-in Module \sectcode{macspeech}}
\bimodindex{macspeech} \bimodindex{macspeech}
\renewcommand{\indexsubitem}{(in module macspeech)} \renewcommand{\indexsubitem}{(in module macspeech)}

View File

@ -1,5 +1,6 @@
\section{Built-in module \sectcode{mactcp}} \section{Built-in Module \sectcode{mactcp}}
\bimodindex{mactcp} \bimodindex{mactcp}
\renewcommand{\indexsubitem}{(in module mactcp)} \renewcommand{\indexsubitem}{(in module mactcp)}
This module provides an interface to the Macintosh TCP/IP driver This module provides an interface to the Macintosh TCP/IP driver
@ -37,8 +38,9 @@ on this port). \var{port} is the UDP port number you want to receive
datagrams on, a value of zero will make MacTCP select a free port. datagrams on, a value of zero will make MacTCP select a free port.
\end{funcdesc} \end{funcdesc}
\subsection{TCP stream objects} \subsection{TCP Stream Objects}
\renewcommand{\indexsubitem}{(TCP stream method)}
\renewcommand{\indexsubitem}{(TCP stream attribute)}
\begin{datadesc}{asr} \begin{datadesc}{asr}
When set to a value different than \code{None} this should point to a When set to a value different than \code{None} this should point to a
@ -50,6 +52,8 @@ is a Python addition to the MacTCP semantics.
It is safe to do further calls from the \code{asr}. It is safe to do further calls from the \code{asr}.
\end{datadesc} \end{datadesc}
\renewcommand{\indexsubitem}{(TCP stream method)}
\begin{funcdesc}{PassiveOpen}{port} \begin{funcdesc}{PassiveOpen}{port}
Wait for an incoming connection on TCP port \var{port} (zero makes the Wait for an incoming connection on TCP port \var{port} (zero makes the
system pick a free port). The call returns immediately, and you should system pick a free port). The call returns immediately, and you should
@ -104,15 +108,17 @@ Forcibly close both sides of a connection, ignoring outstanding data.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{Status}{} \begin{funcdesc}{Status}{}
Return a TCP status object for this stream. Return a TCP status object for this stream giving the current status
(see below).
\end{funcdesc} \end{funcdesc}
\subsection{TCP status objects} \subsection{TCP Status Objects}
This object has no methods, only some members holding information on This object has no methods, only some members holding information on
the connection. A complete description of all fields in this objects the connection. A complete description of all fields in this objects
can be found in the Apple documentation. The most interesting ones are: can be found in the Apple documentation. The most interesting ones are:
\renewcommand{\indexsubitem}{(TCP status method)} \renewcommand{\indexsubitem}{(TCP status attribute)}
\begin{datadesc}{localHost} \begin{datadesc}{localHost}
\dataline{localPort} \dataline{localPort}
\dataline{remoteHost} \dataline{remoteHost}
@ -137,11 +143,11 @@ without blocking).
\subsection{UDP stream objects} \subsection{UDP Stream Objects}
Note that, unlike the name suggests, there is nothing stream-like Note that, unlike the name suggests, there is nothing stream-like
about UDP. about UDP.
\renewcommand{\indexsubitem}{(UDP stream method)} \renewcommand{\indexsubitem}{(UDP stream attribute)}
\begin{datadesc}{asr} \begin{datadesc}{asr}
The asynchronous service routine to be called on events such as The asynchronous service routine to be called on events such as
@ -153,9 +159,11 @@ single argument, the event code.
A read-only member giving the port number of this UDP stream. A read-only member giving the port number of this UDP stream.
\end{datadesc} \end{datadesc}
\renewcommand{\indexsubitem}{(UDP stream method)}
\begin{funcdesc}{Read}{timeout} \begin{funcdesc}{Read}{timeout}
Read a datagram, waiting at most \var{timeout} seconds ($-1$ is Read a datagram, waiting at most \var{timeout} seconds ($-1$ is
indefinite). Return the data. infinite). Return the data.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{Write}{host\, port\, buf} \begin{funcdesc}{Write}{host\, port\, buf}

View File

@ -4,9 +4,9 @@
This module contains functions that can read and write Python This module contains functions that can read and write Python
values in a binary format. The format is specific to Python, but values in a binary format. The format is specific to Python, but
independent of machine architecture issues (e.g., you can write a 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 Python value to a file on a PC, transport the file to a Sun, and read
it back there). Details of the format not explained here; read the it back there). Details of the format are undocumented on purpose;
source if you're interested.% it may change between Python versions (although it rarely does).%
\footnote{The name of this module stems from a bit of terminology used \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 by the designers of Modula-3 (amongst others), who use the term
``marshalling'' for shipping of data around in a self-contained form. ``marshalling'' for shipping of data around in a self-contained form.
@ -14,6 +14,14 @@ Strictly speaking, ``to marshal'' means to convert some data from
internal to external form (in an RPC buffer for instance) and internal to external form (in an RPC buffer for instance) and
``unmarshalling'' for the reverse process.} ``unmarshalling'' for the reverse process.}
This is not a general ``persistency'' module. For general persistency
and transfer of Python objects through RPC calls, see the modules
\code{pickle} and \code{shelve}. The \code{marshal} module exists
mainly to support reading and writing the ``pseudo-compiled'' code for
Python modules of \samp{.pyc} files.
\stmodindex{pickle}
\stmodindex{shelve}
\obindex{code}
Not all Python object types are supported; in general, only objects Not all Python object types are supported; in general, only objects
whose value is independent from a particular invocation of Python can whose value is independent from a particular invocation of Python can
@ -23,7 +31,22 @@ strings, tuples, lists, dictionaries, and code objects, where it
should be understood that tuples, lists and dictionaries are only should be understood that tuples, lists and dictionaries are only
supported as long as the values contained therein are themselves supported as long as the values contained therein are themselves
supported; and recursive lists and dictionaries should not be written supported; and recursive lists and dictionaries should not be written
(they will cause an infinite loop). (they will cause infinite loops).
{\bf Caveat:} On machines where C's \code{long int} type has more than
32 bits (such as the DEC Alpha or the HP Precision Architecture), it
is possible to create plain Python integers that are longer than 32
bits. Since the current \code{marshal} module uses 32 bits to
transfer plain Python integers, such values are silently truncated.
This particularly affects the use of very long integer literals in
Python modules --- these will be accepted by the parser on such
machines, but will be silently be truncated when the module is read
from the \code{.pyc} instead.%
\footnote{A solution would be to refuse such literals in the parser,
since they are inherently non-portable. Another solution would be to
let the \code{marshal} module raise an exception when an integer value
would be truncated. At least one of these solutions will be
implemented in a future version.}
There are functions that read/write files as well as functions There are functions that read/write files as well as functions
operating on strings. operating on strings.
@ -31,6 +54,7 @@ operating on strings.
The module defines these functions: The module defines these functions:
\renewcommand{\indexsubitem}{(in module marshal)} \renewcommand{\indexsubitem}{(in module marshal)}
\begin{funcdesc}{dump}{value\, file} \begin{funcdesc}{dump}{value\, file}
Write the value on the open file. The value must be a supported Write the value on the open file. The value must be a supported
type. The file must be an open file object such as type. The file must be an open file object such as

View File

@ -1,61 +1,64 @@
\section{Built-in module \sectcode{md5}} \section{Built-in Module \sectcode{md5}}
\bimodindex{md5} \bimodindex{md5}
This module implements the interface to RSA's MD5 message digest This module implements the interface to RSA's MD5 message digest
algorithm (see also the file \file{md5.doc}). Its use is quite algorithm (see also Internet RFC 1321). Its use is quite
straightforward:\ use the function \code{new} to create an straightforward:\ use the \code{md5.new()} to create an md5 object.
\dfn{md5}-object. You can now ``feed'' this object with arbitrary You can now feed this object with arbitrary strings using the
strings. \code{update()} method, and at any point you can ask it for the
\dfn{digest} (a strong kind of 128-bit checksum,
a.k.a. ``fingerprint'') of the contatenation of the strings fed to it
so far using the \code{digest()} method.
At any time you can ask for the ``final'' digest of the object. Internally, For example, to obtain the digest of the string {\tt"Nobody inspects
a temporary copy of the object is made and the digest is computed and the spammish repetition"}:
returned. Because of the copy, the digest operation is not destructive
for the object. Before a more exact description of the module's use, a small
example will be helpful:
to obtain the digest of the string \code{'abc'}, use \ldots
\bcode\begin{verbatim} \bcode\begin{verbatim}
>>> import md5 >>> import md5
>>> m = md5.new() >>> m = md5.new()
>>> m.update('abc') >>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest() >>> m.digest()
'\220\001P\230<\322O\260\326\226?}(\341\177r' '\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
\end{verbatim}\ecode \end{verbatim}\ecode
More condensed: More condensed:
\bcode\begin{verbatim} \bcode\begin{verbatim}
>>> md5.new('abc').digest() >>> md5.new("Nobody inspects the spammish repetition").digest()
'\220\001P\230<\322O\260\326\226?}(\341\177r' '\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
\end{verbatim}\ecode \end{verbatim}\ecode
\renewcommand{\indexsubitem}{(in module md5)} \renewcommand{\indexsubitem}{(in module md5)}
\begin{funcdesc}{new}{\optional{arg}} \begin{funcdesc}{new}{\optional{arg}}
Create a new md5-object. If \var{arg} is present, an initial Return a new md5 object. If \var{arg} is present, the method call
\code{update} method is called with \var{arg} as argument. \code{update(\var{arg})} is made.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{md5}{\optional{arg}} \begin{funcdesc}{md5}{\optional{arg}}
For backward compatibility reasons, this is an alternative name for the For backward compatibility reasons, this is an alternative name for the
\code{new} function. \code{new()} function.
\end{funcdesc} \end{funcdesc}
An md5-object has the following methods: An md5 object has the following methods:
\renewcommand{\indexsubitem}{(md5 method)} \renewcommand{\indexsubitem}{(md5 method)}
\begin{funcdesc}{update}{arg} \begin{funcdesc}{update}{arg}
Update this md5-object with the string \var{arg}. Update the md5 object with the string \var{arg}. Repeated calls are
equivalent to a single call with the concatenation of all the
arguments, i.e.\ \code{m.update(a); m.update(b)} is equivalent to
\code{m.update(a+b)}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{digest}{} \begin{funcdesc}{digest}{}
% XXX The following is not quite clear; what does MD5Final do? Return the digest of the strings passed to the \code{update()}
Return the \dfn{digest} of this md5-object. Internally, a copy is made method so far. This is an 8-byte string which may contain
and the \C-function \code{MD5Final} is called. Finally the digest is non-\ASCII{} characters, including null bytes.
returned.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{copy}{} \begin{funcdesc}{copy}{}
Return a separate copy of this md5-object. An \code{update} to this Return a copy (``clone'') of the md5 object. This can be used to
copy won't affect the original object. efficiently compute the digests of strings that share a common initial
substring.
\end{funcdesc} \end{funcdesc}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{mimetools}} \section{Standard Module \sectcode{mimetools}}
\stmodindex{mimetools} \stmodindex{mimetools}
\renewcommand{\indexsubitem}{(in module mimetools)} \renewcommand{\indexsubitem}{(in module mimetools)}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{mpz}} \section{Built-in Module \sectcode{mpz}}
\bimodindex{mpz} \bimodindex{mpz}
This module implements the interface to part of the GNU MP library. This module implements the interface to part of the GNU MP library.

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{nntplib}} \section{Standard Module \sectcode{nntplib}}
\stmodindex{nntplib} \stmodindex{nntplib}
\renewcommand{\indexsubitem}{(in module nntplib)} \renewcommand{\indexsubitem}{(in module nntplib)}

View File

@ -26,9 +26,11 @@ In addition to whatever the correct OS dependent module exports, the
following variables and functions are always exported by \code{os}: following variables and functions are always exported by \code{os}:
\renewcommand{\indexsubitem}{(in module os)} \renewcommand{\indexsubitem}{(in module os)}
\begin{datadesc}{name} \begin{datadesc}{name}
The name of the OS dependent module imported, e.g. \code{'posix'} or The name of the OS dependent module imported. The following names
\code{'mac'}. have currently been registered: \code{'posix'}, \code{'nt'},
\code{'dos'}, \code{'mac'}.
\end{datadesc} \end{datadesc}
\begin{datadesc}{path} \begin{datadesc}{path}
@ -49,29 +51,54 @@ e.g. \code{'..'} for POSIX or \code{'::'} for the Mac.
\end{datadesc} \end{datadesc}
\begin{datadesc}{sep} \begin{datadesc}{sep}
The character used by the OS to separate pathname components, e.g. The character used by the OS to separate pathname components, e.g.\
\code{'/'} for POSIX or \code{':'} for the Mac. Note that knowing this \code{'/'} for POSIX or \code{':'} for the Mac. Note that knowing this
is not sufficient to be able to parse or concatenate pathnames---better 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 use \code{os.path.split()} and \code{os.path.join()}---but it is
occasionally useful. occasionally useful.
\end{datadesc} \end{datadesc}
\begin{datadesc}{pathsep}
The character conventionally used by the OS to separate search patch
components (as in \code{\$PATH}), e.g.\ \code{':'} for POSIX or
\code{';'} for MS-DOS.
\end{datadesc}
\begin{datadesc}{defpath}
The default search path used by \code{os.exec*p*()} if the environment
doesn't have a \code{'PATH'} key.
\end{datadesc}
\begin{funcdesc}{execl}{path\, arg0\, arg1\, ...} \begin{funcdesc}{execl}{path\, arg0\, arg1\, ...}
This is equivalent to a call to \code{os.execv} with an \var{argv} This is equivalent to
of \code{[\var{arg0}, \var{arg1}, ...]}. \code{os.execv(\var{path}, (\var{arg0}, \var{arg1}, ...))}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{execle}{path\, arg0\, arg1\, ...\, env} \begin{funcdesc}{execle}{path\, arg0\, arg1\, ...\, env}
This is equivalent to a call to \code{os.execve} with an \var{argv} This is equivalent to
of \code{[\var{arg0}, \var{arg1}, ...]}. \code{os.execve(\var{path}, (\var{arg0}, \var{arg1}, ...), \var{env})}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{execlp}{path\, arg0\, arg1\, ...} \begin{funcdesc}{execlp}{path\, arg0\, arg1\, ...}
This is like \code{execl} but duplicates the shell's actions in This is equivalent to
searching for an executable file in a list of directories. The \code{os.execvp(\var{path}, (\var{arg0}, \var{arg1}, ...))}.
directory list is obtained from \code{environ['PATH']}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{execvp}{path\, arg0\, arg1\, ...} \begin{funcdesc}{execvp}{path\, args}
\code{execvp} is for \code{execv} what \code{execlp} is for \code{execl}. This is like \code{os.execv(\var{path}, \var{args})} but duplicates
the shell's actions in searching for an executable file in a list of
directories. The directory list is obtained from
\code{os.environ['PATH']}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{execvpe}{path\, args\, env}
This is a cross between \code{os.execve()} and \code{os.execvp()}.
The directory list is obtained from \code{\var{env}['PATH']}.
\end{funcdesc}
(The functions \code{os.execv()} and \code{execve()} are not
documented here, since they are implemented by the OS dependent
module. If the OS dependent module doesn't define either of these,
the functions that rely on it will raise an exception. They are
documented in the section on module \code{posix}, together with all
other functions that \code{os} imports from the OS dependent module.)

View File

@ -91,7 +91,7 @@ Enter post-mortem debugging of the traceback found in
\code{sys.last_traceback}. \code{sys.last_traceback}.
\end{funcdesc} \end{funcdesc}
\subsection{Debugger Commands} \section{Debugger Commands}
The debugger recognizes the following commands. Most commands can be The debugger recognizes the following commands. Most commands can be
abbreviated to one or two letters; e.g. ``\code{h(elp)}'' means that abbreviated to one or two letters; e.g. ``\code{h(elp)}'' means that
@ -117,7 +117,7 @@ but the debugger's state is not changed.
\begin{description} \begin{description}
\item[{h(elp) [\var{command}]}] \item[h(elp) [\var{command}]]
Without argument, print the list of available commands. Without argument, print the list of available commands.
With a \var{command} as argument, print help about that command. With a \var{command} as argument, print help about that command.
@ -127,40 +127,40 @@ through that command instead. Since the \var{command} argument must be
an identifier, ``\code{help exec}'' must be entered to get help on the an identifier, ``\code{help exec}'' must be entered to get help on the
``\code{!}'' command. ``\code{!}'' command.
\item[{w(here)}] \item[w(here)]
Print a stack trace, with the most recent frame at the bottom. Print a stack trace, with the most recent frame at the bottom.
An arrow indicates the current frame, which determines the An arrow indicates the current frame, which determines the
context of most commands. context of most commands.
\item[{d(own)}] \item[d(own)]
Move the current frame one level down in the stack trace Move the current frame one level down in the stack trace
(to an older frame). (to an older frame).
\item[{u(p)}] \item[u(p)]
Move the current frame one level up in the stack trace Move the current frame one level up in the stack trace
(to a newer frame). (to a newer frame).
\item[{b(reak) [\var{lineno}\code{|}\var{function}]}] \item[b(reak) [\var{lineno}\code{|}\var{function}]]
With a \var{lineno} argument, set a break there in the current With a \var{lineno} argument, set a break there in the current
file. With a \var{function} argument, set a break at the entry of file. With a \var{function} argument, set a break at the entry of
that function. Without argument, list all breaks. that function. Without argument, list all breaks.
\item[{cl(ear) [\var{lineno}]}] \item[cl(ear) [\var{lineno}]]
With a \var{lineno} argument, clear that break in the current file. With a \var{lineno} argument, clear that break in the current file.
Without argument, clear all breaks (but first ask confirmation). Without argument, clear all breaks (but first ask confirmation).
\item[{s(tep)}] \item[s(tep)]
Execute the current line, stop at the first possible occasion Execute the current line, stop at the first possible occasion
(either in a function that is called or on the next line in the (either in a function that is called or on the next line in the
current function). current function).
\item[{n(ext)}] \item[n(ext)]
Continue execution until the next line in the current function Continue execution until the next line in the current function
is reached or it returns. (The difference between \code{next} and is reached or it returns. (The difference between \code{next} and
@ -168,15 +168,15 @@ is reached or it returns. (The difference between \code{next} and
\code{next} executes called functions at (nearly) full speed, only \code{next} executes called functions at (nearly) full speed, only
stopping at the next line in the current function.) stopping at the next line in the current function.)
\item[{r(eturn)}] \item[r(eturn)]
Continue execution until the current function returns. Continue execution until the current function returns.
\item[{c(ont(inue))}] \item[c(ont(inue))]
Continue execution, only stop when a breakpoint is encountered. Continue execution, only stop when a breakpoint is encountered.
\item[{l(ist) [\var{first} [, \var{last}]]}] \item[l(ist) [\var{first} [, \var{last}]]]
List source code for the current file. Without arguments, list 11 List source code for the current file. Without arguments, list 11
lines around the current line or continue the previous listing. With lines around the current line or continue the previous listing. With
@ -184,17 +184,17 @@ one argument, list 11 lines around at that line. With two arguments,
list the given range; if the second argument is less than the first, list the given range; if the second argument is less than the first,
it is interpreted as a count. it is interpreted as a count.
\item[{a(rgs)}] \item[a(rgs)]
Print the argument list of the current function. Print the argument list of the current function.
\item[{p \var{expression}}] \item[p \var{expression}]
Evaluate the \var{expression} in the current context and print its Evaluate the \var{expression} in the current context and print its
value. (Note: \code{print} can also be used, but is not a debugger value. (Note: \code{print} can also be used, but is not a debugger
command --- this executes the Python \code{print} statement.) command --- this executes the Python \code{print} statement.)
\item[{[!] \var{statement}}] \item[[!] \var{statement}]
Execute the (one-line) \var{statement} in the context of Execute the (one-line) \var{statement} in the context of
the current stack frame. the current stack frame.
@ -207,9 +207,83 @@ command with a ``\code{global}'' command on the same line, e.g.:
(Pdb) (Pdb)
\end{verbatim} \end{verbatim}
\item[{q(uit)}] \item[q(uit)]
Quit from the debugger. Quit from the debugger.
The program being executed is aborted. The program being executed is aborted.
\end{description} \end{description}
\section{How It Works}
Some changes were made to the interpreter:
\begin{itemize}
\item sys.settrace(func) sets the global trace function
\item there can also a local trace function (see later)
\end{itemize}
Trace functions have three arguments: (\var{frame}, \var{event}, \var{arg})
\begin{description}
\item[\var{frame}] is the current stack frame
\item[\var{event}] is a string: \code{'call'}, \code{'line'}, \code{'return'}
or \code{'exception'}
\item[\var{arg}] is dependent on the event type
\end{description}
A trace function should return a new trace function or None.
Class methods are accepted (and most useful!) as trace methods.
The events have the following meaning:
\begin{description}
\item[\code{'call'}]
A function is called (or some other code block entered). The global
trace function is called; arg is the argument list to the function;
the return value specifies the local trace function.
\item[\code{'line'}]
The interpreter is about to execute a new line of code (sometimes
multiple line events on one line exist). The local trace function is
called; arg in None; the return value specifies the new local trace
function.
\item[\code{'return'}]
A function (or other code block) is about to return. The local trace
function is called; arg is the value that will be returned. The trace
function's return value is ignored.
\item[\code{'exception'}]
An exception has occurred. The local trace function is called; arg is
a triple (exception, value, traceback); the return value specifies the
new local trace function
\end{description}
Note that as an exception is propagated down the chain of callers, an
\code{'exception'} event is generated at each level.
Stack frame objects have the following read-only attributes:
\begin{description}
\item[f_code] the code object being executed
\item[f_lineno] the current line number (\code{-1} for \code{'call'} events)
\item[f_back] the stack frame of the caller, or None
\item[f_locals] dictionary containing local name bindings
\item[f_globals] dictionary containing global name bindings
\end{description}
Code objects have the following read-only attributes:
\begin{description}
\item[co_code] the code string
\item[co_names] the list of names used by the code
\item[co_consts] the list of (literal) constants used by the code
\item[co_filename] the filename from which the code was compiled
\end{description}

View File

@ -1,4 +1,4 @@
\section{Built-in module \sectcode{pickle}} \section{Standard Module \sectcode{pickle}}
\stmodindex{pickle} \stmodindex{pickle}
\index{persistency} \index{persistency}
\indexii{persistent}{objects} \indexii{persistent}{objects}
@ -7,6 +7,8 @@
\indexii{flattening}{objects} \indexii{flattening}{objects}
\indexii{pickling}{objects} \indexii{pickling}{objects}
\renewcommand{\indexsubitem}{(in module pickle)}
The \code{pickle} module implements a basic but powerful algorithm for The \code{pickle} module implements a basic but powerful algorithm for
``pickling'' (a.k.a.\ serializing, marshalling or flattening) nearly ``pickling'' (a.k.a.\ serializing, marshalling or flattening) nearly
arbitrary Python objects. This is a more primitive notion than arbitrary Python objects. This is a more primitive notion than
@ -28,11 +30,11 @@ following correctly:
\begin{itemize} \begin{itemize}
\item recursive objects \item recursive objects (objects containing references to themselves)
\item pointer sharing \item object sharing (references to the same object in different places)
\item instances of user-defined classes \item user-defined classes and their instances
\end{itemize} \end{itemize}
@ -42,13 +44,13 @@ standards such as CORBA (which probably can't represent pointer
sharing or recursive objects); however it means that non-Python sharing or recursive objects); however it means that non-Python
programs may not be able to reconstruct pickled Python objects. programs may not be able to reconstruct pickled Python objects.
The \code{pickle} data format uses a printable ASCII representation. The \code{pickle} data format uses a printable \ASCII{} representation.
This is slightly more voluminous than a binary representation. This is slightly more voluminous than a binary representation.
However, small integers actually take {\em less} space when However, small integers actually take {\em less} space when
represented as minimal-size decimal strings than when represented as represented as minimal-size decimal strings than when represented as
32-bit binary numbers, and strings are only much longer if they 32-bit binary numbers, and strings are only much longer if they
contain many control characters or 8-bit characters. The big contain many control characters or 8-bit characters. The big
advantage of using printable ASCII (and of some other characteristics advantage of using printable \ASCII{} (and of some other characteristics
of \code{pickle}'s representation) is that for debugging or recovery of \code{pickle}'s representation) is that for debugging or recovery
purposes it is possible for a human to read the pickled file with a purposes it is possible for a human to read the pickled file with a
standard text editor. (I could have gone a step further and used a standard text editor. (I could have gone a step further and used a
@ -67,7 +69,7 @@ Trojan horses into a program.
For the benefit of persistency modules written using \code{pickle}, it For the benefit of persistency modules written using \code{pickle}, it
supports the notion of a reference to an object outside the pickled supports the notion of a reference to an object outside the pickled
data stream. Such objects are referenced by a name, which is an data stream. Such objects are referenced by a name, which is an
arbitrary string of printable ASCII characters. The resolution of arbitrary string of printable \ASCII{} characters. The resolution of
such names is not defined by the \code{pickle} module --- the such names is not defined by the \code{pickle} module --- the
persistent object module will have to implement a method persistent object module will have to implement a method
\code{persistent_load}. To write references to persistent objects, \code{persistent_load}. To write references to persistent objects,
@ -78,6 +80,8 @@ There are some restrictions on the pickling of class instances.
First of all, the class must be defined at the top level in a module. First of all, the class must be defined at the top level in a module.
\renewcommand{\indexsubitem}{(pickle protocol)}
Next, it must normally be possible to create class instances by Next, it must normally be possible to create class instances by
calling the class without arguments. If this is undesirable, the calling the class without arguments. If this is undesirable, the
class can define a method \code{__getinitargs__()}, which should class can define a method \code{__getinitargs__()}, which should
@ -86,7 +90,7 @@ class constructor (\code{__init__()}).
\ttindex{__getinitargs__} \ttindex{__getinitargs__}
\ttindex{__init__} \ttindex{__init__}
Classes can further influence how they are pickled --- if the class Classes can further influence how their instances are pickled --- if the class
defines the method \code{__getstate__()}, it is called and the return defines the method \code{__getstate__()}, it is called and the return
state is pickled as the contents for the instance, and if the class state is pickled as the contents for the instance, and if the class
defines the method \code{__setstate__()}, it is called with the defines the method \code{__setstate__()}, it is called with the
@ -113,6 +117,13 @@ will see many versions of a class, it may be worthwhile to put a version
number in the objects so that suitable conversions can be made by the number in the objects so that suitable conversions can be made by the
class's \code{__setstate__()} method. class's \code{__setstate__()} method.
When a class itself is pickled, only its name is pickled --- the class
definition is not pickled, but re-imported by the unpickling process.
Therefore, the restriction that the class must be defined at the top
level in a module applies to pickled classes as well.
\renewcommand{\indexsubitem}{(in module pickle)}
The interface can be summarized as follows. The interface can be summarized as follows.
To pickle an object \code{x} onto a file \code{f}, open for writing: To pickle an object \code{x} onto a file \code{f}, open for writing:
@ -122,6 +133,12 @@ p = pickle.Pickler(f)
p.dump(x) p.dump(x)
\end{verbatim} \end{verbatim}
A shorthand for this is:
\begin{verbatim}
pickle.dump(x, f)
\end{verbatim}
To unpickle an object \code{x} from a file \code{f}, open for reading: To unpickle an object \code{x} from a file \code{f}, open for reading:
\begin{verbatim} \begin{verbatim}
@ -129,11 +146,19 @@ u = pickle.Unpickler(f)
x = u.load(x) x = u.load(x)
\end{verbatim} \end{verbatim}
A shorthand is:
\begin{verbatim}
x = pickle.load(f)
\end{verbatim}
The \code{Pickler} class only calls the method \code{f.write} with a The \code{Pickler} class only calls the method \code{f.write} with a
string argument. The \code{Unpickler} calls the methods \code{f.read} string argument. The \code{Unpickler} calls the methods \code{f.read}
(with an integer argument) and \code{f.readline} (without argument), (with an integer argument) and \code{f.readline} (without argument),
both returning a string. It is explicitly allowed to pass non-file both returning a string. It is explicitly allowed to pass non-file
objects here, as long as they have the right methods. objects here, as long as they have the right methods.
\ttindex{Unpickler}
\ttindex{Pickler}
The following types can be pickled: The following types can be pickled:
\begin{itemize} \begin{itemize}
@ -146,25 +171,56 @@ The following types can be pickled:
\item tuples, lists and dictionaries containing only picklable objects \item tuples, lists and dictionaries containing only picklable objects
\item class instances whose \code{__dict__} or \code{__setstate__()} \item classes that are defined at the top level in a module
is picklable
\item instances of such classes whose \code{__dict__} or
\code{__setstate__()} is picklable
\end{itemize} \end{itemize}
Attempts to pickle unpicklable objects will raise an exception; when Attempts to pickle unpicklable objects will raise the
this happens, an unspecified number of bytes may have been written to \code{PicklingError} exception; when this happens, an unspecified
the file argument. number of bytes may have been written to the file.
It is possible to make multiple calls to \code{Pickler.dump()} or to It is possible to make multiple calls to the \code{dump()} method of
\code{Unpickler.load()}, as long as there is a one-to-one the same \code{Pickler} instance. These must then be matched to the
correspondence between \code{Pickler} and \code{Unpickler} objects and same number of calls to the \code{load()} instance of the
between \code{dump} and \code{load} calls for any pair of corresponding \code{Unpickler} instance. If the same object is
corresponding \code{Pickler} and \code{Unpicklers}. {\em Warning}: pickled by multiple \code{dump()} calls, the \code{load()} will all
this is intended for pickling multiple objects without intervening yield references to the same object. {\em Warning}: this is intended
modifications to the objects or their parts. If you modify an object for pickling multiple objects without intervening modifications to the
and then pickle it again using the same \code{Pickler} instance, the objects or their parts. If you modify an object and then pickle it
object is not pickled again --- a reference to it is pickled and the again using the same \code{Pickler} instance, the object is not
\code{Unpickler} will return the old value, not the modified one. (There pickled again --- a reference to it is pickled and the
are two problems here: (a) detecting changes, and (b) marshalling a \code{Unpickler} will return the old value, not the modified one.
minimal set of changes. I have no answers. Garbage Collection may (There are two problems here: (a) detecting changes, and (b)
also become a problem here.) marshalling a minimal set of changes. I have no answers. Garbage
Collection may also become a problem here.)
Apart from the \code{Pickler} and \code{Unpickler} classes, the
module defines the following functions, and an exception:
\begin{funcdesc}{dump}{object\, file}
Write a pickled representation of \var{obect} to the open file object
\var{file}. This is equivalent to \code{Pickler(file).dump(object)}.
\end{funcdesc}
\begin{funcdesc}{load}{file}
Read a pickled object from the open file object \var{file}. This is
equivalent to \code{Unpickler(file).load()}.
\end{funcdesc}
\begin{funcdesc}{dumps}{object}
Return the pickled representation of the object as a string, instead
of writing it to a file.
\end{funcdesc}
\begin{funcdesc}{loads}{string}
Read a pickled object from a string instead of a file. Characters in
the string past the pickled object's representation are ignored.
\end{funcdesc}
\begin{excdesc}{PicklingError}
This exception is raised when an unpicklable object is passed to
\code{Pickler.dump()}.
\end{excdesc}

View File

@ -1,12 +1,20 @@
\section{Built-in Module \sectcode{posix}} \section{Built-in Module \sectcode{posix}}
\bimodindex{posix} \bimodindex{posix}
This module provides access to operating system functionality that is This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly disguised standardized by the C Standard and the POSIX standard (a thinly disguised
\UNIX{} interface). \UNIX{} interface).
It is available in all Python versions except on the Macintosh;
the MS-DOS version does not support certain functions. \strong{Do not import this module directly.} Instead, import the
module \code{os}, which provides a \emph{portable} version of this
interface. On \UNIX{}, the \code{os} module provides a superset of
the \code{posix} interface. On non-\UNIX{} operating systems the
\code{posix} module is not available, but a subset is always available
through the \code{os} interface. Once \code{os} is imported, there is
\emph{no} performance penalty in using it instead of
\code{posix}.
\stmodindex{os}
The descriptions below are very terse; refer to the The descriptions below are very terse; refer to the
corresponding \UNIX{} manual entry for more information. corresponding \UNIX{} manual entry for more information.
@ -20,13 +28,18 @@ Module \code{posix} defines the following data items:
\begin{datadesc}{environ} \begin{datadesc}{environ}
A dictionary representing the string environment at the time A dictionary representing the string environment at the time
the interpreter was started. the interpreter was started.
(Modifying this dictionary does not affect the string environment of the
interpreter.)
For example, For example,
\code{posix.environ['HOME']} \code{posix.environ['HOME']}
is the pathname of your home directory, equivalent to is the pathname of your home directory, equivalent to
\code{getenv("HOME")} \code{getenv("HOME")}
in C. in C.
Modifying this dictionary does not affect the string environment
passed on by \code{execv()}, \code{popen()} or \code{system()}; if you
need to change the environment, pass \code{environ} to \code{execve()}
or add variable assignments and export statements to the command
string for \code{system()} or \code{popen()}.%
\footnote{The problem with automatically passing on \code{environ} is
that there is no portable way of changing the environment.}
\end{datadesc} \end{datadesc}
\renewcommand{\indexsubitem}{(exception in module posix)} \renewcommand{\indexsubitem}{(exception in module posix)}

View File

@ -7,12 +7,13 @@ This module implements some additional functionality over the built-in
file objects. In particular, it implements file locking, control over file objects. In particular, it implements file locking, control over
the file flags, and an easy interface to duplicate the file object. the file flags, and an easy interface to duplicate the file object.
The module defines a new file object, the posixfile object. It The module defines a new file object, the posixfile object. It
inherits all the standard file object methods and adds the methods has all the standard file object methods and adds the methods
described below. described below. This module only works for certain flavors of
\UNIX{}, since it uses \code{fcntl()} for file locking.
To instantiate a posixfile object, use the \code{open()} function in To instantiate a posixfile object, use the \code{open()} function in
the posixfile module. The resulting object looks and feels the same as the posixfile module. The resulting object looks and feels roughly
a standard file object. the same as a standard file object.
The posixfile module defines the following constants: The posixfile module defines the following constants:
@ -32,10 +33,11 @@ offset is calculated from the end of the file
The posixfile module defines the following functions: The posixfile module defines the following functions:
\renewcommand{\indexsubitem}{(in module posixfile)} \renewcommand{\indexsubitem}{(in module posixfile)}
\begin{funcdesc}{open}{filename\, mode}
\begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}}
Create a new posixfile object with the given filename and mode. The Create a new posixfile object with the given filename and mode. The
filename and mode are interpreted the same way as the \code{open()} \var{filename}, \var{mode} and \var{bufsize} arguments are
builtin function. interpreted the same way as by the \code{open()} builtin function.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{fileopen}{fileobject} \begin{funcdesc}{fileopen}{fileobject}
@ -102,8 +104,8 @@ In addition the following modifiers can be added to the format:
\begin{tableiii}{|c|l|c|}{samp}{Modifier}{Meaning}{Notes} \begin{tableiii}{|c|l|c|}{samp}{Modifier}{Meaning}{Notes}
\lineiii{|}{wait until the lock has been granted}{} \lineiii{|}{wait until the lock has been granted}{}
\lineiii{?}{return the first lock conflicting with the requested lock,}{(1)} \lineiii{?}{return the first lock conflicting with the requested lock, or
{}&{\hskip0.5cm or \code{None} if there is no conflict.}&{}\\ \code{None} if there is no conflict.}{(1)}
\end{tableiii} \end{tableiii}
Note: Note:

View File

@ -1,9 +1,14 @@
\section{Standard Module \sectcode{posixpath}} \section{Standard Module \sectcode{posixpath}}
\stmodindex{posixpath} \stmodindex{posixpath}
This module implements some useful functions on POSIX pathnames. This module implements some useful functions on POSIX pathnames.
\strong{Do not import this module directly.} Instead, import the
module \code{os} and use \code{os.path}.
\stmodindex{os}
\renewcommand{\indexsubitem}{(in module posixpath)} \renewcommand{\indexsubitem}{(in module posixpath)}
\begin{funcdesc}{basename}{p} \begin{funcdesc}{basename}{p}
Return the base name of pathname Return the base name of pathname
\var{p}. \var{p}.
@ -66,10 +71,12 @@ Always false if symbolic links are not supported.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{ismount}{p} \begin{funcdesc}{ismount}{p}
Return true if \var{p} is a mount point. (This currently checks whether Return true if pathname \var{p} is a \dfn{mount point}: a point in a
\code{\var{p}/..} is on a different device from \var{p} or whether file system where a different file system has been mounted. The
\code{\var{p}/..} and \var{p} point to the same i-node on the same function checks whether \var{p}'s parent, \file{\var{p}/..}, is on a
device --- is this test correct for all \UNIX{} and POSIX variants?) different device than \var{p}, or whether \file{\var{p}/..} and
\var{p} point to the same i-node on the same device --- this should
detect mount points for all \UNIX{} and POSIX variants.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{join}{p\, q} \begin{funcdesc}{join}{p\, q}
@ -128,9 +135,10 @@ Calls the function \var{visit} with arguments
directory tree rooted at \var{p} (including \var{p} itself, if it is a directory tree rooted at \var{p} (including \var{p} itself, if it is a
directory). The argument \var{dirname} specifies the visited directory, directory). The argument \var{dirname} specifies the visited directory,
the argument \var{names} lists the files in the directory (gotten from the argument \var{names} lists the files in the directory (gotten from
\code{posix.listdir(\var{dirname})}). The \var{visit} function may \code{posix.listdir(\var{dirname})}, so including \samp{.} and
modify \var{names} to influence the set of directories visited below \samp{..}). The \var{visit} function may modify \var{names} to
\var{dirname}, e.g., to avoid visiting certain parts of the tree. (The influence the set of directories visited below \var{dirname}, e.g., to
object referred to by \var{names} must be modified in place, using avoid visiting certain parts of the tree. (The object referred to by
\code{del} or slice assignment.) \var{names} must be modified in place, using \code{del} or slice
assignment.)
\end{funcdesc} \end{funcdesc}

View File

@ -2,7 +2,7 @@
\stmodindex{profile} \stmodindex{profile}
\stmodindex{pstats} \stmodindex{pstats}
Copyright 1994, by InfoSeek Corporation, all rights reserved. Copyright \copyright\ 1994, by InfoSeek Corporation, all rights reserved.
Written by James Roskind% Written by James Roskind%
\footnote{ \footnote{
@ -42,7 +42,7 @@ ways at times. Please send suggestions for improvements to:
I'd appreciate the feedback. I'd appreciate the feedback.
\section{Introduction} \section{Introduction to the profiler}
A \dfn{profiler} is a program that describes the run time performance A \dfn{profiler} is a program that describes the run time performance
of a program, providing a variety of statistics. This documentation of a program, providing a variety of statistics. This documentation
@ -242,7 +242,7 @@ of algorithms to be directly compared to iterative implementations.
\section{Reference Manual} \section{Reference Manual}
\renewcommand{\indexsubitem}{} \renewcommand{\indexsubitem}{(profiler function)}
The primary entry point for the profiler is the global function The primary entry point for the profiler is the global function
\code{profile.run()}. It is typically used to create any profile \code{profile.run()}. It is typically used to create any profile
@ -254,7 +254,7 @@ Profiler Extensions, which includes discussion of how to derive
``better'' profilers from the classes presented, or reading the source ``better'' profilers from the classes presented, or reading the source
code for these modules. code for these modules.
\begin{funcdesc}{profile.run}{string\optional{\, filename}} \begin{funcdesc}{profile.run}{string\optional{\, filename\optional{\, ...}}}
This function takes a single argument that has can be passed to the This function takes a single argument that has can be passed to the
\code{exec} statement, and an optional file name. In all cases this \code{exec} statement, and an optional file name. In all cases this
@ -336,12 +336,12 @@ need to be combined with data in an existing \code{Stats} object, the
\end{funcdesc} \end{funcdesc}
\subsection{Methods Of The \sectcode{Stats} Class} \subsection{The \sectcode{Stats} Class}
\renewcommand{\indexsubitem}{(Stats method)} \renewcommand{\indexsubitem}{(Stats method)}
\begin{funcdesc}{strip_dirs}{} \begin{funcdesc}{strip_dirs}{}
This method for the code{Stats} class removes all leading path information This method for the \code{Stats} class removes all leading path information
from file names. It is very useful in reducing the size of the from file names. It is very useful in reducing the size of the
printout to fit within (close to) 80 columns. This method modifies printout to fit within (close to) 80 columns. This method modifies
the object, and the stripped information is lost. After performing a the object, and the stripped information is lost. After performing a
@ -355,7 +355,7 @@ these two entries are accumulated into a single entry.
\begin{funcdesc}{add}{filename\optional{\, ...}} \begin{funcdesc}{add}{filename\optional{\, ...}}
This method of the code{Stats} class accumulates additional profiling This method of the \code{Stats} class accumulates additional profiling
information into the current profiling object. Its arguments should information into the current profiling object. Its arguments should
refer to filenames created by the corresponding version of refer to filenames created by the corresponding version of
\code{profile.run()}. Statistics for identically named (re: file, \code{profile.run()}. Statistics for identically named (re: file,
@ -364,7 +364,7 @@ function statistics.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{sort_stats}{key\optional{\, ...}} \begin{funcdesc}{sort_stats}{key\optional{\, ...}}
This method modifies the code{Stats} object by sorting it according to the This method modifies the \code{Stats} object by sorting it according to the
supplied criteria. The argument is typically a string identifying the supplied criteria. The argument is typically a string identifying the
basis of a sort (example: \code{"time"} or \code{"name"}). basis of a sort (example: \code{"time"} or \code{"name"}).
@ -412,7 +412,7 @@ additional arguments will be silently ignored.
\begin{funcdesc}{reverse_order}{} \begin{funcdesc}{reverse_order}{}
This method for the code{Stats} class reverses the ordering of the basic This method for the \code{Stats} class reverses the ordering of the basic
list within the object. This method is provided primarily for list within the object. This method is provided primarily for
compatibility with the old profiler. Its utility is questionable compatibility with the old profiler. Its utility is questionable
now that ascending vs descending order is properly selected based on now that ascending vs descending order is properly selected based on
@ -420,7 +420,7 @@ the sort key of choice.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{print_stats}{restriction\optional{\, ...}} \begin{funcdesc}{print_stats}{restriction\optional{\, ...}}
This method for the code{Stats} class prints out a report as described This method for the \code{Stats} class prints out a report as described
in the \code{profile.run()} definition. in the \code{profile.run()} definition.
The order of the printing is based on the last \code{sort_stats()} The order of the printing is based on the last \code{sort_stats()}
@ -454,7 +454,7 @@ and then proceed to only print the first 10\% of them.
\begin{funcdesc}{print_callers}{restrictions\optional{\, ...}} \begin{funcdesc}{print_callers}{restrictions\optional{\, ...}}
This method for the code{Stats} class prints a list of all functions This method for the \code{Stats} class prints a list of all functions
that called each function in the profiled database. The ordering is that called each function in the profiled database. The ordering is
identical to that provided by \code{print_stats()}, and the definition identical to that provided by \code{print_stats()}, and the definition
of the restricting argument is also identical. For convenience, a of the restricting argument is also identical. For convenience, a
@ -464,14 +464,14 @@ is the cumulative time spent in the function at the right.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{print_callees}{restrictions\optional{\, ...}} \begin{funcdesc}{print_callees}{restrictions\optional{\, ...}}
This method for the code{Stats} class prints a list of all function This method for the \code{Stats} class prints a list of all function
that were called by the indicated function. Aside from this reversal that were called by the indicated function. Aside from this reversal
of direction of calls (re: called vs was called by), the arguments and of direction of calls (re: called vs was called by), the arguments and
ordering are identical to the \code{print_callers()} method. ordering are identical to the \code{print_callers()} method.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{ignore}{} \begin{funcdesc}{ignore}{}
This method of the code{Stats} class is used to dispose of the value This method of the \code{Stats} class is used to dispose of the value
returned by earlier methods. All standard methods in this class returned by earlier methods. All standard methods in this class
return the instance that is being processed, so that the commands can return the instance that is being processed, so that the commands can
be strung together. For example: be strung together. For example:
@ -481,7 +481,7 @@ pstats.Stats('foofile').strip_dirs().sort_stats('cum').print_stats().ignore()
\end{verbatim} \end{verbatim}
would perform all the indicated functions, but it would not return would perform all the indicated functions, but it would not return
the final reference to the code{Stats} instance.% the final reference to the \code{Stats} instance.%
\footnote{ \footnote{
This was once necessary, when Python would print any unused expression This was once necessary, when Python would print any unused expression
result that was not \code{None}. The method is still defined for result that was not \code{None}. The method is still defined for
@ -604,7 +604,7 @@ performance section, and there is no reason to use a variable lookup
at this point, when a constant can be used. at this point, when a constant can be used.
\section{Extensions: Deriving Better Profilers} \section{Extensions - Deriving Better Profilers}
The \code{Profile} class of module \code{profile} was written so that The \code{Profile} class of module \code{profile} was written so that
derived classes could be developed to extend the profiler. Rather derived classes could be developed to extend the profiler. Rather

View File

@ -44,12 +44,13 @@ The module defines these functions, and an exception:
\begin{funcdesc}{compile}{pattern\optional{\, translate}} \begin{funcdesc}{compile}{pattern\optional{\, translate}}
Compile a regular expression pattern into a regular expression Compile a regular expression pattern into a regular expression
object, which can be used for matching using its \code{match} and object, which can be used for matching using its \code{match} and
\code{search} methods, described below. The optional \code{search} methods, described below. The optional argument
\var{translate}, if present, must be a 256-character string \var{translate}, if present, must be a 256-character string
indicating how characters (both of the pattern and of the strings to indicating how characters (both of the pattern and of the strings to
be matched) are translated before comparing them; the \code{i}-th be matched) are translated before comparing them; the \code{i}-th
element of the string gives the translation for the character with element of the string gives the translation for the character with
ASCII code \code{i}. \ASCII{} code \code{i}. This can be used to implement
case-insensitive matching; see the \code{casefold} data item below.
The sequence The sequence

Some files were not shown because too many files have changed in this diff Show More