Merged changes from the 1.5.2p2 release.

(Very rough.)
This commit is contained in:
Fred Drake 2000-04-03 20:13:55 +00:00
parent 659ebfa79e
commit 38e5d27cae
59 changed files with 1248 additions and 516 deletions

View file

@ -6,8 +6,8 @@
The modules described in this chapter implement Internet protocols and The modules described in this chapter implement Internet protocols and
support for related technology. They are all implemented in Python. support for related technology. They are all implemented in Python.
Some of these modules require the presence of the system-dependent Most of these modules require the presence of the system-dependent
module \refmodule{socket}\refbimodindex{socket}, which is currently only module \refmodule{socket}\refbimodindex{socket}, which is currently
fully supported on \UNIX{} and Windows NT. Here is an overview: supported on most popular platforms. Here is an overview:
\localmoduletable \localmoduletable

View file

@ -76,11 +76,11 @@ numbers are valid as long as the array exists and no length-changing
operations are applied to it. operations are applied to it.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}[array]{byteswap}{x} \begin{methoddesc}[array]{byteswap}{}
``Byteswap'' all items of the array. This is only supported for ``Byteswap'' all items of the array. This is only supported for
integer values; for other types of values, \exception{RuntimeError} is values which are 1, 2, 4, or 8 bytes in size; for other types of
raised. It is useful when reading data from a file written on a values, \exception{RuntimeError} is raised. It is useful when reading
machine with a different byte order. data from a file written on a machine with a different byte order.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}[array]{fromfile}{f, n} \begin{methoddesc}[array]{fromfile}{f, n}
@ -150,7 +150,8 @@ represented as \code{array(\var{typecode}, \var{initializer})}. The
string if the \var{typecode} is \code{'c'}, otherwise it is a list of string if the \var{typecode} is \code{'c'}, otherwise it is a list of
numbers. The string is guaranteed to be able to be converted back to numbers. The string is guaranteed to be able to be converted back to
an array with the same type and value using reverse quotes an array with the same type and value using reverse quotes
(\code{``}). Examples: (\code{``}), so long as the \function{array()} function has been
imported using \samp{from array import array}. Examples:
\begin{verbatim} \begin{verbatim}
array('l') array('l')
@ -163,4 +164,10 @@ array('d', [1.0, 2.0, 3.14])
\begin{seealso} \begin{seealso}
\seemodule{struct}{packing and unpacking of heterogeneous binary data} \seemodule{struct}{packing and unpacking of heterogeneous binary data}
\seemodule{xdrlib}{packing and unpacking of XDR data} \seemodule{xdrlib}{packing and unpacking of XDR data}
\seetext{The Numeric Python extension (NumPy) defines another array
type; see \emph{The Numerical Python Manual} for additional
information (available online at
\url{ftp://ftp-icf.llnl.gov/pub/python/numericalpython.pdf}).
Further information about NumPy is available at
\url{http://www.python.org/topics/scicomp/numpy.html}.}
\end{seealso} \end{seealso}

View file

@ -1,18 +1,16 @@
\section{\module{asyncore} --- \section{\module{asyncore} ---
Asyncronous socket handler} Asynchronous socket handler}
\declaremodule{builtin}{asyncore} \declaremodule{builtin}{asyncore}
\modulesynopsis{A base class for developing asyncronous socket \modulesynopsis{A base class for developing asynchronous socket
handling services.} handling services.}
\moduleauthor{Sam Rushing}{rushing@nightmare.com} \moduleauthor{Sam Rushing}{rushing@nightmare.com}
\sectionauthor{Christopher Petrilli}{petrilli@amber.org} \sectionauthor{Christopher Petrilli}{petrilli@amber.org}
% Heavily adapted from original documentation by Sam Rushing. % Heavily adapted from original documentation by Sam Rushing.
This module provides the basic infrastructure for writing asyncronous This module provides the basic infrastructure for writing asynchronous
socket service clients and servers. socket service clients and servers.
%\subsection{Why Asyncronous?}
There are only two ways to have a program on a single processor do There are only two ways to have a program on a single processor do
``more than one thing at a time.'' Multi-threaded programming is the ``more than one thing at a time.'' Multi-threaded programming is the
simplest and most popular way to do it, but there is another very simplest and most popular way to do it, but there is another very

View file

@ -10,14 +10,14 @@
This module performs base64 encoding and decoding of arbitrary binary This module performs base64 encoding and decoding of arbitrary binary
strings into text strings that can be safely emailed or posted. The strings into text strings that can be safely emailed or posted. The
encoding scheme is defined in \rfc{1421} (``Privacy Enhancement for encoding scheme is defined in \rfc{1521} (\emph{MIME
Internet Electronic Mail: Part I: Message Encryption and (Multipurpose Internet Mail Extensions) Part One: Mechanisms for
Authentication Procedures'', section 4.3.2.4, ``Step 4: Printable Specifying and Describing the Format of Internet Message Bodies},
Encoding'') and is used for MIME email and section 5.2, ``Base64 Content-Transfer-Encoding'') and is used for
various other Internet-related applications; it is not the same as the MIME email and various other Internet-related applications; it is not
output produced by the \program{uuencode} program. For example, the the same as the output produced by the \program{uuencode} program.
string \code{'www.python.org'} is encoded as the string For example, the string \code{'www.python.org'} is encoded as the
\code{'d3d3LnB5dGhvbi5vcmc=\e n'}. string \code{'d3d3LnB5dGhvbi5vcmc=\e n'}.
\begin{funcdesc}{decode}{input, output} \begin{funcdesc}{decode}{input, output}
@ -52,4 +52,9 @@ base64 encoded data.
\begin{seealso} \begin{seealso}
\seemodule{binascii}{support module containing \ASCII{}-to-binary \seemodule{binascii}{support module containing \ASCII{}-to-binary
and binary-to-\ASCII{} conversions} and binary-to-\ASCII{} conversions}
\seetext{Internet \rfc{1521}, \emph{MIME (Multipurpose Internet
Mail Extensions) Part One: Mechanisms for Specifying and
Describing the Format of Internet Message Bodies}, section
5.2, ``Base64 Content-Transfer-Encoding,'' provides the
definition of the base64 encoding.}
\end{seealso} \end{seealso}

View file

@ -1,12 +1,12 @@
% LaTeX produced by Fred L. Drake, Jr. <fdrake@acm.org>, with an
% example based on the PyModules FAQ entry by Aaron Watters
% <arw@pythonpros.com>.
\section{\module{bisect} --- \section{\module{bisect} ---
Array bisection algorithm} Array bisection algorithm}
\declaremodule{standard}{bisect} \declaremodule{standard}{bisect}
\modulesynopsis{Array bisection algorithms for binary searching.} \modulesynopsis{Array bisection algorithms for binary searching.}
\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
% LaTeX produced by Fred L. Drake, Jr. <fdrake@acm.org>, with an
% example based on the PyModules FAQ entry by Aaron Watters
% <arw@pythonpros.com>.
This module provides support for maintaining a list in sorted order This module provides support for maintaining a list in sorted order

View file

@ -7,59 +7,71 @@
\sectionauthor{Skip Montanaro}{skip@mojam.com} \sectionauthor{Skip Montanaro}{skip@mojam.com}
The \module{bsddb} module provides an interface to the Berkeley DB library. The \module{bsddb} module provides an interface to the Berkeley DB
Users can create hash, btree or record based library files using the library. Users can create hash, btree or record based library files
appropriate open call. Bsddb objects behave generally like dictionaries. using the appropriate open call. Bsddb objects behave generally like
Keys and values must be strings, however, so to use other objects as keys or dictionaries. Keys and values must be strings, however, so to use
to store other kinds of objects the user must serialize them somehow, other objects as keys or to store other kinds of objects the user must
typically using marshal.dumps or pickle.dumps. serialize them somehow, typically using marshal.dumps or pickle.dumps.
The \module{bsddb} module is only available on \UNIX{} systems, so it is not The \module{bsddb} module is only available on \UNIX{} systems, so it
built by default in the standard Python distribution. Also, there are two is not built by default in the standard Python distribution. Also,
incompatible versions of the underlying library. Version 1.85 is widely there are two incompatible versions of the underlying library.
available, but has some known bugs. Version 2 is not quite as widely used, Version 1.85 is widely available, but has some known bugs. Version 2
but does offer some improvements. The \module{bsddb} module uses the 1.85 is not quite as widely used, but does offer some improvements. The
interface. Users wishing to use version 2 of the Berkeley DB library will \module{bsddb} module uses the 1.85 interface. Users wishing to use
have to modify the source for the module to include db_185.h instead of version 2 of the Berkeley DB library will have to modify the source
db.h. for the module to include \file{db_185.h} instead of
\file{db.h} (\file{db_185.h} contains the version 1.85 compatibility
interface).
The \module{bsddb} module defines the following functions that create The \module{bsddb} module defines the following functions that create
objects that access the appropriate type of Berkeley DB file. The first two objects that access the appropriate type of Berkeley DB file. The
arguments of each function are the same. For ease of portability, only the first two arguments of each function are the same. For ease of
first two arguments should be used in most instances. portability, only the first two arguments should be used in most
instances.
\begin{funcdesc}{hashopen}{filename\optional{, flag\optional{, \begin{funcdesc}{hashopen}{filename\optional{, flag\optional{,
mode\optional{, bsize\optional{, ffactor\optional{, nelem\optional{, mode\optional{, bsize\optional{,
cachesize\optional{, hash\optional{, lorder}}}}}}}}} ffactor\optional{, nelem\optional{,
Open the hash format file named \var{filename}. The optional \var{flag} cachesize\optional{, hash\optional{,
identifies the mode used to open the file. It may be ``r'' (read only), lorder}}}}}}}}}
``w'' (read-write), ``c'' (read-write - create if necessary) or ``n'' Open the hash format file named \var{filename}. The optional
(read-write - truncate to zero length). The other arguments are rarely used \var{flag} identifies the mode used to open the file. It may be
and are just passed to the low-level dbopen function. Consult the \character{r} (read only), \character{w} (read-write),
Berkeley DB documentation for their use and interpretation. \character{c} (read-write - create if necessary) or
\character{n} (read-write - truncate to zero length). The other
arguments are rarely used and are just passed to the low-level
\cfunction{dbopen()} function. Consult the Berkeley DB documentation
for their use and interpretation.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{btopen}{filename\optional{, flag\optional{, \begin{funcdesc}{btopen}{filename\optional{, flag\optional{,
mode\optional{, btflags\optional{, cachesize\optional{, maxkeypage\optional{, mode\optional{, btflags\optional{, cachesize\optional{, maxkeypage\optional{,
minkeypage\optional{, psize\optional{, lorder}}}}}}}}} minkeypage\optional{, psize\optional{, lorder}}}}}}}}}
Open the btree format file named \var{filename}. The optional \var{flag}
identifies the mode used to open the file. It may be ``r'' (read only), Open the btree format file named \var{filename}. The optional
``w'' (read-write), ``c'' (read-write - create if necessary) or ``n'' \var{flag} identifies the mode used to open the file. It may be
(read-write - truncate to zero length). The other arguments are rarely used \character{r} (read only), \character{w} (read-write),
and are just passed to the low-level dbopen function. Consult the \character{c} (read-write - create if necessary) or
Berkeley DB documentation for their use and interpretation. \character{n} (read-write - truncate to zero length). The other
arguments are rarely used and are just passed to the low-level dbopen
function. Consult the Berkeley DB documentation for their use and
interpretation.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{rnopen}{filename\optional{, flag\optional{, mode\optional{, \begin{funcdesc}{rnopen}{filename\optional{, flag\optional{, mode\optional{,
rnflags\optional{, cachesize\optional{, psize\optional{, lorder\optional{, rnflags\optional{, cachesize\optional{, psize\optional{, lorder\optional{,
reclen\optional{, bval\optional{, bfname}}}}}}}}}} reclen\optional{, bval\optional{, bfname}}}}}}}}}}
Open a DB record format file named \var{filename}. The optional \var{flag}
identifies the mode used to open the file. It may be ``r'' (read only), Open a DB record format file named \var{filename}. The optional
``w'' (read-write), ``c'' (read-write - create if necessary) or ``n'' \var{flag} identifies the mode used to open the file. It may be
(read-write - truncate to zero length). The other arguments are rarely used \character{r} (read only), \character{w} (read-write),
and are just passed to the low-level dbopen function. Consult the \character{c} (read-write - create if necessary) or
Berkeley DB documentation for their use and interpretation. \character{n} (read-write - truncate to zero length). The other
arguments are rarely used and are just passed to the low-level dbopen
function. Consult the Berkeley DB documentation for their use and
interpretation.
\end{funcdesc} \end{funcdesc}
@ -86,7 +98,7 @@ list returned is different for different file formats.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}{has_key}{key} \begin{methoddesc}{has_key}{key}
Return 1 if the DB file contains the argument as a key. Return \code{1} if the DB file contains the argument as a key.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}{set_location}{key} \begin{methoddesc}{set_location}{key}

View file

@ -1,18 +1,18 @@
% This section was contributed by Drew Csillag <drew_csillag@geocities.com>.
\section{\module{calendar} --- \section{\module{calendar} ---
Functions that emulate the \UNIX{} \program{cal} program.} General calendar-related functions}
\declaremodule{standard}{calendar} \declaremodule{standard}{calendar}
\modulesynopsis{General functions for working with the calendar,
\modulesynopsis{Functions that emulate the \UNIX{} \program{cal} including some emulation of the \UNIX{} \program{cal}
program.} program.}
\sectionauthor{Drew Csillag}{drew_csillag@geocities.com}
This module allows you to output calendars like the \UNIX{} This module allows you to output calendars like the \UNIX{}
\manpage{cal}{1} program. \program{cal} program, and provides additional useful functions
related to the calendar.
\begin{funcdesc}{isleap}{year} \begin{funcdesc}{isleap}{year}
Returns \code{1} if \var{year} is a leap year. Returns true if \var{year} is a leap year.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{leapdays}{year1, year2} \begin{funcdesc}{leapdays}{year1, year2}
@ -48,9 +48,14 @@ Prints the calendar for the year \var{year}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{timegm}{tuple} \begin{funcdesc}{timegm}{tuple}
An unrelated but handy function that takes a time tuple such are An unrelated but handy function that takes a time tuple such as
returned by the \function{gmtime()} function in the \module{time} returned by the \function{gmtime()} function in the \refmodule{time}
module, and returns the corresponding Unix timestamp value, assuming module, and returns the corresponding Unix timestamp value, assuming
an epoch of 1970, and the POSIX encoding. In fact, an epoch of 1970, and the POSIX encoding. In fact,
\function{gmtime()} and \function{timegm()} are each others inverse. \function{time.gmtime()} and \function{timegm()} are each others' inverse.
\end{funcdesc} \end{funcdesc}
\begin{seealso}
\seemodule{time}{Low-level time related functions.}
\end{seealso}

View file

@ -3,6 +3,8 @@
\declaremodule{standard}{ConfigParser} \declaremodule{standard}{ConfigParser}
\modulesynopsis{Configuration file parser.} \modulesynopsis{Configuration file parser.}
\moduleauthor{Ken Manheimer}{klm@digicool.com}
\moduleauthor{Barry Warsaw}{bwarsaw@python.org}
\sectionauthor{Christopher G. Petrilli}{petrilli@amber.org} \sectionauthor{Christopher G. Petrilli}{petrilli@amber.org}
This module defines the class \class{ConfigParser}. This module defines the class \class{ConfigParser}.
@ -16,24 +18,27 @@ programs which can be customized by end users easily.
The configuration file consists of sections, lead by a The configuration file consists of sections, lead by a
\samp{[section]} header and followed by \samp{name: value} entries, \samp{[section]} header and followed by \samp{name: value} entries,
with continuations in the style of \rfc{822}; \samp{name=value} is with continuations in the style of \rfc{822}; \samp{name=value} is
also accepted. The optional values can contain format strings which also accepted. Note that leading whitespace is removed from values.
refer to other values in the same section, or values in a special The optional values can contain format strings which refer to other
values in the same section, or values in a special
\code{DEFAULT} section. Additional defaults can be provided upon \code{DEFAULT} section. Additional defaults can be provided upon
initialization and retrieval. Lines beginning with \character{\#} are initialization and retrieval. Lines beginning with \character{\#} or
ignored and may be used to provide comments. \character{;} are ignored and may be used to provide comments.
For example: For example:
\begin{verbatim} \begin{verbatim}
foodir: %(dir)s/whatever foodir: %(dir)s/whatever
dir=frob
\end{verbatim} \end{verbatim}
would resolve the \samp{\%(dir)s} to the value of dir. All reference would resolve the \samp{\%(dir)s} to the value of
expansions are done late, on demand. \samp{dir} (\samp{frob} in this case). All reference expansions are
done on demand.
Intrinsic defaults can be specified by passing them into the Default values can be specified by passing them into the
\class{ConfigParser} constructor as a dictionary. Additional defaults \class{ConfigParser} constructor as a dictionary. Additional defaults
may be passed into the \method{get} method which will override all may be passed into the \method{get()} method which will override all
others. others.
\begin{classdesc}{ConfigParser}{\optional{defaults}} \begin{classdesc}{ConfigParser}{\optional{defaults}}
@ -50,7 +55,9 @@ Exception raised when a specified section is not found.
\end{excdesc} \end{excdesc}
\begin{excdesc}{DuplicateSectionError} \begin{excdesc}{DuplicateSectionError}
Exception raised when mutliple sections with the same name are found. Exception raised when mutliple sections with the same name are found,
or if \method{add_section()} is called with the name of a section that
is already present.
\end{excdesc} \end{excdesc}
\begin{excdesc}{NoOptionError} \begin{excdesc}{NoOptionError}
@ -87,7 +94,14 @@ Return a dictionairy containing the instance-wide defaults.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}{sections}{} \begin{methoddesc}{sections}{}
Return a list of the sections available. Return a list of the sections available; \code{DEFAULT} is not
included in the list.
\end{methoddesc}
\begin{methoddesc}{add_section}{section}
Add a section named \var{section} to the instance. If a section by
the given name already exists, \exception{DuplicateSectionError} is
raised.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}{has_section}{section} \begin{methoddesc}{has_section}{section}
@ -123,6 +137,6 @@ A convenience method which coerces the \var{option} in the specified
\begin{methoddesc}{getboolean}{section, option} \begin{methoddesc}{getboolean}{section, option}
A convenience method which coerces the \var{option} in the specified A convenience method which coerces the \var{option} in the specified
\var{section} to a boolean value. Note that the only accepted values \var{section} to a boolean value. Note that the only accepted values
for the option are \code{0} and \code{1}, any others will raise for the option are \samp{0} and \samp{1}, any others will raise
\exception{ValueError}. \exception{ValueError}.
\end{methoddesc} \end{methoddesc}

View file

@ -195,7 +195,7 @@ Parse a query in the environment or from a file (default
Parse a query string given as a string argument (data of type Parse a query string given as a string argument (data of type
\mimetype{application/x-www-form-urlencoded}). Data are \mimetype{application/x-www-form-urlencoded}). Data are
returned as a dictionary. The dictionary keys are the unique query returned as a dictionary. The dictionary keys are the unique query
variable names and the values are lists of vales for each name. variable names and the values are lists of values for each name.
The optional argument \var{keep_blank_values} is The optional argument \var{keep_blank_values} is
a flag indicating whether blank values in a flag indicating whether blank values in

View file

@ -3,6 +3,7 @@
\declaremodule{standard}{CGIHTTPServer} \declaremodule{standard}{CGIHTTPServer}
\platform{Unix}
\sectionauthor{Moshe Zadka}{mzadka@geocities.com} \sectionauthor{Moshe Zadka}{mzadka@geocities.com}
\modulesynopsis{This module provides a request handler for HTTP servers \modulesynopsis{This module provides a request handler for HTTP servers
which can run CGI scripts.} which can run CGI scripts.}
@ -14,6 +15,9 @@ interface compatible with
from \class{SimpleHTTPServer.SimpleHTTPRequestHandler} but can also from \class{SimpleHTTPServer.SimpleHTTPRequestHandler} but can also
run CGI scripts. run CGI scripts.
\strong{Note:} This module is \UNIX{} dependent since it creates the
CGI process using \function{os.fork()} and \function{os.exec()}.
The \module{CGIHTTPServer} module defines the following class: The \module{CGIHTTPServer} module defines the following class:
\begin{classdesc}{CGIHTTPRequestHandler}{request, client_address, server} \begin{classdesc}{CGIHTTPRequestHandler}{request, client_address, server}

View file

@ -1,30 +1,173 @@
\section{\module{code} --- \section{\module{code} ---
Code object services.} Interpreter base classes}
\declaremodule{standard}{code} \declaremodule{standard}{code}
\modulesynopsis{Code object services.} \modulesynopsis{Base classes for interactive Python interpreters.}
The \code{code} module defines operations pertaining to Python code The \code{code} module provides facilities to implement
objects. It defines the following function: read-eval-print loops in Python. Two classes and convenience
functions are included which can be used to build applications which
provide an interactive interpreter prompt.
\begin{funcdesc}{compile_command}{source, \optional{filename\optional{, symbol}}} \begin{classdesc}{InteractiveInterpreter}{\optional{locals}}
This class deals with parsing and interpreter state (the user's
namespace); it does not deal with input buffering or prompting or
input file naming (the filename is always passed in explicitly).
The optional \var{locals} argument specifies the dictionary in
which code will be executed; it defaults to a newly created
dictionary with key \code{'__name__'} set to \code{'__console__'}
and key \code{'__doc__'} set to \code{None}.
\end{classdesc}
\begin{classdesc}{InteractiveConsole}{\optional{locals\optional{, filename}}}
Closely emulate the behavior of the interactive Python interpreter.
This class builds on \class{InteractiveInterpreter} and adds
prompting using the familiar \code{sys.ps1} and \code{sys.ps2}, and
input buffering.
\end{classdesc}
\begin{funcdesc}{interact}{\optional{banner\optional{,
readfunc\optional{, local}}}}
Convenience function to run a read-eval-print loop. This creates a
new instance of \class{InteractiveConsole} and sets \var{readfunc}
to be used as the \method{raw_input()} method, if provided. If
\var{local} is provided, it is passed to the
\class{InteractiveConsole} constructor for use as the default
namespace for the interpreter loop. The \method{interact()} method
of the instance is then run with \var{banner} passed as the banner
to use, if provided. The console object is discarded after use.
\end{funcdesc}
\begin{funcdesc}{compile_command}{source\optional{,
filename\optional{, symbol}}}
This function is useful for programs that want to emulate Python's This function is useful for programs that want to emulate Python's
interpreter main loop (a.k.a. the read-eval-print loop). The tricky interpreter main loop (a.k.a. the read-eval-print loop). The tricky
part is to determine when the user has entered an incomplete command part is to determine when the user has entered an incomplete command
that can be completed by entering more text (as opposed to a complete that can be completed by entering more text (as opposed to a
command or a syntax error). This function \emph{almost} always makes complete command or a syntax error). This function
the same decision as the real interpreter main loop. \emph{almost} always makes the same decision as the real interpreter
main loop.
Arguments: \var{source} is the source string; \var{filename} is the \var{source} is the source string; \var{filename} is the optional
optional filename from which source was read, defaulting to filename from which source was read, defaulting to \code{'<input>'};
\code{'<input>'}; and \var{symbol} is the optional grammar start and \var{symbol} is the optional grammar start symbol, which should
symbol, which should be either \code{'single'} (the default) or be either \code{'single'} (the default) or \code{'eval'}.
\code{'eval'}.
Return a code object (the same as \code{compile(\var{source}, Returns a code object (the same as \code{compile(\var{source},
\var{filename}, \var{symbol})}) if the command is complete and valid; \var{filename}, \var{symbol})}) if the command is complete and
return \code{None} if the command is incomplete; raise valid; \code{None} if the command is incomplete; raises
\exception{SyntaxError} if the command is a syntax error. \exception{SyntaxError} if the command is complete and contains a
syntax error, or raises \exception{OverflowError} if the command
includes a numeric constant which exceeds the range of the
appropriate numeric type.
\end{funcdesc} \end{funcdesc}
\subsection{Interactive Interpreter Objects
\label{interpreter-objects}}
\begin{methoddesc}{runsource}{source\optional{, filename\optional{, symbol}}}
Compile and run some source in the interpreter.
Arguments are the same as for \function{compile_command()}; the
default for \var{filename} is \code{'<input>'}, and for
\var{symbol} is \code{'single'}. One several things can happen:
\begin{itemize}
\item
The input is incorrect; \function{compile_command()} raised an
exception (\exception{SyntaxError} or \exception{OverflowError}). A
syntax traceback will be printed by calling the
\method{showsyntaxerror()} method. \method{runsource()} returns
\code{0}.
\item
The input is incomplete, and more input is required;
\function{compile_command()} returned \code{None}.
\method{runsource()} returns \code{1}.
\item
The input is complete; \function{compile_command()} returned a code
object. The code is executed by calling the \method{runcode()} (which
also handles run-time exceptions, except for \exception{SystemExit}).
\method{runsource()} returns \code{0}.
\end{itemize}
The return value can be used to decide whether to use
\code{sys.ps1} or \code{sys.ps2} to prompt the next line.
\end{methoddesc}
\begin{methoddesc}{runcode}{code}
Execute a code object.
When an exception occurs, \method{showtraceback()} is called to
display a traceback. All exceptions are caught except
\exception{SystemExit}, which is allowed to propogate.
A note about \exception{KeyboardInterrupt}: this exception may occur
elsewhere in this code, and may not always be caught. The caller
should be prepared to deal with it.
\end{methoddesc}
\begin{methoddesc}{showsyntaxerror}{\optional{filename}}
Display the syntax error that just occurred. This does not display
a stack trace because there isn't one for syntax errors.
If \var{filename} is given, it is stuffed into the exception instead
of the default filename provided by Python's parser, because it
always uses \code{'<string>'} when reading from a string.
The output is written by the \method{write()} method.
\end{methoddesc}
\begin{methoddesc}{showtraceback}{}
Display the exception that just occurred. We remove the first stack
item because it is within the interpreter object implementation.
The output is written by the \method{write()} method.
\end{methoddesc}
\begin{methoddesc}{write}{data}
Write a string to standard output. Derived classes should override
this to provide the appropriate output handling as needed.
\end{methoddesc}
\subsection{Interactive Console Objects
\label{console-objects}}
The \class{InteractiveConsole} class is a subclass of
\class{InteractiveInterpreter}, and so offers all the methods of the
interpreter objects as well as the following additions.
\begin{methoddesc}{interact}{\optional{banner}}
Closely emulate the interactive Python console.
The optional banner argument specify the banner to print before the
first interaction; by default it prints a banner similar to the one
printed by the standard Python interpreter, followed by the class
name of the console object in parentheses (so as not to confuse this
with the real interpreter -- since it's so close!).
\end{methoddesc}
\begin{methoddesc}{push}{line}
Push a line of source text to the interpreter.
The line should not have a trailing newline; it may have internal
newlines. The line is appended to a buffer and the interpreter's
\method{runsource()} method is called with the concatenated contents
of the buffer as source. If this indicates that the command was
executed or invalid, the buffer is reset; otherwise, the command is
incomplete, and the buffer is left as it was after the line was
appended. The return value is \code{1} if more input is required,
\code{0} if the line was dealt with in some way (this is the same as
\method{runsource()}).
\end{methoddesc}
\begin{methoddesc}{resetbuffer}{}
Remove any unhandled source text from the input buffer.
\end{methoddesc}
\begin{methoddesc}{raw_input}{\optional{prompt}}
Write a prompt and read a line. The returned line does not include
the trailing newline. When the user enters the \EOF{} key sequence,
\exception{EOFError} is raised. The base implementation uses the
built-in function \function{raw_input()}; a subclass may replace this
with a different implementation.
\end{methoddesc}

View file

@ -1,13 +1,14 @@
% LaTeXed from excellent doc-string.
\section{\module{codeop} --- \section{\module{codeop} ---
Compile Python code} Compile Python code}
% LaTeXed from excellent doc-string.
\declaremodule{standard}{codeop} \declaremodule{standard}{codeop}
\sectionauthor{Moshe Zadka}{mzadka@geocities.com} \sectionauthor{Moshe Zadka}{mzadka@geocities.com}
\modulesynopsis{Compile (possibly incomplete) Python code.} \modulesynopsis{Compile (possibly incomplete) Python code.}
The \module{codeop} module provides a function to compile Python code The \module{codeop} module provides a function to compile Python code
with hints on whether it certainly complete, possible complete or with hints on whether it is certainly complete, possibly complete or
definitely incomplete. This is used by the \refmodule{code} module definitely incomplete. This is used by the \refmodule{code} module
and should not normally be used directly. and should not normally be used directly.
@ -15,25 +16,22 @@ The \module{codeop} module defines the following function:
\begin{funcdesc}{compile_command} \begin{funcdesc}{compile_command}
{source\optional{, filename\optional{, symbol}}} {source\optional{, filename\optional{, symbol}}}
Tries to compile \var{source}, which should be a string of Python
Try to compile \var{source}, which should be a string of Python code and return a code object if \var{source} is valid
code. Return a code object if \var{source} is valid
Python code. In that case, the filename attribute of the code object Python code. In that case, the filename attribute of the code object
will be \var{filename}, which defaults to \code{'<input>'}. will be \var{filename}, which defaults to \code{'<input>'}.
Returns \code{None} if \var{source} is \emph{not} valid Python
Return \code{None} if \var{source} is \emph{not} valid Python
code, but is a prefix of valid Python code. code, but is a prefix of valid Python code.
Raise an exception if there is a problem with \var{source}: If there is a problem with \var{source}, an exception will be raised.
\begin{itemize} \exception{SyntaxError} is raised if there is invalid Python syntax,
\item \exception{SyntaxError} and \exception{OverflowError} if there is an invalid numeric
if there is invalid Python syntax. constant.
\item \exception{OverflowError}
if there is an invalid numeric constant.
\end{itemize}
The \var{symbol} argument means whether to compile it as a statement The \var{symbol} argument determines whether \var{source} is compiled
(\code{'single'}, the default) or as an expression (\code{'eval'}). as a statement (\code{'single'}, the default) or as an expression
(\code{'eval'}). Any other value will cause \exception{ValueError} to
be raised.
\strong{Caveat:} \strong{Caveat:}
It is possible (but not likely) that the parser stops parsing It is possible (but not likely) that the parser stops parsing

View file

@ -1,13 +1,9 @@
% Documentation based on module docstrings, by Fred L. Drake, Jr.
% <fdrake@acm.org>
\section{\module{compileall} --- \section{\module{compileall} ---
Byte-compile Python libraries.} Byte-compile Python libraries}
\declaremodule{standard}{compileall} \declaremodule{standard}{compileall}
\modulesynopsis{Tools for byte-compiling all Python source files in a \modulesynopsis{Tools for byte-compiling all Python source files in a
directory tree.} directory tree.}
This module provides some utility functions to support installing This module provides some utility functions to support installing
@ -20,19 +16,24 @@ compile Python sources in directories named on the command line or in
\code{sys.path}. \code{sys.path}.
\begin{funcdesc}{compile_dir}{dir\optional{, maxlevels\optional{, ddir}}} \begin{funcdesc}{compile_dir}{dir\optional{, maxlevels\optional{,
ddir\optional{, force}}}}
Recursively descend the directory tree named by \var{dir}, compiling Recursively descend the directory tree named by \var{dir}, compiling
all \file{.py} files along the way. The \var{maxlevels} parameter all \file{.py} files along the way. The \var{maxlevels} parameter
is used to limit the depth of the recursion; it defaults to is used to limit the depth of the recursion; it defaults to
\code{10}. If \var{ddir} is given, it is used as the base path from \code{10}. If \var{ddir} is given, it is used as the base path from
which the filenames used in error messages will be generated. which the filenames used in error messages will be generated. If
\var{force} is true, modules are re-compiled even if the timestamps
are up to date.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{compile_path}{\optional{skip_curdir\optional{, maxlevels}}} \begin{funcdesc}{compile_path}{\optional{skip_curdir\optional{,
maxlevels\optional{, force}}}}
Byte-compile all the \file{.py} files found along \code{sys.path}. Byte-compile all the \file{.py} files found along \code{sys.path}.
If \var{skip_curdir} is true (the default), the current directory is If \var{skip_curdir} is true (the default), the current directory is
not included in the search. The \var{maxlevels} parameter defaults not included in the search. The \var{maxlevels} and
to \code{0} and is passed to the \function{compile_dir()} function. \var{force} parameters default to \code{0} and are passed to the
\function{compile_dir()} function.
\end{funcdesc} \end{funcdesc}

View file

@ -1,29 +1,46 @@
\section{\module{crypt} --- \section{\module{crypt} ---
Function used to check \UNIX{} passwords} Function to check \UNIX{} passwords}
\declaremodule{builtin}{crypt} \declaremodule{builtin}{crypt}
\platform{Unix} \platform{Unix}
\modulesynopsis{The \cfunction{crypt()} function used to check \UNIX{} \modulesynopsis{The \cfunction{crypt()} function used to check
passwords.} \UNIX{} passwords.}
\moduleauthor{Steven D. Majewski}{sdm7g@virginia.edu} \moduleauthor{Steven D. Majewski}{sdm7g@virginia.edu}
\sectionauthor{Steven D. Majewski}{sdm7g@virginia.edu} \sectionauthor{Steven D. Majewski}{sdm7g@virginia.edu}
\sectionauthor{Peter Funk}{pf@artcom-gmbh.de}
This module implements an interface to the \manpage{crypt}{3} routine, This module implements an interface to the
which is a one-way hash function based upon a modified DES algorithm; \manpage{crypt}{3}\index{crypt(3)} routine, which is a one-way hash
see the \UNIX{} man page for further details. Possible uses include function based upon a modified DES\indexii{cipher}{DES} algorithm; see
the \UNIX{} man page for further details. Possible uses include
allowing Python scripts to accept typed passwords from the user, or allowing Python scripts to accept typed passwords from the user, or
attempting to crack \UNIX{} passwords with a dictionary. attempting to crack \UNIX{} passwords with a dictionary.
\index{crypt(3)}
\begin{funcdesc}{crypt}{word, salt} \begin{funcdesc}{crypt}{word, salt}
\var{word} will usually be a user's password. \var{salt} is a \var{word} will usually be a user's password as typed at a prompt or
2-character string which will be used to select one of 4096 variations in a graphical interface. \var{salt} is usually a random
of DES\indexii{cipher}{DES}. The characters in \var{salt} must be two-character string which will be used to perturb the DES algorithm
either \character{.}, \character{/}, or an alphanumeric character. in one of 4096 ways. The characters in \var{salt} must be in the
Returns the hashed password as a string, which will be composed of set \regexp{[./a-zA-Z0-9]}. Returns the hashed password as a
characters from the same alphabet as the salt. string, which will be composed of characters from the same alphabet
as the salt (the first two characters represent the salt itself).
\end{funcdesc} \end{funcdesc}
The module and documentation were written by Steve Majewski.
\index{Majewski, Steve} A simple example illustrating typical use:
\begin{verbatim}
import crypt, getpass, pwd
def login():
username = raw_input('Python login:')
cryptedpasswd = pwd.getpwnam(username)[1]
if cryptedpasswd:
if cryptedpasswd == 'x' or cryptedpasswd == '*':
raise "Sorry, currently no support for shadow passwords"
cleartext = getpass.getpass()
return crypt.crypt(cleartext, cryptedpasswd[:2]) == cryptedpasswd
else:
return 1
\end{verbatim}

View file

@ -11,18 +11,6 @@ and users are encouraged to do the same. The source code for those
exceptions is present in the standard library module exceptions is present in the standard library module
\module{exceptions}; this module never needs to be imported explicitly. \module{exceptions}; this module never needs to be imported explicitly.
For backward compatibility, when Python is invoked with the
\programopt{-X} option, most of the standard exceptions are
strings\footnote{
For forward-compatibility the new exceptions \exception{Exception},
\exception{LookupError}, \exception{ArithmeticError},
\exception{EnvironmentError}, and \exception{StandardError} are
tuples.
}. This option may be used to run code that breaks because of the
different semantics of class based exceptions. The
\programopt{-X} option will become obsolete in future Python versions,
so the recommended solution is to fix the code.
Two distinct string objects with the same value are considered different Two distinct string objects with the same value are considered different
exceptions. This is done to force programmers to use exception names exceptions. This is done to force programmers to use exception names
rather than their string value when specifying exception handlers. rather than their string value when specifying exception handlers.
@ -30,29 +18,27 @@ The string value of all built-in exceptions is their name, but this is
not a requirement for user-defined exceptions or exceptions defined by not a requirement for user-defined exceptions or exceptions defined by
library modules. library modules.
For class exceptions, in a \keyword{try} statement with an \keyword{except} For class exceptions, in a \keyword{try}\stindex{try} statement with
clause that mentions a particular class, that clause also handles an \keyword{except}\stindex{except} clause that mentions a particular
any exception classes derived from that class (but not exception class, that clause also handles any exception classes derived from
classes from which \emph{it} is derived). Two exception classes that class (but not exception classes from which \emph{it} is
that are not related via subclassing are never equivalent, even if derived). Two exception classes that are not related via subclassing
they have the same name. are never equivalent, even if they have the same name.
\stindex{try}
\stindex{except}
The built-in exceptions listed below can be generated by the The built-in exceptions listed below can be generated by the
interpreter or built-in functions. Except where mentioned, they have interpreter or built-in functions. Except where mentioned, they have
an ``associated value'' indicating the detailed cause of the error. an ``associated value'' indicating the detailed cause of the error.
This may be a string or a tuple containing several items of This may be a string or a tuple containing several items of
information (e.g., an error code and a string explaining the code). information (e.g., an error code and a string explaining the code).
The associated value is the second argument to the \keyword{raise} The associated value is the second argument to the
statement. For string exceptions, the associated value itself will be \keyword{raise}\stindex{raise} statement. For string exceptions, the
stored in the variable named as the second argument of the associated value itself will be stored in the variable named as the
\keyword{except} clause (if any). For class exceptions, that variable second argument of the \keyword{except} clause (if any). For class
receives the exception instance. If the exception class is derived exceptions, that variable receives the exception instance. If the
from the standard root class \exception{Exception}, the associated exception class is derived from the standard root class
value is present as the exception instance's \member{args} attribute, \exception{Exception}, the associated value is present as the
and possibly on other attributes as well. exception instance's \member{args} attribute, and possibly on other
\stindex{raise} attributes as well.
User code can raise built-in exceptions. This can be used to test an User code can raise built-in exceptions. This can be used to test an
exception handler or to report an error condition ``just like'' the exception handler or to report an error condition ``just like'' the
@ -65,6 +51,7 @@ inappropriate error.
The following exceptions are only used as base classes for other The following exceptions are only used as base classes for other
exceptions. When string-based standard exceptions are used, they exceptions. When string-based standard exceptions are used, they
are tuples containing the directly derived classes. are tuples containing the directly derived classes.
\strong{Note:} These will always be classes in Python 1.6.
\begin{excdesc}{Exception} \begin{excdesc}{Exception}
The root class for exceptions. All built-in exceptions are derived The root class for exceptions. All built-in exceptions are derived
@ -128,8 +115,8 @@ They are class objects, except when the \programopt{-X} option is used
to revert back to string-based standard exceptions. to revert back to string-based standard exceptions.
\begin{excdesc}{AssertionError} \begin{excdesc}{AssertionError}
Raised when an \keyword{assert} statement fails.
\stindex{assert} \stindex{assert}
Raised when an \keyword{assert} statement fails.
\end{excdesc} \end{excdesc}
\begin{excdesc}{AttributeError} \begin{excdesc}{AttributeError}

View file

@ -1,10 +1,10 @@
% Manual text by Jaap Vermeulen
\section{\module{fcntl} --- \section{\module{fcntl} ---
The \function{fcntl()} and \function{ioctl()} system calls} The \function{fcntl()} and \function{ioctl()} system calls}
\declaremodule{builtin}{fcntl} \declaremodule{builtin}{fcntl}
\platform{Unix} \platform{Unix}
\modulesynopsis{The \function{fcntl()} and \function{ioctl()} system calls.} \modulesynopsis{The \function{fcntl()} and \function{ioctl()} system calls.}
\sectionauthor{Jaap Vermeulen}{}
\indexii{UNIX@\UNIX{}}{file control} \indexii{UNIX@\UNIX{}}{file control}
\indexii{UNIX@\UNIX{}}{I/O control} \indexii{UNIX@\UNIX{}}{I/O control}

View file

@ -75,11 +75,13 @@ The following functions use the global state created by
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{isfirstline}{} \begin{funcdesc}{isfirstline}{}
Return true iff the line just read is the first line of its file. Returns true the line just read is the first line of its file,
otherwise returns false.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{isstdin}{} \begin{funcdesc}{isstdin}{}
Returns true iff the last line was read from \code{sys.stdin}. Returns true if the last line was read from \code{sys.stdin},
otherwise returns false.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{nextfile}{} \begin{funcdesc}{nextfile}{}

View file

@ -5,42 +5,45 @@
\modulesynopsis{\UNIX{} shell style filename pattern matching.} \modulesynopsis{\UNIX{} shell style filename pattern matching.}
\index{filenames!wildcard expansion}
This module provides support for \UNIX{} shell-style wildcards, which This module provides support for \UNIX{} shell-style wildcards, which
are \emph{not} the same as regular expressions (which are documented are \emph{not} the same as regular expressions (which are documented
in the \refmodule{re}\refstmodindex{re} module). The special in the \refmodule{re}\refstmodindex{re} module). The special
characters used in shell-style wildcards are: characters used in shell-style wildcards are:
\index{filenames!wildcard expansion}
\begin{list}{}{\leftmargin 0.5in \labelwidth 0.45in} \begin{tableii}{c|l}{code}{Pattern}{Meaning}
\item[\code{*}] matches everything \lineii{*}{matches everything}
\item[\code{?}] matches any single character \lineii{?}{matches any single character}
\item[\code{[}\var{seq}\code{]}] matches any character in \var{seq} \lineii{[\var{seq}]}{matches any character in \var{seq}}
\item[\code{[!}\var{seq}\code{]}] matches any character not in \var{seq} \lineii{[!\var{seq}]}{matches any character not in \var{seq}}
\end{list} \end{tableii}
Note that the filename separator (\code{'/'} on \UNIX{}) is \emph{not} Note that the filename separator (\code{'/'} on \UNIX{}) is \emph{not}
special to this module. See module special to this module. See module
\refmodule{glob}\refstmodindex{glob} for pathname expansion \refmodule{glob}\refstmodindex{glob} for pathname expansion
(\refmodule{glob} uses \function{fnmatch()} to match filename (\refmodule{glob} uses \function{fnmatch()} to match pathname
segments). segments). Similarly, filenames starting with a period are
not special for this module, and are matched by the \code{*} and
\code{?} patterns.
\begin{funcdesc}{fnmatch}{filename, pattern} \begin{funcdesc}{fnmatch}{filename, pattern}
Test whether the \var{filename} string matches the \var{pattern} Test whether the \var{filename} string matches the \var{pattern}
string, returning true or false. If the operating system is string, returning true or false. If the operating system is
case-insensitive, then both parameters will be normalized to all case-insensitive, then both parameters will be normalized to all
lower- or upper-case before the comparision is performed. If you lower- or upper-case before the comparison is performed. If you
require a case-sensitive comparision regardless of whether that's require a case-sensitive comparison regardless of whether that's
standard for your operating system, use \function{fnmatchcase()} standard for your operating system, use \function{fnmatchcase()}
instead. instead.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{fnmatchcase}{filename, pattern} \begin{funcdesc}{fnmatchcase}{filename, pattern}
Test whether \var{filename} matches \var{pattern}, returning true or Test whether \var{filename} matches \var{pattern}, returning true or
false; the comparision is case-sensitive. false; the comparison is case-sensitive.
\end{funcdesc} \end{funcdesc}
\begin{seealso} \begin{seealso}
\seemodule{glob}{Shell-style path expansion} \seemodule{glob}{\UNIX{} shell-style path expansion.}
\end{seealso} \end{seealso}

View file

@ -33,9 +33,10 @@ The return value consists of two elements: the first is a list of
program arguments left after the option list was stripped (this is a program arguments left after the option list was stripped (this is a
trailing slice of the first argument). trailing slice of the first argument).
Each option-and-value pair returned has the option as its first Each option-and-value pair returned has the option as its first
element, prefixed with a hyphen (e.g., \code{'-x'}), and the option element, prefixed with a hyphen for short options (e.g., \code{'-x'})
argument as its second element, or an empty string if the option has or two hyphens for long options (e.g., \code{'-}\code{-long-option'}),
no argument. and the option argument as its second element, or an empty string if
the option has no argument.
The options occur in the list in the same order in which they were The options occur in the list in the same order in which they were
found, thus allowing multiple occurrences. Long and short options may found, thus allowing multiple occurrences. Long and short options may
be mixed. be mixed.

View file

@ -11,10 +11,14 @@ It is available on all \UNIX{} versions.
Group database entries are reported as 4-tuples containing the Group database entries are reported as 4-tuples containing the
following items from the group database (see \code{<grp.h>}), in order: following items from the group database (see \code{<grp.h>}), in order:
\code{gr_name},
\code{gr_passwd}, \begin{tableiii}{r|l|l}{textrm}{Index}{Field}{Meaning}
\code{gr_gid}, \lineiii{0}{gr_name}{the name of the group}
\code{gr_mem}. \lineiii{1}{gr_passwd}{the (encrypted) group password; often empty}
\lineiii{2}{gr_gid}{the numerical group ID}
\lineiii{3}{gr_mem}{all the group member's user names}
\end{tableiii}
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
@ -34,3 +38,8 @@ Return the group database entry for the given group name.
\begin{funcdesc}{getgrall}{} \begin{funcdesc}{getgrall}{}
Return a list of all available group entries, in arbitrary order. Return a list of all available group entries, in arbitrary order.
\end{funcdesc} \end{funcdesc}
\begin{seealso}
\seemodule{pwd}{An interface to the user database, similar to this.}
\end{seealso}

View file

@ -1,6 +1,3 @@
% Based on HTML documentation by Piers Lauder <piers@staff.cs.usyd.edu.au>;
% converted by Fred L. Drake, Jr. <fdrake@acm.org>.
\section{\module{imaplib} --- \section{\module{imaplib} ---
IMAP4 protocol client} IMAP4 protocol client}
@ -9,6 +6,9 @@
\moduleauthor{Piers Lauder}{piers@staff.cs.usyd.edu.au} \moduleauthor{Piers Lauder}{piers@staff.cs.usyd.edu.au}
\sectionauthor{Piers Lauder}{piers@staff.cs.usyd.edu.au} \sectionauthor{Piers Lauder}{piers@staff.cs.usyd.edu.au}
% Based on HTML documentation by Piers Lauder <piers@staff.cs.usyd.edu.au>;
% converted by Fred L. Drake, Jr. <fdrake@acm.org>.
\indexii{IMAP4}{protocol} \indexii{IMAP4}{protocol}
This module defines a class, \class{IMAP4}, which encapsulates a This module defines a class, \class{IMAP4}, which encapsulates a

View file

@ -22,14 +22,15 @@ written in C and built in to the Python interpreter; others are
written in Python and imported in source form. Some modules provide written in Python and imported in source form. Some modules provide
interfaces that are highly specific to Python, like printing a stack interfaces that are highly specific to Python, like printing a stack
trace; some provide interfaces that are specific to particular trace; some provide interfaces that are specific to particular
operating systems, like socket I/O; others provide interfaces that are operating systems, such as access to specific hardware; others provide
interfaces that are
specific to a particular application domain, like the World-Wide Web. specific to a particular application domain, like the World-Wide Web.
Some modules are avaiable in all versions and ports of Python; others Some modules are avaiable in all versions and ports of Python; others
are only available when the underlying system supports or requires are only available when the underlying system supports or requires
them; yet others are available only when a particular configuration them; yet others are available only when a particular configuration
option was chosen at the time when Python was compiled and installed. option was chosen at the time when Python was compiled and installed.
This manual is organized ``from the inside out'': it first describes This manual is organized ``from the inside out:'' it first describes
the built-in data types, then the built-in functions and exceptions, the built-in data types, then the built-in functions and exceptions,
and finally the modules, grouped in chapters of related modules. The and finally the modules, grouped in chapters of related modules. The
ordering of the chapters as well as the ordering of the modules within ordering of the chapters as well as the ordering of the modules within

View file

@ -17,7 +17,9 @@ The \module{linecache} module defines the following functions:
\begin{funcdesc}{getline}{filename, lineno} \begin{funcdesc}{getline}{filename, lineno}
Get line \var{lineno} from file named \var{filename}. This function Get line \var{lineno} from file named \var{filename}. This function
will never throw an exception --- it will return \code{''} on errors. will never throw an exception --- it will return \code{''} on errors
(the terminating newline character will be included for lines that are
found).
If a file named \var{filename} is not found, the function will look If a file named \var{filename} is not found, the function will look
for it in the module\indexiii{module}{search}{path} search path, for it in the module\indexiii{module}{search}{path} search path,
@ -25,9 +27,8 @@ for it in the module\indexiii{module}{search}{path} search path,
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{clearcache}{} \begin{funcdesc}{clearcache}{}
Clear the cache. Use this function if you know that you do not need Clear the cache. Use this function if you no longer need lines from
to read lines from many of files you already read from using this files previously read using \function{getline()}.
module.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{checkcache}{} \begin{funcdesc}{checkcache}{}

View file

@ -62,7 +62,8 @@ The module defines these functions:
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
\code{sys.stdout} or returned by \function{open()} or \code{sys.stdout} or returned by \function{open()} or
\function{posix.popen()}. \function{posix.popen()}. It must be opened in binary mode
(\code{'wb'} or \code{'w+b'}).
If the value has (or contains an object that has) an unsupported type, If the value has (or contains an object that has) an unsupported type,
a \exception{ValueError} exception is raised --- but garbage data a \exception{ValueError} exception is raised --- but garbage data
@ -73,7 +74,8 @@ The module defines these functions:
\begin{funcdesc}{load}{file} \begin{funcdesc}{load}{file}
Read one value from the open file and return it. If no valid value Read one value from the open file and return it. If no valid value
is read, raise \exception{EOFError}, \exception{ValueError} or is read, raise \exception{EOFError}, \exception{ValueError} or
\exception{TypeError}. The file must be an open file object. \exception{TypeError}. The file must be an open file object opened
in binary mode (\code{'rb'} or \code{'r+b'}).
\strong{Warning:} If an object containing an unsupported type was \strong{Warning:} If an object containing an unsupported type was
marshalled with \function{dump()}, \function{load()} will substitute marshalled with \function{dump()}, \function{load()} will substitute

View file

@ -5,7 +5,19 @@
\modulesynopsis{Mathematical functions (\function{sin()} etc.).} \modulesynopsis{Mathematical functions (\function{sin()} etc.).}
This module is always available. It provides access to the This module is always available. It provides access to the
mathematical functions defined by the C standard. They are: mathematical functions defined by the C standard.
These functions cannot be used with complex numbers; use the functions
of the same name from the \refmodule{cmath} module if you require
support for complex numbers. The distinction between functions which
support complex numbers and those which don't is made since most users
do not want to learn quite as much mathematics as required to
understand complex numbers. Receiving an exception instead of a
complex result allows earlier detection of the unexpected complex
number used as a parameter, so that the programmer can determine how
and why it was generated in the first place.
The following functions provided by this module:
\begin{funcdesc}{acos}{x} \begin{funcdesc}{acos}{x}
Return the arc cosine of \var{x}. Return the arc cosine of \var{x}.

View file

@ -1,9 +1,9 @@
% LaTeX'ized from the comments in the module by Skip Montanaro
% <skip@mojam.com>.
\section{\module{mhlib} --- \section{\module{mhlib} ---
Access to MH mailboxes} Access to MH mailboxes}
% LaTeX'ized from the comments in the module by Skip Montanaro
% <skip@mojam.com>.
\declaremodule{standard}{mhlib} \declaremodule{standard}{mhlib}
\modulesynopsis{Manipulate MH mailboxes from Python.} \modulesynopsis{Manipulate MH mailboxes from Python.}

View file

@ -2,7 +2,7 @@
Tools for parsing MIME messages} Tools for parsing MIME messages}
\declaremodule{standard}{mimetools} \declaremodule{standard}{mimetools}
\modulesynopsis{Tools for parsing MIME style message bodies.} \modulesynopsis{Tools for parsing MIME-style message bodies.}
This module defines a subclass of the \class{rfc822.Message} class and This module defines a subclass of the \class{rfc822.Message} class and
@ -38,7 +38,7 @@ Valid values for \var{encoding} are the same as for \method{decode()}.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{copyliteral}{input, output} \begin{funcdesc}{copyliteral}{input, output}
Read lines until \EOF{} from open file \var{input} and write them to Read lines from open file \var{input} until \EOF{} and write them to
open file \var{output}. open file \var{output}.
\end{funcdesc} \end{funcdesc}
@ -48,6 +48,12 @@ open file \var{output}. The block size is currently fixed at 8192.
\end{funcdesc} \end{funcdesc}
\begin{seealso}
\seemodule{rfc822}{Provides the base class for
\class{mimetools.Message}.}
\end{seealso}
\subsection{Additional Methods of Message objects} \subsection{Additional Methods of Message objects}
\nodename{mimetools.Message Methods} \nodename{mimetools.Message Methods}

View file

@ -1,7 +1,3 @@
% This document section was written by Fred L. Drake, Jr.
% <fdrake@acm.org>, based in part on original docstrings in the
% mimetypes module.
\section{\module{mimetypes} --- \section{\module{mimetypes} ---
Map filenames to MIME types} Map filenames to MIME types}

View file

@ -54,7 +54,7 @@ insert at the start.
boundary\optional{, plist\optional{, prefix}}}} boundary\optional{, plist\optional{, prefix}}}}
Returns a file-like object which can be used to write to the Returns a file-like object which can be used to write to the
body of the message. Additionally, this method initializes the body of the message. Additionally, this method initializes the
multi-part code, where \var{subtype} provides the mutlipart subtype, multi-part code, where \var{subtype} provides the multipart subtype,
\var{boundary} may provide a user-defined boundary specification, and \var{boundary} may provide a user-defined boundary specification, and
\var{plist} provides optional parameters for the subtype. \var{plist} provides optional parameters for the subtype.
\var{prefix} functions as in \method{startbody()}. Subparts should be \var{prefix} functions as in \method{startbody()}. Subparts should be

View file

@ -1,5 +1,3 @@
% Module and documentation by Eric S. Raymond, 21 Dec 1998
\section{\module{netrc} --- \section{\module{netrc} ---
netrc file processing} netrc file processing}
@ -45,7 +43,7 @@ Dump the class data as a string in the format of a netrc file.
Instances of \class{netrc} have public instance variables: Instances of \class{netrc} have public instance variables:
\begin{memberdesc}{hosts} \begin{memberdesc}{hosts}
Dictionmary mapping host names to \code{(\var{login}, \var{account}, Dictionary mapping host names to \code{(\var{login}, \var{account},
\var{password})} tuples. The `default' entry, if any, is represented \var{password})} tuples. The `default' entry, if any, is represented
as a pseudo-host by that name. as a pseudo-host by that name.
\end{memberdesc} \end{memberdesc}

View file

@ -5,7 +5,7 @@
\platform{UNIX} \platform{UNIX}
\moduleauthor{Fred Gansevles}{Fred.Gansevles@cs.utwente.nl} \moduleauthor{Fred Gansevles}{Fred.Gansevles@cs.utwente.nl}
\sectionauthor{Moshe Zadka}{mzadka@geocities.com} \sectionauthor{Moshe Zadka}{mzadka@geocities.com}
\modulesynopsis{Interface to Sun's N.I.S. (a.k.a. Yellow Pages) library.} \modulesynopsis{Interface to Sun's NIS (a.k.a. Yellow Pages) library.}
The \module{nis} module gives a thin wrapper around the NIS library, useful The \module{nis} module gives a thin wrapper around the NIS library, useful
for central administration of several hosts. for central administration of several hosts.
@ -23,8 +23,6 @@ Return value is an arbitary array of bytes (i.e., may contain \code{NULL}
and other joys). and other joys).
Note that \var{mapname} is first checked if it is an alias to another name. Note that \var{mapname} is first checked if it is an alias to another name.
XXX Describe list of all aliases? Internal for the C code, so
I'm not sure it's a good idea.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{cat}{mapname} \begin{funcdesc}{cat}{mapname}

View file

@ -262,7 +262,9 @@ argument to the built-in \function{open()} function. The exit status of
the command (encoded in the format specified for \function{wait()}) is the command (encoded in the format specified for \function{wait()}) is
available as the return value of the \method{close()} method of the file available as the return value of the \method{close()} method of the file
object, except that when the exit status is zero (termination without object, except that when the exit status is zero (termination without
errors), \code{None} is returned. errors), \code{None} is returned. \strong{Note:} This function
behaves unreliably under Windows due to the native implementation of
\cfunction{popen()}.
Availability: \UNIX{}, Windows. Availability: \UNIX{}, Windows.
\end{funcdesc} \end{funcdesc}
@ -443,12 +445,35 @@ Availability: Macintosh, \UNIX{}, Windows.
\subsection{Files and Directories \label{os-file-dir}} \subsection{Files and Directories \label{os-file-dir}}
\begin{funcdesc}{access}{path, mode} \begin{funcdesc}{access}{path, mode}
Check read/write/execute permissions for this process or extance of file Check read/write/execute permissions for this process or existence of
\var{path}. Return \code{1} if access is granted, \code{0} if not. file \var{path}. \var{mode} should be \constant{F_OK} to test the
See the \UNIX{} manual for the semantics. existence of \var{path}, or it can be the inclusive OR of one or more
of \constant{R_OK}, \constant{W_OK}, and \constant{X_OK} to test
permissions. Return \code{1} if access is allowed, \code{0} if not.
See the \UNIX{} man page \manpage{access}{2} for more information.
Availability: \UNIX{}. Availability: \UNIX{}.
\end{funcdesc} \end{funcdesc}
\begin{datadesc}{F_OK}
Value to pass as the \var{mode} parameter of \function{access()} to
test the existence of \var{path}.
\end{datadesc}
\begin{datadesc}{R_OK}
Value to include in the \var{mode} parameter of \function{access()}
to test the readability of \var{path}.
\end{datadesc}
\begin{datadesc}{W_OK}
Value to include in the \var{mode} parameter of \function{access()}
to test the writability of \var{path}.
\end{datadesc}
\begin{datadesc}{X_OK}
Value to include in the \var{mode} parameter of \function{access()}
to determine if \var{path} can be executed.
\end{datadesc}
\begin{funcdesc}{chdir}{path} \begin{funcdesc}{chdir}{path}
\index{directory!changing} \index{directory!changing}
Change the current working directory to \var{path}. Change the current working directory to \var{path}.
@ -877,9 +902,10 @@ process status is available immediately.
Availability: \UNIX{}. Availability: \UNIX{}.
\end{datadesc} \end{datadesc}
The following functions take a process stats code as returned by The following functions take a process status code as returned by
\function{waitpid()} as a parameter. They may be used to determine \function{system()}, \function{wait()}, or \function{waitpid()} as a
the disposition of a process. parameter. They may be used to determine the disposition of a
process.
\begin{funcdesc}{WIFSTOPPED}{status} \begin{funcdesc}{WIFSTOPPED}{status}
Return true if the process has been stopped. Return true if the process has been stopped.

View file

@ -1,5 +1,6 @@
% libparser.tex \section{\module{parser} ---
% Access Python parse trees}
% Copyright 1995 Virginia Polytechnic Institute and State University % Copyright 1995 Virginia Polytechnic Institute and State University
% and Fred L. Drake, Jr. This copyright notice must be distributed on % and Fred L. Drake, Jr. This copyright notice must be distributed on
% all copies, but this document otherwise may be distributed as part % all copies, but this document otherwise may be distributed as part
@ -7,10 +8,6 @@
% in any representation, either on paper or electronically. This % in any representation, either on paper or electronically. This
% restriction does not affect other elements in a distributed package % restriction does not affect other elements in a distributed package
% in any way. % in any way.
%
\section{\module{parser} ---
Access Python parse trees}
\declaremodule{builtin}{parser} \declaremodule{builtin}{parser}
\modulesynopsis{Access parse trees for Python source code.} \modulesynopsis{Access parse trees for Python source code.}
@ -166,7 +163,7 @@ extracted with or without line numbering information.
\begin{funcdesc}{ast2list}{ast\optional{, line_info}} \begin{funcdesc}{ast2list}{ast\optional{, line_info}}
This function accepts an AST object from the caller in This function accepts an AST object from the caller in
\var{ast} and returns a Python list representing the \var{ast} and returns a Python list representing the
equivelent parse tree. The resulting list representation can be used equivalent parse tree. The resulting list representation can be used
for inspection or the creation of a new parse tree in list form. This for inspection or the creation of a new parse tree in list form. This
function does not fail so long as memory is available to build the function does not fail so long as memory is available to build the
list representation. If the parse tree will only be used for list representation. If the parse tree will only be used for
@ -185,7 +182,7 @@ omitted if the flag is false or omitted.
\begin{funcdesc}{ast2tuple}{ast\optional{, line_info}} \begin{funcdesc}{ast2tuple}{ast\optional{, line_info}}
This function accepts an AST object from the caller in This function accepts an AST object from the caller in
\var{ast} and returns a Python tuple representing the \var{ast} and returns a Python tuple representing the
equivelent parse tree. Other than returning a tuple instead of a equivalent parse tree. Other than returning a tuple instead of a
list, this function is identical to \function{ast2list()}. list, this function is identical to \function{ast2list()}.
If \var{line_info} is true, line number information will be If \var{line_info} is true, line number information will be
@ -238,7 +235,7 @@ identical to those created by the built-in
\begin{funcdesc}{issuite}{ast} \begin{funcdesc}{issuite}{ast}
This function mirrors \function{isexpr()} in that it reports whether an This function mirrors \function{isexpr()} in that it reports whether an
AST object represents an \code{'exec'} form, commonly known as a AST object represents an \code{'exec'} form, commonly known as a
``suite.'' It is not safe to assume that this function is equivelent ``suite.'' It is not safe to assume that this function is equivalent
to \samp{not isexpr(\var{ast})}, as additional syntactic fragments may to \samp{not isexpr(\var{ast})}, as additional syntactic fragments may
be supported in the future. be supported in the future.
\end{funcdesc} \end{funcdesc}
@ -274,9 +271,6 @@ to the descriptions of each function for detailed information.
\subsection{AST Objects \label{AST Objects}} \subsection{AST Objects \label{AST Objects}}
AST objects returned by \function{expr()}, \function{suite()} and
\function{sequence2ast()} have no methods of their own.
Ordered and equality comparisons are supported between AST objects. Ordered and equality comparisons are supported between AST objects.
Pickling of AST objects (using the \refmodule{pickle} module) is also Pickling of AST objects (using the \refmodule{pickle} module) is also
supported. supported.
@ -326,7 +320,7 @@ discovery.
While many useful operations may take place between parsing and While many useful operations may take place between parsing and
bytecode generation, the simplest operation is to do nothing. For bytecode generation, the simplest operation is to do nothing. For
this purpose, using the \module{parser} module to produce an this purpose, using the \module{parser} module to produce an
intermediate data structure is equivelent to the code intermediate data structure is equivalent to the code
\begin{verbatim} \begin{verbatim}
>>> code = compile('a + 5', 'eval') >>> code = compile('a + 5', 'eval')
@ -335,7 +329,7 @@ intermediate data structure is equivelent to the code
10 10
\end{verbatim} \end{verbatim}
The equivelent operation using the \module{parser} module is somewhat The equivalent operation using the \module{parser} module is somewhat
longer, and allows the intermediate internal parse tree to be retained longer, and allows the intermediate internal parse tree to be retained
as an AST object: as an AST object:
@ -474,7 +468,7 @@ structure.
By replacing the actual docstring with something to signify a variable By replacing the actual docstring with something to signify a variable
component of the tree, we allow a simple pattern matching approach to component of the tree, we allow a simple pattern matching approach to
check any given subtree for equivelence to the general pattern for check any given subtree for equivalence to the general pattern for
docstrings. Since the example demonstrates information extraction, we docstrings. Since the example demonstrates information extraction, we
can safely require that the tree be in tuple form rather than list can safely require that the tree be in tuple form rather than list
form, allowing a simple variable representation to be form, allowing a simple variable representation to be

View file

@ -3,6 +3,7 @@
\declaremodule{standard}{pickle} \declaremodule{standard}{pickle}
\modulesynopsis{Convert Python objects to streams of bytes and back.} \modulesynopsis{Convert Python objects to streams of bytes and back.}
% Substantial improvements by Jim Kerr <jbkerr@sr.hp.com>.
\index{persistency} \index{persistency}
\indexii{persistent}{objects} \indexii{persistent}{objects}
@ -37,17 +38,29 @@ interface except that \class{Pickler} and \class{Unpickler} are
factory functions, not classes (so they cannot be used as base classes factory functions, not classes (so they cannot be used as base classes
for inheritance). for inheritance).
Unlike the built-in module \refmodule{marshal}\refbimodindex{marshal}, Although the \module{pickle} module can use the built-in module
\module{pickle} handles the following correctly: \refmodule{marshal}\refbimodindex{marshal} internally, it differs from
\refmodule{marshal} in the way it handles certain kinds of data:
\begin{itemize} \begin{itemize}
\item recursive objects (objects containing references to themselves) \item Recursive objects (objects containing references to themselves):
\module{pickle} keeps track of the objects it has already
serialized, so later references to the same object won't be
serialized again. (The \refmodule{marshal} module breaks for
this.)
\item object sharing (references to the same object in different places) \item Object sharing (references to the same object in different
places): This is similar to self-referencing objects;
\module{pickle} stores the object once, and ensures that all
other references point to the master copy. Shared objects
remain shared, which can be very important for mutable objects.
\item user-defined classes and their instances \item User-defined classes and their instances: \refmodule{marshal}
does not support these at all, but \module{pickle} can save
and restore class instances transparently. The class definition
must be importable and live in the same module as when the
object was stored.
\end{itemize} \end{itemize}
@ -177,16 +190,15 @@ x = pickle.load(f)
\end{verbatim} \end{verbatim}
The \class{Pickler} class only calls the method \code{f.write()} with a The \class{Pickler} class only calls the method \code{f.write()} with a
\withsubitem{(class in pickle)}{ \withsubitem{(class in pickle)}{\ttindex{Unpickler}\ttindex{Pickler}}
\ttindex{Unpickler}\ttindex{Pickler}}
string argument. The \class{Unpickler} calls the methods \code{f.read()} string argument. The \class{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.
The constructor for the \class{Pickler} class has an optional second The constructor for the \class{Pickler} class has an optional second
argument, \var{bin}. If this is present and nonzero, the binary argument, \var{bin}. If this is present and true, the binary
pickle format is used; if it is zero or absent, the (less efficient, pickle format is used; if it is absent or false, the (less efficient,
but backwards compatible) text pickle format is used. The but backwards compatible) text pickle format is used. The
\class{Unpickler} class does not have an argument to distinguish \class{Unpickler} class does not have an argument to distinguish
between binary and text pickle formats; it accepts either format. between binary and text pickle formats; it accepts either format.
@ -203,6 +215,11 @@ 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 functions defined at the top level of a module (by name
reference, not storage of the implementation)
\item built-in functions
\item classes that are defined at the top level in a module \item classes that are defined at the top level in a module
\item instances of such classes whose \member{__dict__} or \item instances of such classes whose \member{__dict__} or
@ -276,11 +293,80 @@ This exception is raised when an unpicklable object is passed to
\end{seealso} \end{seealso}
\subsection{Example \label{pickle-example}}
Here's a simple example of how to modify pickling behavior for a
class. The \class{TextReader} class opens a text file, and returns
the line number and line contents each time its \method{readline()}
method is called. If a \class{TextReader} instance is pickled, all
attributes \emph{except} the file object member are saved. When the
instance is unpickled, the file is reopened, and reading resumes from
the last location. The \method{__setstate__()} and
\method{__getstate__()} methods are used to implement this behavior.
\begin{verbatim}
# illustrate __setstate__ and __getstate__ methods
# used in pickling.
class TextReader:
"Print and number lines in a text file."
def __init__(self,file):
self.file = file
self.fh = open(file,'r')
self.lineno = 0
def readline(self):
self.lineno = self.lineno + 1
line = self.fh.readline()
if not line:
return None
return "%d: %s" % (self.lineno,line[:-1])
# return data representation for pickled object
def __getstate__(self):
odict = self.__dict__ # get attribute dictionary
del odict['fh'] # remove filehandle entry
return odict
# restore object state from data representation generated
# by __getstate__
def __setstate__(self,dict):
fh = open(dict['file']) # reopen file
count = dict['lineno'] # read from file...
while count: # until line count is restored
fh.readline()
count = count - 1
dict['fh'] = fh # create filehandle entry
self.__dict__ = dict # make dict our attribute dictionary
\end{verbatim}
A sample usage might be something like this:
\begin{verbatim}
>>> import TextReader
>>> obj = TextReader.TextReader("TextReader.py")
>>> obj.readline()
'1: #!/usr/local/bin/python'
>>> # (more invocations of obj.readline() here)
... obj.readline()
'7: class TextReader:'
>>> import pickle
>>> pickle.dump(obj,open('save.p','w'))
(start another Python session)
>>> import pickle
>>> reader = pickle.load(open('save.p'))
>>> reader.readline()
'8: "Print and number lines in a text file."'
\end{verbatim}
\section{\module{cPickle} --- \section{\module{cPickle} ---
Alternate implementation of \module{pickle}} Alternate implementation of \module{pickle}}
\declaremodule{builtin}{cPickle} \declaremodule{builtin}{cPickle}
\modulesynopsis{Faster version of \module{pickle}, but not subclassable.} \modulesynopsis{Faster version of \refmodule{pickle}, but not subclassable.}
\moduleauthor{Jim Fulton}{jfulton@digicool.com} \moduleauthor{Jim Fulton}{jfulton@digicool.com}
\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org} \sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}

View file

@ -1,14 +1,14 @@
%By Andrew T. Csillag
%Even though I put it into LaTeX, I cannot really claim that I wrote
%it since I just stole most of it from the poplib.py source code and
%the imaplib ``chapter''.
\section{\module{poplib} --- \section{\module{poplib} ---
POP3 protocol client} POP3 protocol client}
\declaremodule{standard}{poplib} \declaremodule{standard}{poplib}
\modulesynopsis{POP3 protocol client (requires sockets).} \modulesynopsis{POP3 protocol client (requires sockets).}
%By Andrew T. Csillag
%Even though I put it into LaTeX, I cannot really claim that I wrote
%it since I just stole most of it from the poplib.py source code and
%the imaplib ``chapter''.
\indexii{POP3}{protocol} \indexii{POP3}{protocol}
This module defines a class, \class{POP3}, which encapsulates a This module defines a class, \class{POP3}, which encapsulates a

View file

@ -127,8 +127,8 @@ slashes.
Normalize a pathname. This collapses redundant separators and Normalize a pathname. This collapses redundant separators and
up-level references, e.g. \code{A//B}, \code{A/./B} and up-level references, e.g. \code{A//B}, \code{A/./B} and
\code{A/foo/../B} all become \code{A/B}. It does not normalize the \code{A/foo/../B} all become \code{A/B}. It does not normalize the
case (use \function{normcase()} for that). On Windows, it does case (use \function{normcase()} for that). On Windows, it converts
converts forward slashes to backward slashes. forward slashes to backward slashes.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{samefile}{path1, path2} \begin{funcdesc}{samefile}{path1, path2}

View file

@ -1,11 +1,7 @@
%%%% LaTeX'ed and enhanced from comments in file
%%%% Skipped some functions which seemed to be for private
%%%% usage (decision debatable).
\section{\module{pty} --- \section{\module{pty} ---
Pseudo-terminal utilities} Pseudo-terminal utilities}
\declaremodule{standard}{pty} \declaremodule{standard}{pty}
\platform{IRIX, Linux} %XXX Is that the right way??? \platform{IRIX, Linux}
\modulesynopsis{Pseudo-Terminal Handling for SGI and Linux.} \modulesynopsis{Pseudo-Terminal Handling for SGI and Linux.}
\moduleauthor{Steen Lumholt}{} \moduleauthor{Steen Lumholt}{}
\sectionauthor{Moshe Zadka}{mzadka@geocities.com} \sectionauthor{Moshe Zadka}{mzadka@geocities.com}

View file

@ -5,21 +5,33 @@
\platform{Unix} \platform{Unix}
\modulesynopsis{The password database (\function{getpwnam()} and friends).} \modulesynopsis{The password database (\function{getpwnam()} and friends).}
This module provides access to the \UNIX{} password database. This module provides access to the \UNIX{} user account and password
It is available on all \UNIX{} versions. database. It is available on all \UNIX{} versions.
Password database entries are reported as 7-tuples containing the Password database entries are reported as 7-tuples containing the
following items from the password database (see \code{<pwd.h>}), in order: following items from the password database (see \code{<pwd.h>}), in order:
\code{pw_name},
\code{pw_passwd}, \begin{tableiii}{r|l|l}{textrm}{Index}{Field}{Meaning}
\code{pw_uid}, \lineiii{0}{\code{pw_name}}{Login name}
\code{pw_gid}, \lineiii{1}{\code{pw_passwd}}{Optional encrypted password}
\code{pw_gecos}, \lineiii{2}{\code{pw_uid}}{Numerical user ID}
\code{pw_dir}, \lineiii{3}{\code{pw_gid}}{Numerical group ID}
\code{pw_shell}. \lineiii{4}{\code{pw_gecos}}{User name or comment field}
\lineiii{5}{\code{pw_dir}}{User home directory}
\lineiii{6}{\code{pw_shell}}{User command interpreter}
\end{tableiii}
The uid and gid items are integers, all others are strings. The uid and gid items are integers, all others are strings.
\exception{KeyError} is raised if the entry asked for cannot be found. \exception{KeyError} is raised if the entry asked for cannot be found.
\strong{Note:} In traditional \UNIX{} the field \code{pw_passwd} usually
contains a password encrypted with a DES derived algorithm (see module
\refmodule{crypt}\refbimodindex{crypt}). However most modern unices
use a so-called \emph{shadow password} system. On those unices the
field \code{pw_passwd} only contains a asterisk (\code{'*'}) or the
letter \character{x} where the encrypted password is stored in a file
\file{/etc/shadow} which is not world readable.
It defines the following items: It defines the following items:
\begin{funcdesc}{getpwuid}{uid} \begin{funcdesc}{getpwuid}{uid}
@ -33,3 +45,8 @@ Return the password database entry for the given user name.
\begin{funcdesc}{getpwall}{} \begin{funcdesc}{getpwall}{}
Return a list of all available password database entries, in arbitrary order. Return a list of all available password database entries, in arbitrary order.
\end{funcdesc} \end{funcdesc}
\begin{seealso}
\seemodule{grp}{An interface to the group database, similar to this.}
\end{seealso}

View file

@ -1,9 +1,9 @@
\section{\module{py_compile} ---
Compile Python source files}
% Documentation based on module docstrings, by Fred L. Drake, Jr. % Documentation based on module docstrings, by Fred L. Drake, Jr.
% <fdrake@acm.org> % <fdrake@acm.org>
\section{\module{py_compile} ---
Compile Python source files.}
\declaremodule[pycompile]{standard}{py_compile} \declaremodule[pycompile]{standard}{py_compile}
\modulesynopsis{Compile Python source files to byte-code files.} \modulesynopsis{Compile Python source files to byte-code files.}

View file

@ -32,7 +32,7 @@ empty or locked.
\begin{excdesc}{Full} \begin{excdesc}{Full}
Exception raised when non-blocking \method{put()} (or Exception raised when non-blocking \method{put()} (or
\method{get_nowait()}) is called on a \class{Queue} object which is \method{put_nowait()}) is called on a \class{Queue} object which is
full or locked. full or locked.
\end{excdesc} \end{excdesc}

View file

@ -12,22 +12,25 @@ or Gaussian, lognormal, negative exponential, gamma, and beta
distributions. For generating distribution of angles, the circular distributions. For generating distribution of angles, the circular
uniform and von Mises distributions are available. uniform and von Mises distributions are available.
The module exports the following functions, which are exactly
equivalent to those in the \refmodule{whrandom} module:
\function{choice()}, \function{randint()}, \function{random()} and
\function{uniform()}. See the documentation for the
\refmodule{whrandom} module for these functions.
The following functions specific to the \module{random} module are also The \module{random} module supports the \emph{Random Number
defined, and all return real values. Function parameters are named Generator} interface, described in section \ref{rng-objects}. This
after the corresponding variables in the distribution's equation, as interface of the module, as well as the distribution-specific
used in common mathematical practice; most of these equations can be functions described below, all use the pseudo-random generator
found in any statistics text. provided by the \refmodule{whrandom} module.
The following functions are defined to support specific distributions,
and all return real values. Function parameters are named after the
corresponding variables in the distribution's equation, as used in
common mathematical practice; most of these equations can be found in
any statistics text. These are expected to become part of the Random
Number Generator interface in a future release.
\begin{funcdesc}{betavariate}{alpha, beta} \begin{funcdesc}{betavariate}{alpha, beta}
Beta distribution. Conditions on the parameters are Beta distribution. Conditions on the parameters are
\code{\var{alpha} >- 1} and \code{\var{beta} > -1}. \code{\var{alpha} > -1} and \code{\var{beta} > -1}.
Returned values will range between 0 and 1. Returned values range between 0 and 1.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{cunifvariate}{mean, arc} \begin{funcdesc}{cunifvariate}{mean, arc}
@ -59,8 +62,8 @@ standard deviation. This is slightly faster than the
\begin{funcdesc}{lognormvariate}{mu, sigma} \begin{funcdesc}{lognormvariate}{mu, sigma}
Log normal distribution. If you take the natural logarithm of this Log normal distribution. If you take the natural logarithm of this
distribution, you'll get a normal distribution with mean \var{mu} and distribution, you'll get a normal distribution with mean \var{mu} and
standard deviation \var{sigma}. \var{mu} can have any value, and \var{sigma} standard deviation \var{sigma}. \var{mu} can have any value, and
must be greater than zero. \var{sigma} must be greater than zero.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{normalvariate}{mu, sigma} \begin{funcdesc}{normalvariate}{mu, sigma}
@ -86,5 +89,40 @@ Weibull distribution. \var{alpha} is the scale parameter and
\end{funcdesc} \end{funcdesc}
\begin{seealso} \begin{seealso}
\seemodule{whrandom}{the standard Python random number generator} \seemodule{whrandom}{The standard Python random number generator.}
\end{seealso} \end{seealso}
\subsection{The Random Number Generator Interface
\label{rng-objects}}
% XXX This *must* be updated before a future release!
The \dfn{Random Number Generator} interface describes the methods
which are available for all random number generators. This will be
enhanced in future releases of Python.
In this release of Python, the modules \refmodule{random},
\refmodule{whrandom}, and instances of the
\class{whrandom.whrandom} class all conform to this interface.
\begin{funcdesc}{choice}{seq}
Chooses a random element from the non-empty sequence \var{seq} and
returns it.
\end{funcdesc}
\begin{funcdesc}{randint}{a, b}
Returns a random integer \var{N} such that
\code{\var{a} <= \var{N} <= \var{b}}.
\end{funcdesc}
\begin{funcdesc}{random}{}
Returns the next random floating point number in the range [0.0
... 1.0).
\end{funcdesc}
\begin{funcdesc}{uniform}{a, b}
Returns a random real number \var{N} such that
\code{\var{a} <= \var{N} < \var{b}}.
\end{funcdesc}

View file

@ -8,10 +8,11 @@ This module defines a class, \class{Message}, which represents a
collection of ``email headers'' as defined by the Internet standard collection of ``email headers'' as defined by the Internet standard
\rfc{822}. It is used in various contexts, usually to read such \rfc{822}. It is used in various contexts, usually to read such
headers from a file. This module also defines a helper class headers from a file. This module also defines a helper class
\class{AddressList} for parsing \rfc{822} addresses. \class{AddressList} for parsing \rfc{822} addresses. Please refer to
the RFC for information on the specific syntax of \rfc{822} headers.
Note that there's a separate module to read \UNIX{}, MH, and MMDF The \refmodule{mailbox}\refstmodindex{mailbox} module provides classes
style mailbox files: \refmodule{mailbox}\refstmodindex{mailbox}. to read mailboxes produced by various end-user mail programs.
\begin{classdesc}{Message}{file\optional{, seekable}} \begin{classdesc}{Message}{file\optional{, seekable}}
A \class{Message} instance is instantiated with an input object as A \class{Message} instance is instantiated with an input object as
@ -61,7 +62,8 @@ however, some mailers don't follow that format as specified, so
\code{'Mon, 20 Nov 1995 19:12:08 -0500'}. If it succeeds in parsing \code{'Mon, 20 Nov 1995 19:12:08 -0500'}. If it succeeds in parsing
the date, \function{parsedate()} returns a 9-tuple that can be passed the date, \function{parsedate()} returns a 9-tuple that can be passed
directly to \function{time.mktime()}; otherwise \code{None} will be directly to \function{time.mktime()}; otherwise \code{None} will be
returned. returned. Note that fields 6, 7, and 8 of the result tuple are not
usable.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{parsedate_tz}{date} \begin{funcdesc}{parsedate_tz}{date}
@ -74,7 +76,8 @@ offset is the opposite of the sign of the \code{time.timezone}
variable for the same timezone; the latter variable follows the variable for the same timezone; the latter variable follows the
\POSIX{} standard while this module follows \rfc{822}.) If the input \POSIX{} standard while this module follows \rfc{822}.) If the input
string has no timezone, the last element of the tuple returned is string has no timezone, the last element of the tuple returned is
\code{None}. \code{None}. Note that fields 6, 7, and 8 of the result tuple are not
usable.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{mktime_tz}{tuple} \begin{funcdesc}{mktime_tz}{tuple}
@ -87,6 +90,12 @@ switch dates. Not enough to worry about for common use.
\end{funcdesc} \end{funcdesc}
\begin{seealso}
\seemodule{mailbox}{Classes to read various mailbox formats produced
by end-user mail programs.}
\end{seealso}
\subsection{Message Objects \label{message-objects}} \subsection{Message Objects \label{message-objects}}
A \class{Message} instance has the following methods: A \class{Message} instance has the following methods:
@ -180,7 +189,8 @@ continuation lines the named headers contain are also parsed.
\begin{methoddesc}{getdate}{name} \begin{methoddesc}{getdate}{name}
Retrieve a header using \method{getheader()} and parse it into a 9-tuple Retrieve a header using \method{getheader()} and parse it into a 9-tuple
compatible with \function{time.mktime()}. If there is no header matching compatible with \function{time.mktime()}; note that fields 6, 7, and 8
are not usable. If there is no header matching
\var{name}, or it is unparsable, return \code{None}. \var{name}, or it is unparsable, return \code{None}.
Date parsing appears to be a black art, and not all mailers adhere to Date parsing appears to be a black art, and not all mailers adhere to
@ -193,7 +203,8 @@ function may occasionally yield an incorrect result.
Retrieve a header using \method{getheader()} and parse it into a Retrieve a header using \method{getheader()} and parse it into a
10-tuple; the first 9 elements will make a tuple compatible with 10-tuple; the first 9 elements will make a tuple compatible with
\function{time.mktime()}, and the 10th is a number giving the offset \function{time.mktime()}, and the 10th is a number giving the offset
of the date's timezone from UTC. Similarly to \method{getdate()}, if of the date's timezone from UTC. Note that fields 6, 7, and 8
are not usable. Similarly to \method{getdate()}, if
there is no header matching \var{name}, or it is unparsable, return there is no header matching \var{name}, or it is unparsable, return
\code{None}. \code{None}.
\end{methoddesc} \end{methoddesc}

View file

@ -1,7 +1,8 @@
% LaTeXed and enhanced from comments in file
\section{\module{sched} --- \section{\module{sched} ---
Event scheduler} Event scheduler}
% LaTeXed and enhanced from comments in file
\declaremodule{standard}{sched} \declaremodule{standard}{sched}
\sectionauthor{Moshe Zadka}{mzadka@geocities.com} \sectionauthor{Moshe Zadka}{mzadka@geocities.com}
\modulesynopsis{General purpose event scheduler.} \modulesynopsis{General purpose event scheduler.}
@ -49,7 +50,8 @@ From print_time 930343700.273
\begin{methoddesc}{enterabs}{time, priority, action, argument} \begin{methoddesc}{enterabs}{time, priority, action, argument}
Schedule a new event. The \var{time} argument should be a numeric type Schedule a new event. The \var{time} argument should be a numeric type
compatible to the return value of \var{timefunc}. Events scheduled for compatible with the return value of the \var{timefunc} function passed
to the constructor. Events scheduled for
the same \var{time} will be executed in the order of their the same \var{time} will be executed in the order of their
\var{priority}. \var{priority}.

View file

@ -9,7 +9,7 @@ This module provides access to the function \cfunction{select()}
available in most operating systems. Note that on Windows, it only available in most operating systems. Note that on Windows, it only
works for sockets; on other operating systems, it also works for other works for sockets; on other operating systems, it also works for other
file types (in particular, on \UNIX{}, it works on pipes). It cannot file types (in particular, on \UNIX{}, it works on pipes). It cannot
be used or regular files to determine whether a file has grown since be used on regular files to determine whether a file has grown since
it was last read. it was last read.
The module defines the following: The module defines the following:

View file

@ -1,5 +1,3 @@
% Module and documentation by Eric S. Raymond, 21 Dec 1998
\section{\module{shlex} --- \section{\module{shlex} ---
Simple lexical analysis} Simple lexical analysis}

View file

@ -74,6 +74,17 @@ A nice selection of exceptions is defined as well:
\end{excdesc} \end{excdesc}
\begin{seealso}
\seetext{Internet \rfc{821}, \emph{Simple Mail Transfer Protocol}.
Available online at
\url{http://info.internet.isi.edu/in-notes/rfc/files/rfc821.txt}.}
\seetext{Internet \rfc{1869}, \emph{SMTP Service Extensions}.
Available online at
\url{http://info.internet.isi.edu/in-notes/rfc/files/rfc1869.txt}.}
\end{seealso}
\subsection{SMTP Objects \label{SMTP-objects}} \subsection{SMTP Objects \label{SMTP-objects}}
An \class{SMTP} instance has the following methods: An \class{SMTP} instance has the following methods:
@ -160,6 +171,10 @@ need to use different ESMTP options to different recipients you have
to use the low-level methods such as \method{mail}, \method{rcpt} and to use the low-level methods such as \method{mail}, \method{rcpt} and
\method{data} to send the message.) \method{data} to send the message.)
\strong{Note:} The \var{from_addr} and \var{to_addrs} parameters are
used to construct the message envelope used by the transport agents.
The \class{SMTP} does not modify the message headers in any way.
If there has been no previous \samp{EHLO} or \samp{HELO} command this If there has been no previous \samp{EHLO} or \samp{HELO} command this
session, this method tries ESMTP \samp{EHLO} first. If the server does session, this method tries ESMTP \samp{EHLO} first. If the server does
ESMTP, message size and each of the specified options will be passed ESMTP, message size and each of the specified options will be passed
@ -177,27 +192,25 @@ message sent by the server.
This method may raise the following exceptions: This method may raise the following exceptions:
\begin{itemize} \begin{description}
\item[\exception{SMTPRecipientsRefused}] \item[\exception{SMTPRecipientsRefused}]
All recipients were refused. Nobody got the mail. The All recipients were refused. Nobody got the mail. The
\var{recipients} attribute of the exception object is a dictionary \member{recipients} attribute of the exception object is a dictionary
with information about the refused recipients (like the one returned with information about the refused recipients (like the one returned
when at least one recipient was accepted). when at least one recipient was accepted).
\item[\exception{SMTPHeloError}] \item[\exception{SMTPHeloError}]
The server didn't reply properly to The server didn't reply properly to the \samp{HELO} greeting.
the helo greeting.
\item[\exception{SMTPSenderRefused}] \item[\exception{SMTPSenderRefused}]
The server didn't accept the from_addr. The server didn't accept the \var{from_addr}.
\item[\exception{SMTPDataError}] \item[\exception{SMTPDataError}]
The server replied with an unexpected The server replied with an unexpected error code (other than a refusal
error code (other than a refusal of of a recipient).
a recipient). \end{description}
\end{itemize}
Unless otherwise noted the connection will be open even after Unless otherwise noted, the connection will be open even after
an exception is raised. an exception is raised.
\end{methoddesc} \end{methoddesc}
@ -216,33 +229,37 @@ consult the module code.
\subsection{SMTP Example \label{SMTP-example}} \subsection{SMTP Example \label{SMTP-example}}
This example prompts the user for addresses needed in the message This example prompts the user for addresses needed in the message
envelop (`To' and `From' addresses), and the message to be envelope (`To' and `From' addresses), and the message to be
delivered. Note that the headers to be included with the message must delivered. Note that the headers to be included with the message must
be included in the message as entered; this example doesn't do any be included in the message as entered; this example doesn't do any
processing of the \rfc{822} headers. In particular, the `To' and processing of the \rfc{822} headers. In particular, the `To' and
`From' addresses must be included in the message headers explicitly. `From' addresses must be included in the message headers explicitly.
\begin{verbatim} \begin{verbatim}
import rfc822, string, sys
import smtplib import smtplib
import string
def prompt(prompt): def prompt(prompt):
sys.stdout.write(prompt + ": ") return string.strip(raw_input(prompt))
return string.strip(sys.stdin.readline())
fromaddr = prompt("From") fromaddr = prompt("From: ")
toaddrs = string.splitfields(prompt("To"), ',') toaddrs = string.split(prompt("To: "))
print "Enter message, end with ^D:" print "Enter message, end with ^D:"
msg = ""
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, string.join(toaddrs, ", ")))
while 1: while 1:
line = sys.stdin.readline() line = raw_input()
if not line: if not line:
break break
msg = msg + line msg = msg + line
print "Message length is " + `len(msg)` print "Message length is " + `len(msg)`
server = smtplib.SMTP('localhost') server = smtplib.SMTP('localhost')
server.set_debuglevel(1) server.set_debuglevel(1)
server.connect()
server.sendmail(fromaddr, toaddrs, msg) server.sendmail(fromaddr, toaddrs, msg)
server.quit() server.quit()
\end{verbatim} \end{verbatim}

View file

@ -6,16 +6,19 @@
This module provides access to the BSD \emph{socket} interface. This module provides access to the BSD \emph{socket} interface.
It is available on \UNIX{} systems that support this interface. It is available on all modern \UNIX{} systems, Windows, MacOS, BeOS,
OS/2, and probably additional platforms.
For an introduction to socket programming (in C), see the following For an introduction to socket programming (in C), see the following
papers: \citetitle{An Introductory 4.3BSD Interprocess Communication papers: \citetitle{An Introductory 4.3BSD Interprocess Communication
Tutorial}, by Stuart Sechrest and \citetitle{An Advanced 4.3BSD Tutorial}, by Stuart Sechrest and \citetitle{An Advanced 4.3BSD
Interprocess Communication Tutorial}, by Samuel J. Leffler et al, Interprocess Communication Tutorial}, by Samuel J. Leffler et al,
both in the \citetitle{\UNIX{} Programmer's Manual, Supplementary Documents 1} both in the \citetitle{\UNIX{} Programmer's Manual, Supplementary Documents 1}
(sections PS1:7 and PS1:8). The \UNIX{} manual pages for the various (sections PS1:7 and PS1:8). The platform-specific reference material
socket-related system calls are also a valuable source of information for the various socket-related system calls are also a valuable source
on the details of socket semantics. of information on the details of socket semantics. For \UNIX, refer
to the manual pages; for Windows, see the WinSock (or Winsock 2)
specification.
The Python interface is a straightforward transliteration of the The Python interface is a straightforward transliteration of the
\UNIX{} system call and library interface for sockets to Python's \UNIX{} system call and library interface for sockets to Python's

View file

@ -22,6 +22,10 @@ Preferred file system block size.
Fundamental file system block size. Fundamental file system block size.
\end{datadesc} \end{datadesc}
\begin{datadesc}{F_BLOCKS}
Total number of blocks in the filesystem.
\end{datadesc}
\begin{datadesc}{F_BFREE} \begin{datadesc}{F_BFREE}
Total number of free blocks. Total number of free blocks.
\end{datadesc} \end{datadesc}
@ -39,7 +43,7 @@ Total number of free file nodes.
\end{datadesc} \end{datadesc}
\begin{datadesc}{F_FAVAIL} \begin{datadesc}{F_FAVAIL}
Free nodes available to non-superuser. Free nodes available to non-super user.
\end{datadesc} \end{datadesc}
\begin{datadesc}{F_FLAG} \begin{datadesc}{F_FLAG}

View file

@ -30,15 +30,17 @@ The following values are considered false:
\item \code{None} \item \code{None}
\withsubitem{(Built-in object)}{\ttindex{None}} \withsubitem{(Built-in object)}{\ttindex{None}}
\item zero of any numeric type, e.g., \code{0}, \code{0L}, \code{0.0}. \item zero of any numeric type, for example, \code{0}, \code{0L},
\code{0.0}, \code{0j}.
\item any empty sequence, e.g., \code{''}, \code{()}, \code{[]}. \item any empty sequence, for example, \code{''}, \code{()}, \code{[]}.
\item any empty mapping, e.g., \code{\{\}}. \item any empty mapping, for example, \code{\{\}}.
\item instances of user-defined classes, if the class defines a \item instances of user-defined classes, if the class defines a
\method{__nonzero__()} or \method{__len__()} method, when that \method{__nonzero__()} or \method{__len__()} method, when that
method returns zero. method returns zero.\footnote{Additional information on these
special methods may be found in the \emph{Python Reference Manual}.}
\end{itemize} \end{itemize}
@ -77,9 +79,9 @@ Notes:
These only evaluate their second argument if needed for their outcome. These only evaluate their second argument if needed for their outcome.
\item[(2)] \item[(2)]
\samp{not} has a lower priority than non-Boolean operators, so e.g. \samp{not} has a lower priority than non-Boolean operators, so
\code{not a == b} is interpreted as \code{not(a == b)}, and \code{not \var{a} == \var{b}} is interpreted as \code{not (\var{a} ==
\code{a == not b} is a syntax error. \var{b})}, and \code{\var{a} == not \var{b}} is a syntax error.
\end{description} \end{description}
@ -88,10 +90,11 @@ These only evaluate their second argument if needed for their outcome.
Comparison operations are supported by all objects. They all have the Comparison operations are supported by all objects. They all have the
same priority (which is higher than that of the Boolean operations). same priority (which is higher than that of the Boolean operations).
Comparisons can be chained arbitrarily, e.g. \code{x < y <= z} is Comparisons can be chained arbitrarily; for example, \code{\var{x} <
equivalent to \code{x < y and y <= z}, except that \code{y} is \var{y} <= \var{z}} is equivalent to \code{\var{x} < \var{y} and
evaluated only once (but in both cases \code{z} is not evaluated at \var{y} <= \var{z}}, except that \var{y} is evaluated only once (but
all when \code{x < y} is found to be false). in both cases \var{z} is not evaluated at all when \code{\var{x} <
\var{y}} is found to be false).
\indexii{chaining}{comparisons} \indexii{chaining}{comparisons}
This table summarizes the comparison operations: This table summarizes the comparison operations:
@ -123,26 +126,33 @@ Notes:
\index{ABC language@\ABC{} language} \index{ABC language@\ABC{} language}
\index{language!ABC@\ABC{}} \index{language!ABC@\ABC{}}
\indexii{C@\C{}}{language} \indexii{C@\C{}}{language}
\code{!=} is the preferred spelling; \code{<>} is obsolescent.
\end{description} \end{description}
Objects of different types, except different numeric types, never Objects of different types, except different numeric types, never
compare equal; such objects are ordered consistently but arbitrarily compare equal; such objects are ordered consistently but arbitrarily
(so that sorting a heterogeneous array yields a consistent result). (so that sorting a heterogeneous array yields a consistent result).
Furthermore, some types (e.g., windows) support only a degenerate Furthermore, some types (for example, file objects) support only a
notion of comparison where any two objects of that type are unequal. degenerate notion of comparison where any two objects of that type are
Again, such objects are ordered arbitrarily but consistently. unequal. Again, such objects are ordered arbitrarily but
\indexii{types}{numeric} consistently.
\indexii{object}{numeric}
\indexii{objects}{comparing} \indexii{objects}{comparing}
(Implementation note: objects of different types except numbers are Instances of a class normally compare as non-equal unless the class
ordered by their type names; objects of the same types that don't \withsubitem{(instance method)}{\ttindex{__cmp__()}}
support proper comparison are ordered by their address.) defines the \method{__cmp__()} method. Refer to the \emph{Python
Reference Manual} for information on the use of this method to effect
object comparisons.
Two more operations with the same syntactic priority, \samp{in} and \strong{Implementation note:} Objects of different types except
\samp{not in}, are supported only by sequence types (below). numbers are ordered by their type names; objects of the same types
\opindex{in} that don't support proper comparison are ordered by their address.
\opindex{not in}
Two more operations with the same syntactic priority,
\samp{in}\opindex{in} and \samp{not in}\opindex{not in}, are supported
only by sequence types (below).
\subsection{Numeric Types \label{typesnumeric}} \subsection{Numeric Types \label{typesnumeric}}
@ -150,9 +160,9 @@ Two more operations with the same syntactic priority, \samp{in} and
There are four numeric types: \dfn{plain integers}, \dfn{long integers}, There are four numeric types: \dfn{plain integers}, \dfn{long integers},
\dfn{floating point numbers}, and \dfn{complex numbers}. \dfn{floating point numbers}, and \dfn{complex numbers}.
Plain integers (also just called \dfn{integers}) Plain integers (also just called \dfn{integers})
are implemented using \ctype{long} in \C{}, which gives them at least 32 are implemented using \ctype{long} in C, which gives them at least 32
bits of precision. Long integers have unlimited precision. Floating bits of precision. Long integers have unlimited precision. Floating
point numbers are implemented using \ctype{double} in \C{}. All bets on point numbers are implemented using \ctype{double} in C. All bets on
their precision are off unless you happen to know the machine you are their precision are off unless you happen to know the machine you are
working with. working with.
\indexii{numeric}{types} \indexii{numeric}{types}
@ -161,20 +171,20 @@ working with.
\indexiii{long}{integer}{type} \indexiii{long}{integer}{type}
\indexii{floating point}{type} \indexii{floating point}{type}
\indexii{complex number}{type} \indexii{complex number}{type}
\indexii{C@\C{}}{language} \indexii{C}{language}
Complex numbers have a real and imaginary part, which are both Complex numbers have a real and imaginary part, which are both
implemented using \ctype{double} in \C{}. To extract these parts from implemented using \ctype{double} in C. To extract these parts from
a complex number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}. a complex number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Numbers are created by numeric literals or as the result of built-in Numbers are created by numeric literals or as the result of built-in
functions and operators. Unadorned integer literals (including hex functions and operators. Unadorned integer literals (including hex
and octal numbers) yield plain integers. Integer literals with an \samp{L} and octal numbers) yield plain integers. Integer literals with an
or \samp{l} suffix yield long integers \character{L} or \character{l} suffix yield long integers
(\samp{L} is preferred because \samp{1l} looks too much like eleven!). (\character{L} is preferred because \samp{1l} looks too much like
Numeric literals containing a decimal point or an exponent sign yield eleven!). Numeric literals containing a decimal point or an exponent
floating point numbers. Appending \samp{j} or \samp{J} to a numeric sign yield floating point numbers. Appending \character{j} or
literal yields a complex number. \character{J} to a numeric literal yields a complex number.
\indexii{numeric}{literals} \indexii{numeric}{literals}
\indexii{integer}{literals} \indexii{integer}{literals}
\indexiii{long}{integer}{literals} \indexiii{long}{integer}{literals}
@ -236,21 +246,23 @@ Notes:
\item[(1)] \item[(1)]
For (plain or long) integer division, the result is an integer. For (plain or long) integer division, the result is an integer.
The result is always rounded towards minus infinity: 1/2 is 0, The result is always rounded towards minus infinity: 1/2 is 0,
(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result
is a long integer if either operand is a long integer, regardless of
the numeric value.
\indexii{integer}{division} \indexii{integer}{division}
\indexiii{long}{integer}{division} \indexiii{long}{integer}{division}
\item[(2)] \item[(2)]
Conversion from floating point to (long or plain) integer may round or Conversion from floating point to (long or plain) integer may round or
truncate as in \C{}; see functions \function{floor()} and \function{ceil()} in truncate as in \C{}; see functions \function{floor()} and \function{ceil()} in
module \module{math} for well-defined conversions. module \refmodule{math}\refbimodindex{math} for well-defined conversions.
\withsubitem{(in module math)}{\ttindex{floor()}\ttindex{ceil()}} \withsubitem{(in module math)}{\ttindex{floor()}\ttindex{ceil()}}
\indexii{numeric}{conversions} \indexii{numeric}{conversions}
\refbimodindex{math}
\indexii{C@\C{}}{language} \indexii{C@\C{}}{language}
\item[(3)] \item[(3)]
See the section on built-in functions for an exact definition. See section \ref{built-in-funcs}, ``Built-in Functions,'' for a full
description.
\end{description} \end{description}
% XXXJH exceptions: overflow (when? what operations?) zerodivision % XXXJH exceptions: overflow (when? what operations?) zerodivision
@ -302,7 +314,7 @@ division by \code{pow(2, \var{n})} without overflow check.
There are three sequence types: strings, lists and tuples. There are three sequence types: strings, lists and tuples.
Strings literals are written in single or double quotes: Strings literals are written in single or double quotes:
\code{'xyzzy'}, \code{"frobozz"}. See Chapter 2 of the \code{'xyzzy'}, \code{"frobozz"}. See chapter 2 of the
\citetitle[../ref/ref.html]{Python Reference Manual} for more about \citetitle[../ref/ref.html]{Python Reference Manual} for more about
string literals. Lists are constructed with square brackets, string literals. Lists are constructed with square brackets,
separating items with commas: \code{[a, b, c]}. Tuples are separating items with commas: \code{[a, b, c]}. Tuples are
@ -332,10 +344,10 @@ and \var{j} are integers:
equal to \var{x}, else \code{1}}{} equal to \var{x}, else \code{1}}{}
\hline \hline
\lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{} \lineiii{\var{s} + \var{t}}{the concatenation of \var{s} and \var{t}}{}
\lineiii{\var{s} * \var{n}\textrm{,} \var{n} * \var{s}}{\var{n} copies of \var{s} concatenated}{(3)} \lineiii{\var{s} * \var{n}\textrm{,} \var{n} * \var{s}}{\var{n} copies of \var{s} concatenated}{(1)}
\hline \hline
\lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(1)} \lineiii{\var{s}[\var{i}]}{\var{i}'th item of \var{s}, origin 0}{(2)}
\lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(1), (2)} \lineiii{\var{s}[\var{i}:\var{j}]}{slice of \var{s} from \var{i} to \var{j}}{(2), (3)}
\hline \hline
\lineiii{len(\var{s})}{length of \var{s}}{} \lineiii{len(\var{s})}{length of \var{s}}{}
\lineiii{min(\var{s})}{smallest item of \var{s}}{} \lineiii{min(\var{s})}{smallest item of \var{s}}{}
@ -356,23 +368,21 @@ equal to \var{x}, else \code{1}}{}
Notes: Notes:
\begin{description} \begin{description}
\item[(1)] Values of \var{n} less than \code{0} are treated as
\item[(1)] If \var{i} or \var{j} is negative, the index is relative to \code{0} (which yields an empty sequence of the same type as
\var{s}).
\item[(2)] If \var{i} or \var{j} is negative, the index is relative to
the end of the string, i.e., \code{len(\var{s}) + \var{i}} or the end of the string, i.e., \code{len(\var{s}) + \var{i}} or
\code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is \code{len(\var{s}) + \var{j}} is substituted. But note that \code{-0} is
still \code{0}. still \code{0}.
\item[(2)] The slice of \var{s} from \var{i} to \var{j} is defined as \item[(3)] The slice of \var{s} from \var{i} to \var{j} is defined as
the sequence of items with index \var{k} such that \code{\var{i} <= the sequence of items with index \var{k} such that \code{\var{i} <=
\var{k} < \var{j}}. If \var{i} or \var{j} is greater than \var{k} < \var{j}}. If \var{i} or \var{j} is greater than
\code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted, \code{len(\var{s})}, use \code{len(\var{s})}. If \var{i} is omitted,
use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If use \code{0}. If \var{j} is omitted, use \code{len(\var{s})}. If
\var{i} is greater than or equal to \var{j}, the slice is empty. \var{i} is greater than or equal to \var{j}, the slice is empty.
\item[(3)] Values of \var{n} less than \code{0} are treated as
\code{0} (which yields an empty sequence of the same type as
\var{s}).
\end{description} \end{description}
@ -452,24 +462,24 @@ The following operations are defined on mutable sequence types (where
\lineiii{del \var{s}[\var{i}:\var{j}]} \lineiii{del \var{s}[\var{i}:\var{j}]}
{same as \code{\var{s}[\var{i}:\var{j}] = []}}{} {same as \code{\var{s}[\var{i}:\var{j}] = []}}{}
\lineiii{\var{s}.append(\var{x})} \lineiii{\var{s}.append(\var{x})}
{same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{} {same as \code{\var{s}[len(\var{s}):len(\var{s})] = [\var{x}]}}{(1)}
\lineiii{\var{s}.extend(\var{x})} \lineiii{\var{s}.extend(\var{x})}
{same as \code{\var{s}[len(\var{s}):len(\var{s})] = \var{x}}}{(5)} {same as \code{\var{s}[len(\var{s}):len(\var{s})] = \var{x}}}{(2)}
\lineiii{\var{s}.count(\var{x})} \lineiii{\var{s}.count(\var{x})}
{return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{} {return number of \var{i}'s for which \code{\var{s}[\var{i}] == \var{x}}}{}
\lineiii{\var{s}.index(\var{x})} \lineiii{\var{s}.index(\var{x})}
{return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(1)} {return smallest \var{i} such that \code{\var{s}[\var{i}] == \var{x}}}{(3)}
\lineiii{\var{s}.insert(\var{i}, \var{x})} \lineiii{\var{s}.insert(\var{i}, \var{x})}
{same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]} {same as \code{\var{s}[\var{i}:\var{i}] = [\var{x}]}
if \code{\var{i} >= 0}}{} if \code{\var{i} >= 0}}{}
\lineiii{\var{s}.pop(\optional{\var{i}})} \lineiii{\var{s}.pop(\optional{\var{i}})}
{same as \code{\var{x} = \var{s}[\var{i}]; del \var{s}[\var{i}]; return \var{x}}}{(4)} {same as \code{\var{x} = \var{s}[\var{i}]; del \var{s}[\var{i}]; return \var{x}}}{(4)}
\lineiii{\var{s}.remove(\var{x})} \lineiii{\var{s}.remove(\var{x})}
{same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(1)} {same as \code{del \var{s}[\var{s}.index(\var{x})]}}{(3)}
\lineiii{\var{s}.reverse()} \lineiii{\var{s}.reverse()}
{reverses the items of \var{s} in place}{(3)} {reverses the items of \var{s} in place}{(5)}
\lineiii{\var{s}.sort(\optional{\var{cmpfunc}})} \lineiii{\var{s}.sort(\optional{\var{cmpfunc}})}
{sort the items of \var{s} in place}{(2), (3)} {sort the items of \var{s} in place}{(5), (6)}
\end{tableiii} \end{tableiii}
\indexiv{operations on}{mutable}{sequence}{types} \indexiv{operations on}{mutable}{sequence}{types}
\indexiii{operations on}{sequence}{types} \indexiii{operations on}{sequence}{types}
@ -484,10 +494,29 @@ The following operations are defined on mutable sequence types (where
\noindent \noindent
Notes: Notes:
\begin{description} \begin{description}
\item[(1)] Raises \exception{ValueError} when \var{x} is not found in \item[(1)] The C implementation of Python has historically accepted
multiple parameters and implicitly joined them into a tuple; this
will no longer work in Python 1.6. Use of this misfeature has been
deprecated since Python 1.4.
\item[(2)] Raises an exception when \var{x} is not a list object. The
\method{extend()} method is experimental and not supported by
mutable sequence types other than lists.
\item[(3)] Raises \exception{ValueError} when \var{x} is not found in
\var{s}. \var{s}.
\item[(2)] The \method{sort()} method takes an optional argument \item[(4)] The \method{pop()} method is experimental and not supported
by other mutable sequence types than lists. The optional argument
\var{i} defaults to \code{-1}, so that by default the last item is
removed and returned.
\item[(5)] The \method{sort()} and \method{reverse()} methods modify the
list in place for economy of space when sorting or reversing a large
list. They don't return the sorted or reversed list to remind you
of this side effect.
\item[(6)] The \method{sort()} method takes an optional argument
specifying a comparison function of two arguments (list items) which specifying a comparison function of two arguments (list items) which
should return \code{-1}, \code{0} or \code{1} depending on whether should return \code{-1}, \code{0} or \code{1} depending on whether
the first argument is considered smaller than, equal to, or larger the first argument is considered smaller than, equal to, or larger
@ -497,24 +526,12 @@ Notes:
\method{reverse()} than to use the built-in function \method{reverse()} than to use the built-in function
\function{sort()} with a comparison function that reverses the \function{sort()} with a comparison function that reverses the
ordering of the elements. ordering of the elements.
\item[(3)] The \method{sort()} and \method{reverse()} methods modify the
list in place for economy of space when sorting or reversing a large
list. They don't return the sorted or reversed list to remind you
of this side effect.
\item[(4)] The \method{pop()} method is experimental and not supported
by other mutable sequence types than lists. The optional argument
\var{i} defaults to \code{-1}, so that by default the last item is
removed and returned.
\item[(5)] Raises an exception when \var{x} is not a list object. The
\method{extend()} method is experimental and not supported by
mutable types other than lists.
\end{description} \end{description}
\subsection{Mapping Types \label{typesmapping}} \subsection{Mapping Types \label{typesmapping}}
\indexii{mapping}{types}
\indexii{dictionary}{type}
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
@ -527,9 +544,6 @@ comparison: if two numbers compare equal (e.g. \code{1} and
\code{1.0}) then they can be used interchangeably to index the same \code{1.0}) then they can be used interchangeably to index the same
dictionary entry. dictionary entry.
\indexii{mapping}{types}
\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
@ -586,12 +600,17 @@ Notes:
\item[(1)] Raises a \exception{KeyError} exception if \var{k} is not \item[(1)] Raises a \exception{KeyError} exception if \var{k} is not
in the map. in the map.
\item[(2)] Keys and values are listed in random order. \item[(2)] Keys and values are listed in random order. If
\method{keys()} and \method{values()} are called with no intervening
modifications to the dictionary, the two lists will directly
correspond. This allows the creation of \code{(\var{value},
\var{key})} pairs using \function{map()}: \samp{pairs = map(None,
\var{a}.values(), \var{a}.keys())}.
\item[(3)] \var{b} must be of the same type as \var{a}. \item[(3)] \var{b} must be of the same type as \var{a}.
\item[(4)] Never raises an exception if \var{k} is not in the map, \item[(4)] Never raises an exception if \var{k} is not in the map,
instead it returns \var{f}. \var{f} is optional; when \var{f} is not instead it returns \var{x}. \var{x} is optional; when \var{x} is not
provided and \var{k} is not in the map, \code{None} is returned. provided and \var{k} is not in the map, \code{None} is returned.
\end{description} \end{description}
@ -629,7 +648,7 @@ written as \code{<module 'os' from '/usr/local/lib/python1.5/os.pyc'>}.
\subsubsection{Classes and Class Instances \label{typesobjects}} \subsubsection{Classes and Class Instances \label{typesobjects}}
\nodename{Classes and Instances} \nodename{Classes and Instances}
See Chapters 3 and 7 of the \citetitle[../ref/ref.html]{Python See chapters 3 and 7 of the \citetitle[../ref/ref.html]{Python
Reference Manual} for these. Reference Manual} for these.
@ -730,7 +749,7 @@ It is written as \code{Ellipsis}.
File objects are implemented using \C{}'s \code{stdio} File objects are implemented using \C{}'s \code{stdio}
package and can be created with the built-in function package and can be created with the built-in function
\function{open()}\bifuncindex{open} described section \function{open()}\bifuncindex{open} described in section
\ref{built-in-funcs}, ``Built-in Functions.'' They are also returned \ref{built-in-funcs}, ``Built-in Functions.'' They are also returned
by some other built-in functions and methods, e.g., by some other built-in functions and methods, e.g.,
\function{posix.popen()} and \function{posix.fdopen()} and the \function{posix.popen()} and \function{posix.fdopen()} and the
@ -793,7 +812,7 @@ descriptors, e.g. module \module{fcntl} or \function{os.read()} and friends.
non-negative, it is a maximum byte count (including the trailing non-negative, it is a maximum byte count (including the trailing
newline) and an incomplete line may be returned. newline) and an incomplete line may be returned.
An empty string is returned when \EOF{} is hit An empty string is returned when \EOF{} is hit
immediately. Note: unlike \code{stdio}'s \cfunction{fgets()}, the returned immediately. Note: Unlike \code{stdio}'s \cfunction{fgets()}, the returned
string contains null characters (\code{'\e 0'}) if they occurred in the string contains null characters (\code{'\e 0'}) if they occurred in the
input. input.
\end{methoddesc} \end{methoddesc}
@ -823,12 +842,12 @@ descriptors, e.g. module \module{fcntl} or \function{os.read()} and friends.
Truncate the file's size. If the optional size argument present, the Truncate the file's size. If the optional size argument present, the
file is truncated to (at most) that size. The size defaults to the file is truncated to (at most) that size. The size defaults to the
current position. Availability of this function depends on the current position. Availability of this function depends on the
operating system version (e.g., not all \UNIX{} versions support this operating system version (for example, not all \UNIX{} versions support this
operation). operation).
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}[file]{write}{str} \begin{methoddesc}[file]{write}{str}
Write a string to the file. There is no return value. Note: due to Write a string to the file. There is no return value. Note: Due to
buffering, the string may not actually show up in the file until buffering, the string may not actually show up in the file until
the \method{flush()} or \method{close()} method is called. the \method{flush()} or \method{close()} method is called.
\end{methoddesc} \end{methoddesc}

View file

@ -45,23 +45,35 @@ The module defines the following exception and functions:
Format characters have the following meaning; the conversion between Format characters have the following meaning; the conversion between
C and Python values should be obvious given their types: C and Python values should be obvious given their types:
\begin{tableiii}{c|l|l}{samp}{Format}{C Type}{Python} \begin{tableiv}{c|l|l|c}{samp}{Format}{C Type}{Python}{Notes}
\lineiii{x}{pad byte}{no value} \lineiv{x}{pad byte}{no value}{}
\lineiii{c}{\ctype{char}}{string of length 1} \lineiv{c}{\ctype{char}}{string of length 1}{}
\lineiii{b}{\ctype{signed char}}{integer} \lineiv{b}{\ctype{signed char}}{integer}{}
\lineiii{B}{\ctype{unsigned char}}{integer} \lineiv{B}{\ctype{unsigned char}}{integer}{}
\lineiii{h}{\ctype{short}}{integer} \lineiv{h}{\ctype{short}}{integer}{}
\lineiii{H}{\ctype{unsigned short}}{integer} \lineiv{H}{\ctype{unsigned short}}{integer}{}
\lineiii{i}{\ctype{int}}{integer} \lineiv{i}{\ctype{int}}{integer}{}
\lineiii{I}{\ctype{unsigned int}}{integer} \lineiv{I}{\ctype{unsigned int}}{long}{(1)}
\lineiii{l}{\ctype{long}}{integer} \lineiv{l}{\ctype{long}}{integer}{}
\lineiii{L}{\ctype{unsigned long}}{integer} \lineiv{L}{\ctype{unsigned long}}{long}{}
\lineiii{f}{\ctype{float}}{float} \lineiv{f}{\ctype{float}}{float}{}
\lineiii{d}{\ctype{double}}{float} \lineiv{d}{\ctype{double}}{float}{}
\lineiii{s}{\ctype{char[]}}{string} \lineiv{s}{\ctype{char[]}}{string}{}
\lineiii{p}{\ctype{char[]}}{string} \lineiv{p}{\ctype{char[]}}{string}{}
\lineiii{P}{\ctype{void *}}{integer} \lineiv{P}{\ctype{void *}}{integer}{}
\end{tableiii} \end{tableiv}
\noindent
Notes:
\begin{description}
\item[(1)]
The \character{I} conversion code will convert to a Python long if
the C \ctype{int} is the same size as a C \ctype{long}, which is
typical on most modern systems. If a C \ctype{int} is smaller than
a C \ctype{long}, an Python integer will be created instead.
\end{description}
A format character may be preceded by an integral repeat count; A format character may be preceded by an integral repeat count;
e.g.\ the format string \code{'4h'} means exactly the same as e.g.\ the format string \code{'4h'} means exactly the same as

View file

@ -31,6 +31,11 @@ It is always available.
A string containing the copyright pertaining to the Python interpreter. A string containing the copyright pertaining to the Python interpreter.
\end{datadesc} \end{datadesc}
\begin{datadesc}{dllhandle}
Integer specifying the handle of the Python DLL.
Availability: Windows.
\end{datadesc}
\begin{funcdesc}{exc_info}{} \begin{funcdesc}{exc_info}{}
This function returns a tuple of three values that give information This function returns a tuple of three values that give information
about the exception that is currently being handled. The information about the exception that is currently being handled. The information
@ -285,5 +290,26 @@ exception type and value are printed.
\end{datadesc} \end{datadesc}
\begin{datadesc}{version} \begin{datadesc}{version}
A string containing the version number of the Python interpreter. A string containing the version number of the Python interpreter plus
additional information on the build number and compiler used. It has
a value of the form \code{'\var{version} (\#\var{build_number},
\var{build_date}, \var{build_time}) [\var{compiler}]'}. The first
three characters are used to identify the version in the installation
directories (where appropriate on each platform). An example:
\begin{verbatim}
>>> import sys
>>> sys.version
'1.5.2 (#0 Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)]'
\end{verbatim}
\end{datadesc}
\begin{datadesc}{winver}
The version number used to form registry keys on Windows platforms.
This is stored as string resource 1000 in the Python DLL. The value
is normally the first three characters of \constant{version}. It is
provided in the \module{sys} module for informational purposes;
modifying this value has no effect on the registry keys used by
Python.
Availability: Windows.
\end{datadesc} \end{datadesc}

View file

@ -1,12 +1,9 @@
% LaTeX'ized from the comments in the module by Skip Montanaro
% <skip@mojam.com>.
\section{\module{telnetlib} --- \section{\module{telnetlib} ---
Telnet client} Telnet client}
\declaremodule{standard}{telnetlib} \declaremodule{standard}{telnetlib}
\modulesynopsis{Telnet client class.} \modulesynopsis{Telnet client class.}
\sectionauthor{Skip Montanaro}{skip@mojam.com}
The \module{telnetlib} module provides a \class{Telnet} class that The \module{telnetlib} module provides a \class{Telnet} class that
implements the Telnet protocol. See \rfc{854} for details about the implements the Telnet protocol. See \rfc{854} for details about the
@ -149,3 +146,32 @@ If a regular expression ends with a greedy match (e.g. \regexp{.*})
or if more than one expression can match the same input, the or if more than one expression can match the same input, the
results are undeterministic, and may depend on the I/O timing. results are undeterministic, and may depend on the I/O timing.
\end{methoddesc} \end{methoddesc}
\subsection{Telnet Example \label{telnet-example}}
\sectionauthor{Peter Funk}{pf@artcom-gmbh.de}
A simple example illustrating typical use:
\begin{verbatim}
import getpass
import sys
import telnetlib
HOST = "localhost"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("ls\n")
tn.write("exit\n")
print tn.read_all()
\end{verbatim}

View file

@ -1,12 +1,13 @@
\section{\module{time} --- \section{\module{time} ---
Time access and conversions.} Time access and conversions}
\declaremodule{builtin}{time}
\declaremodule{builtin}{time}
\modulesynopsis{Time access and conversions.} \modulesynopsis{Time access and conversions.}
This module provides various time-related functions. This module provides various time-related functions.
It is always available. It is always available, but not all functions are available
on all platforms.
An explanation of some terminology and conventions is in order. An explanation of some terminology and conventions is in order.
@ -72,17 +73,29 @@ nonzero fraction (\UNIX{} \cfunction{select()} is used to implement
this, where available). this, where available).
\item \item
The time tuple as returned by \function{gmtime()}, The time tuple as returned by \function{gmtime()},
\function{localtime()}, and \function{strptime()}, and accepted by \function{localtime()}, and \function{strptime()}, and accepted by
\function{asctime()}, \function{mktime()} and \function{strftime()}, \function{asctime()}, \function{mktime()} and \function{strftime()},
is a tuple of 9 integers: year (e.g.\ 1993), month (1--12), day is a tuple of 9 integers:
(1--31), hour (0--23), minute (0--59), second (0--59), weekday (0--6,
monday is 0), Julian day (1--366) and daylight savings flag (-1, 0 or \begin{tableiii}{r|l|l}{textrm}{Index}{Field}{Values}
1). Note that unlike the C structure, the month value is a range \lineiii{0}{year}{(e.g.\ 1993)}
of 1-12, not 0-11. A year value will be handled as descibed under \lineiii{1}{month}{range [1,12]}
``Year 2000 (Y2K) issues'' above. A \code{-1} argument as daylight \lineiii{2}{day}{range [1,31]}
savings flag, passed to \function{mktime()} will usually result in the \lineiii{3}{hour}{range [0,23]}
correct daylight savings state to be filled in. \lineiii{4}{minute}{range [0,59]}
\lineiii{5}{second}{range [0,61]; see \strong{(1)} in \function{strftime()} description}
\lineiii{6}{weekday}{range [0,6], monday is 0}
\lineiii{7}{Julian day}{range [1,366]}
\lineiii{8}{daylight savings flag}{0, 1 or -1; see below}
\end{tableiii}
Note that unlike the C structure, the month value is a
range of 1-12, not 0-11. A year value will be handled as described
under ``Year 2000 (Y2K) issues'' above. A \code{-1} argument as
daylight savings flag, passed to \function{mktime()} will usually
result in the correct daylight savings state to be filled in.
\end{itemize} \end{itemize}
@ -168,34 +181,43 @@ They are shown without the optional field width and precision
specification, and are replaced by the indicated characters in the specification, and are replaced by the indicated characters in the
\function{strftime()} result: \function{strftime()} result:
\begin{tableii}{c|p{24em}}{code}{Directive}{Meaning} \begin{tableiii}{c|p{24em}|c}{code}{Directive}{Meaning}{Notes}
\lineii{\%a}{Locale's abbreviated weekday name.} \lineiii{\%a}{Locale's abbreviated weekday name.}{}
\lineii{\%A}{Locale's full weekday name.} \lineiii{\%A}{Locale's full weekday name.}{}
\lineii{\%b}{Locale's abbreviated month name.} \lineiii{\%b}{Locale's abbreviated month name.}{}
\lineii{\%B}{Locale's full month name.} \lineiii{\%B}{Locale's full month name.}{}
\lineii{\%c}{Locale's appropriate date and time representation.} \lineiii{\%c}{Locale's appropriate date and time representation.}{}
\lineii{\%d}{Day of the month as a decimal number [01,31].} \lineiii{\%d}{Day of the month as a decimal number [01,31].}{}
\lineii{\%H}{Hour (24-hour clock) as a decimal number [00,23].} \lineiii{\%H}{Hour (24-hour clock) as a decimal number [00,23].}{}
\lineii{\%I}{Hour (12-hour clock) as a decimal number [01,12].} \lineiii{\%I}{Hour (12-hour clock) as a decimal number [01,12].}{}
\lineii{\%j}{Day of the year as a decimal number [001,366].} \lineiii{\%j}{Day of the year as a decimal number [001,366].}{}
\lineii{\%m}{Month as a decimal number [01,12].} \lineiii{\%m}{Month as a decimal number [01,12].}{}
\lineii{\%M}{Minute as a decimal number [00,59].} \lineiii{\%M}{Minute as a decimal number [00,59].}{}
\lineii{\%p}{Locale's equivalent of either AM or PM.} \lineiii{\%p}{Locale's equivalent of either AM or PM.}{}
\lineii{\%S}{Second as a decimal number [00,61].} \lineiii{\%S}{Second as a decimal number [00,61].}{(1)}
\lineii{\%U}{Week number of the year (Sunday as the first day of the \lineiii{\%U}{Week number of the year (Sunday as the first day of the
week) as a decimal number [00,53]. All days in a new year week) as a decimal number [00,53]. All days in a new year
preceding the first Sunday are considered to be in week 0.} preceding the first Sunday are considered to be in week 0.}{}
\lineii{\%w}{Weekday as a decimal number [0(Sunday),6].} \lineiii{\%w}{Weekday as a decimal number [0(Sunday),6].}{}
\lineii{\%W}{Week number of the year (Monday as the first day of the \lineiii{\%W}{Week number of the year (Monday as the first day of the
week) as a decimal number [00,53]. All days in a new year week) as a decimal number [00,53]. All days in a new year
preceding the first Sunday are considered to be in week 0.} preceding the first Sunday are considered to be in week 0.}{}
\lineii{\%x}{Locale's appropriate date representation.} \lineiii{\%x}{Locale's appropriate date representation.}{}
\lineii{\%X}{Locale's appropriate time representation.} \lineiii{\%X}{Locale's appropriate time representation.}{}
\lineii{\%y}{Year without century as a decimal number [00,99].} \lineiii{\%y}{Year without century as a decimal number [00,99].}{}
\lineii{\%Y}{Year with century as a decimal number.} \lineiii{\%Y}{Year with century as a decimal number.}{}
\lineii{\%Z}{Time zone name (or by no characters if no time zone exists).} \lineiii{\%Z}{Time zone name (or by no characters if no time zone exists).}{}
\lineii{\%\%}{\%} \lineiii{\%\%}{A literal \character{\%} character.}{}
\end{tableii} \end{tableiii}
\noindent
Notes:
\begin{description}
\item[(1)]
The range really is \code{0} to \code{61}; this accounts for leap
seconds and the (very rare) double leap seconds.
\end{description}
Additional directives may be supported on certain platforms, but Additional directives may be supported on certain platforms, but
only the ones listed here have a meaning standardized by ANSI C. only the ones listed here have a meaning standardized by ANSI C.
@ -215,8 +237,9 @@ directives as those used by \function{strftime()}; it defaults to
returned by \function{ctime()}. The same platform caveats apply; see returned by \function{ctime()}. The same platform caveats apply; see
the local \UNIX{} documentation for restrictions or additional the local \UNIX{} documentation for restrictions or additional
supported directives. If \var{string} cannot be parsed according to supported directives. If \var{string} cannot be parsed according to
\var{format}, \exception{ValueError} is raised. This function may not \var{format}, \exception{ValueError} is raised.
be defined on all platforms.
Availability: Most modern \UNIX{} systems.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{time}{} \begin{funcdesc}{time}{}
@ -238,3 +261,9 @@ timezone, the second is the name of the local DST timezone. If no DST
timezone is defined, the second string should not be used. timezone is defined, the second string should not be used.
\end{datadesc} \end{datadesc}
\begin{seealso}
\seemodule{locale}{Internationalization services. The locale
settings can affect the return values for some of
the functions in the \module{time} module.}
\end{seealso}

View file

@ -1,11 +1,10 @@
\section{\module{types} --- \section{\module{types} ---
Names for all built-in types.} Names for all built-in types}
\declaremodule{standard}{types} \declaremodule{standard}{types}
\modulesynopsis{Names for all built-in types.} \modulesynopsis{Names for all built-in types.}
This module defines names for all object types that are used by the This module defines names for all object types that are used by the
standard Python interpreter, but not for the types defined by various standard Python interpreter, but not for the types defined by various
extension modules. It is safe to use \samp{from types import *} --- extension modules. It is safe to use \samp{from types import *} ---
@ -141,3 +140,8 @@ The type of traceback objects such as found in
The type of frame objects such as found in \code{tb.tb_frame} if The type of frame objects such as found in \code{tb.tb_frame} if
\code{tb} is a traceback object. \code{tb} is a traceback object.
\end{datadesc} \end{datadesc}
\begin{datadesc}{BufferType}
The type of buffer objects created by the
\function{buffer()}\bifuncindex{buffer} function.
\end{datadesc}

View file

@ -23,6 +23,9 @@ reference material.
\item[\module{Tkdnd}] \item[\module{Tkdnd}]
--- Drag-and-drop support for \module{Tkinter}. --- Drag-and-drop support for \module{Tkinter}.
\item[\module{turtle}]
--- Turtle graphics in a Tk window.
\item[\module{test}] \item[\module{test}]
--- Regression testing framework. This is used for the Python --- Regression testing framework. This is used for the Python
regression test, but is useful for other Python libraries as well. regression test, but is useful for other Python libraries as well.
@ -35,6 +38,11 @@ This is a package rather than a module.
Some of these are very old and/or not very robust; marked with ``hmm.'' Some of these are very old and/or not very robust; marked with ``hmm.''
\begin{description} \begin{description}
\item[\module{dircmp}]
--- Class to build directory diff tools on (may become a demo or tool).
\deprecated{1.6}{The \refmodule{filecmp} module will replace
\module{dircmp}.}
\item[\module{bdb}] \item[\module{bdb}]
--- A generic Python debugger base class (used by pdb) --- A generic Python debugger base class (used by pdb)
@ -72,7 +80,7 @@ document these.
--- Platform-independent API for playing audio data --- Platform-independent API for playing audio data
\item[\module{sunaudio}] \item[\module{sunaudio}]
--- interpret sun audio headers (may become obsolete or a tool/demo) --- Interpret Sun audio headers (may become obsolete or a tool/demo)
\item[\module{toaiff}] \item[\module{toaiff}]
--- Convert "arbitrary" sound files to AIFF files; should probably --- Convert "arbitrary" sound files to AIFF files; should probably
@ -80,14 +88,23 @@ become a tool or demo. Requires the external program \program{sox}.
\end{description} \end{description}
\section{Obsolete} \section{Obsolete \label{obsolete-modules}}
These modules are not on the standard module search path; These modules are not normally available for import; additional work
\indexiii{module}{search}{path} must be done to make them available.
but are available in the directory \file{lib-old/} installed under
\file{\textrm{\$prefix}/lib/python1.5/}. % $ <-- bow to font lock Those which are written in Python will be installed into the directory
To use any of these modules, add that directory to \code{sys.path}, \file{lib-old/} installed as part of the standard library. To use
possibly using \envvar{PYTHONPATH}. these, the directory must be added to \code{sys.path}, possibly using
\envvar{PYTHONPATH}.
Obsolete extension modules written in C are not built by default.
Under \UNIX, these must be enabled by uncommenting the appropriate
lines in \file{Modules/Setup} in the build tree and either rebuilding
Python if the modules are statically linked, or building and
installing the shared object if using dynamically-loaded extensions.
% XXX need Windows instructions!
\begin{description} \begin{description}
\item[\module{addpack}] \item[\module{addpack}]

View file

@ -1,8 +1,8 @@
\section{\module{urllib} --- \section{\module{urllib} ---
Open an arbitrary object given by URL.} Open an arbitrary resource by URL}
\declaremodule{standard}{urllib}
\modulesynopsis{Open an arbitrary object given by URL (requires sockets).} \declaremodule{standard}{urllib}
\modulesynopsis{Open an arbitrary network resource by URL (requires sockets).}
\index{WWW} \index{WWW}
\index{World-Wide Web} \index{World-Wide Web}
@ -62,6 +62,37 @@ If the \var{url} uses the \file{http:} scheme identifier, the optional
must in standard \file{application/x-www-form-urlencoded} format; must in standard \file{application/x-www-form-urlencoded} format;
see the \function{urlencode()} function below. see the \function{urlencode()} function below.
The \function{urlopen()} function works transparently with proxies.
In a \UNIX{} or Windows environment, set the \envvar{http_proxy},
\envvar{ftp_proxy} or \envvar{gopher_proxy} environment variables to a
URL that identifies the proxy server before starting the Python
interpreter. For example (the \character{\%} is the command prompt):
\begin{verbatim}
% http_proxy="http://www.someproxy.com:3128"
% export http_proxy
% python
...
\end{verbatim}
In a Macintosh environment, \function{urlopen()} will retrieve proxy
information from Internet\index{Internet Config} Config.
The \function{urlopen()} function works transparently with proxies.
In a \UNIX{} or Windows environment, set the \envvar{http_proxy},
\envvar{ftp_proxy} or \envvar{gopher_proxy} environment variables to a
URL that identifies the proxy server before starting the Python
interpreter, e.g.:
\begin{verbatim}
% http_proxy="http://www.someproxy.com:3128"
% export http_proxy
% python
...
\end{verbatim}
In a Macintosh environment, \function{urlopen()} will retrieve proxy
information from Internet Config.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{urlretrieve}{url\optional{, filename\optional{, hook}}} \begin{funcdesc}{urlretrieve}{url\optional{, filename\optional{, hook}}}
@ -127,6 +158,55 @@ characters, where both \var{key} and \var{value} are quoted using
\function{quote_plus()} above. \function{quote_plus()} above.
\end{funcdesc} \end{funcdesc}
The public functions \function{urlopen()} and \function{urlretrieve()}
create an instance of the \class{FancyURLopener} class and use it to perform
their requested actions. To override this functionality, programmers can
create a subclass of \class{URLopener} or \class{FancyURLopener}, then
assign that class to the \var{urllib._urlopener} variable before calling the
desired function. For example, applications may want to specify a different
\code{user-agent} header than \class{URLopener} defines. This can be
accomplished with the following code:
\begin{verbatim}
class AppURLopener(urllib.FancyURLopener):
def __init__(self, *args):
apply(urllib.FancyURLopener.__init__, (self,) + args)
self.version = "App/1.7"
urllib._urlopener = AppURLopener
\end{verbatim}
\begin{classdesc}{URLopener}{\optional{proxies\optional{, **x509}}}
Base class for opening and reading URLs. Unless you need to support
opening objects using schemes other than \file{http:}, \file{ftp:},
\file{gopher:} or \file{file:}, you probably want to use
\class{FancyURLopener}.
By default, the \class{URLopener} class sends a
\code{user-agent} header of \samp{urllib/\var{VVV}}, where
\var{VVV} is the \module{urllib} version number. Applications can
define their own \code{user-agent} header by subclassing
\class{URLopener} or \class{FancyURLopener} and setting the instance
attribute \var{version} to an appropriate string value before the
\method{open()} method is called.
Additional keyword parameters, collected in \var{x509}, are used for
authentication with the \file{https:} scheme. The keywords
\var{key_file} and \var{cert_file} are supported; both are needed to
actually retrieve a resource at an \file{https:} URL.
\end{classdesc}
\begin{classdesc}{FancyURLopener}{...}
\class{FancyURLopener} subclasses \class{URLopener} providing default
handling for the following HTTP response codes: 301, 302 or 401. For
301 and 302 response codes, the \code{location} header is used to
fetch the actual URL. For 401 response codes (authentication
required), basic HTTP authentication is performed.
The parameters to the constructor are the same as those for
\class{URLopener}.
\end{classdesc}
Restrictions: Restrictions:
\begin{itemize} \begin{itemize}
@ -175,3 +255,60 @@ to parse and unparse URL strings, the recommended interface for URL
manipulation is in module \refmodule{urlparse}\refstmodindex{urlparse}. manipulation is in module \refmodule{urlparse}\refstmodindex{urlparse}.
\end{itemize} \end{itemize}
\subsection{URLopener Objects \label{urlopener-objs}}
\sectionauthor{Skip Montanaro}{skip@mojam.com}
\class{URLopener} and \class{FancyURLopener} objects have the
following methodsL
\begin{methoddesc}{open}{fullurl\optional{, data}}
Open \var{fullurl} using the appropriate protocol. This method sets
up cache and proxy information, then calls the appropriate open method with
its input arguments. If the scheme is not recognized,
\method{open_unknown()} is called. The \var{data} argument
has the same meaning as the \var{data} argument of \function{urlopen()}.
\end{methoddesc}
\begin{methoddesc}{open_unknown}{fullurl\optional{, data}}
Overridable interface to open unknown URL types.
\end{methoddesc}
\begin{methoddesc}{retrieve}{url\optional{, filename\optional{, reporthook}}}
Retrieves the contents of \var{url} and places it in \var{filename}. The
return value is a tuple consisting of a local filename and either a
\class{mimetools.Message} object containing the response headers (for remote
URLs) or None (for local URLs). The caller must then open and read the
contents of \var{filename}. If \var{filename} is not given and the URL
refers to a local file, the input filename is returned. If the URL is
non-local and \var{filename} is not given, the filename is the output of
\function{tempfile.mktemp()} with a suffix that matches the suffix of the last
path component of the input URL. If \var{reporthook} is given, it must be
a function accepting three numeric parameters. It will be called after each
chunk of data is read from the network. \var{reporthook} is ignored for
local URLs.
\end{methoddesc}
\subsection{Examples}
\nodename{Urllib Examples}
Here is an example session that uses the \samp{GET} method to retrieve
a URL containing parameters:
\begin{verbatim}
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
>>> print f.read()
\end{verbatim}
The following example uses the \samp{POST} method instead:
\begin{verbatim}
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()
\end{verbatim}

View file

@ -1,13 +1,27 @@
\section{\module{whrandom} --- \section{\module{whrandom} ---
Floating point pseudo-random number generator.} Pseudo-random number generator}
\declaremodule{standard}{whrandom}
\declaremodule{standard}{whrandom}
\modulesynopsis{Floating point pseudo-random number generator.} \modulesynopsis{Floating point pseudo-random number generator.}
This module implements a Wichmann-Hill pseudo-random number generator This module implements a Wichmann-Hill pseudo-random number generator
class that is also named \code{whrandom}. Instances of the class that is also named \class{whrandom}. Instances of the
\code{whrandom} class have the following methods: \class{whrandom} class conform to the Random Number Generator
interface described in section \ref{rng-objects}. They also offer the
following method, specific to the Wichmann-Hill algorithm:
\begin{methoddesc}[whrandom]{seed}{\optional{x, y, z}}
Initializes the random number generator from the integers \var{x},
\var{y} and \var{z}. When the module is first imported, the random
number is initialized using values derived from the current time.
If \var{x}, \var{y}, and \var{z} are either omitted or \code{0}, the
seed will be computed from the current system time. If one or two
of the parameters are \code{0}, but not all three, the zero values
are replaced by ones. This causes some apparently different seeds
to be equal, with the corresponding result on the pseudo-random
series produced by the generator.
\end{methoddesc}
\begin{funcdesc}{choice}{seq} \begin{funcdesc}{choice}{seq}
Chooses a random element from the non-empty sequence \var{seq} and returns it. Chooses a random element from the non-empty sequence \var{seq} and returns it.
@ -31,17 +45,23 @@ number is initialized using values derived from the current time.
Returns a random real number \var{N} such that \code{\var{a}<=\var{N}<\var{b}}. Returns a random real number \var{N} such that \code{\var{a}<=\var{N}<\var{b}}.
\end{funcdesc} \end{funcdesc}
When imported, the \code{whrandom} module also creates an instance of When imported, the \module{whrandom} module also creates an instance of
the \code{whrandom} class, and makes the methods of that instance the \class{whrandom} class, and makes the methods of that instance
available at the module level. Therefore one can write either available at the module level. Therefore one can write either
\code{N = whrandom.random()} or: \code{N = whrandom.random()} or:
\begin{verbatim} \begin{verbatim}
generator = whrandom.whrandom() generator = whrandom.whrandom()
N = generator.random() N = generator.random()
\end{verbatim} \end{verbatim}
Note that using separate instances of the generator leads to
independent sequences of pseudo-random numbers.
\begin{seealso} \begin{seealso}
\seemodule{random}{generators for various random distributions} \seemodule{random}{Generators for various random distributions and
documentation for the Random Number Generator
interface.}
\seetext{Wichmann, B. A. \& Hill, I. D., ``Algorithm AS 183: \seetext{Wichmann, B. A. \& Hill, I. D., ``Algorithm AS 183:
An efficient and portable pseudo-random number generator'', An efficient and portable pseudo-random number generator'',
\citetitle{Applied Statistics} 31 (1982) 188-190.} \citetitle{Applied Statistics} 31 (1982) 188-190.}

View file

@ -98,11 +98,12 @@ passed to \method{handle_xml()} default to \code{None} and the string
\code{'no'} respectively. \code{'no'} respectively.
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}{handle_doctype}{tag, data} \begin{methoddesc}{handle_doctype}{tag, pubid, syslit, data}
This method is called when the \samp{<!DOCTYPE...>} tag is processed. This method is called when the \samp{<!DOCTYPE...>} tag is processed.
The arguments are the name of the root element and the uninterpreted The arguments are the name of the root element, the Formal Public
contents of the tag, starting after the white space after the name of Identifier (or \code{None} if not specified), the system identifier,
the root element. and the uninterpreted contents of the internal DTD subset as a string
(or \code{None} if not present).
\end{methoddesc} \end{methoddesc}
\begin{methoddesc}{handle_starttag}{tag, method, attributes} \begin{methoddesc}{handle_starttag}{tag, method, attributes}
@ -226,6 +227,12 @@ implementation calls \method{syntax_error()} to signal an error.
\begin{seealso} \begin{seealso}
\seetext{The XML specification, published by the World Wide Web
Consortium (W3C), is available online at
\url{http://www.w3.org/TR/REC-xml}. References to
additional material on XML are available at
\url{http://www.w3.org/XML/}.}
\seetext{The Python XML Topic Guide provides a great deal of information \seetext{The Python XML Topic Guide provides a great deal of information
on using XML from Python and links to other sources of information on using XML from Python and links to other sources of information
on XML. It's located on the Web at on XML. It's located on the Web at

View file

@ -1,6 +1,3 @@
% XXX The module has been extended (by Jeremy and Andrew) but this
% documentation is incorrect in some cases.
\section{\module{zlib} --- \section{\module{zlib} ---
Compression compatible with \program{gzip}} Compression compatible with \program{gzip}}
@ -17,10 +14,6 @@ most recent version as of April 1999; use a later version if one
is available. There are known incompatibilities between the Python is available. There are known incompatibilities between the Python
module and earlier versions of the zlib library. module and earlier versions of the zlib library.
The documentation for this module is woefully out of date. In some
cases, the doc strings have been updated more recently. In other
cases, they are both stale.
The available exception and functions in this module are: The available exception and functions in this module are:
\begin{excdesc}{error} \begin{excdesc}{error}
@ -68,12 +61,29 @@ The available exception and functions in this module are:
should not be used for authentication or digital signatures. should not be used for authentication or digital signatures.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{decompress}{string\optional{, wbits\optional{, buffsize}}} \begin{funcdesc}{decompress}{string\optional{, wbits\optional{, bufsize}}}
Decompresses the data in \var{string}, returning a string containing Decompresses the data in \var{string}, returning a string containing
the uncompressed data. The \var{wbits} parameter controls the size of the uncompressed data. The \var{wbits} parameter controls the size of
the window buffer. If \var{buffsize} is given, it is used as the the window buffer. If \var{bufsize} is given, it is used as the
initial size of the output buffer. Raises the \exception{error} initial size of the output buffer. Raises the \exception{error}
exception if any error occurs. exception if any error occurs.
The absolute value of \var{wbits} is the base two logarithm of the
size of the history buffer (the ``window size'') used when compressing
data. Its absolute value should be between 8 and 15 for the most
recent versions of the zlib library, larger values resulting in better
compression at the expense of greater memory usage. The default value
is 15. When \var{wbits} is negative, the standard
\program{gzip} header is suppressed; this is an undocumented feature
of the zlib library, used for compatibility with \program{unzip}'s
compression file format.
\var{bufsize} is the initial size of the buffer used to hold
decompressed data. If more space is required, the buffer size will be
increased as needed, so you don't have to get this value exactly
right; tuning it will only save a few calls to \cfunction{malloc()}. The
default size is 16384.
\end{funcdesc} \end{funcdesc}
\begin{funcdesc}{decompressobj}{\optional{wbits}} \begin{funcdesc}{decompressobj}{\optional{wbits}}
@ -106,7 +116,20 @@ prevents compressing any more data. After calling
action is to delete the object. action is to delete the object.
\end{methoddesc} \end{methoddesc}
Decompression objects support the following methods: Decompression objects support the following methods, and a single attribute:
\begin{memberdesc}{unused_data}
A string which contains any unused data from the last string fed to
this decompression object. If the whole string turned out to contain
compressed data, this is \code{""}, the empty string.
The only way to determine where a string of compressed data ends is by
actually decompressing it. This means that when compressed data is
contained part of a larger file, you can only find the end of it by
reading data and feeding it into a decompression object's
\method{decompress} method until the \member{unused_data} attribute is
no longer the empty string.
\end{memberdesc}
\begin{methoddesc}[Decompress]{decompress}{string} \begin{methoddesc}[Decompress]{decompress}{string}
Decompress \var{string}, returning a string containing the Decompress \var{string}, returning a string containing the