checkin of myformat.sty.
Change "\renewcommand{\indexsubitem}{(...)}" to "\setindexsubitem{(...)}"
everywhere.
Some other minor nits that I happened to come across.
Module \code{aifc} defines the following function:
-\renewcommand{\indexsubitem}{(in module aifc)}
+\setindexsubitem{(in module aifc)}
\begin{funcdesc}{open}{file\, mode}
Open an AIFF or AIFF-C file and return an object instance with
methods that are described below. The argument file is either a
Objects returned by \code{aifc.open()} when a file is opened for
reading have the following methods:
-\renewcommand{\indexsubitem}{(aifc object method)}
+\setindexsubitem{(aifc object method)}
\begin{funcdesc}{getnchannels}{}
Return the number of audio channels (1 for mono, 2 for stereo).
\end{funcdesc}
The module defines the following functions:
-\renewcommand{\indexsubitem}{(in module al)}
+\setindexsubitem{(in module al)}
\begin{funcdesc}{openport}{name\, direction\optional{\, config}}
The name and direction arguments are strings. The optional config
Configuration objects (returned by \code{al.newconfig()} have the
following methods:
-\renewcommand{\indexsubitem}{(audio configuration object method)}
+\setindexsubitem{(audio configuration object method)}
\begin{funcdesc}{getqueuesize}{}
Return the queue size.
Port objects (returned by \code{al.openport()} have the following
methods:
-\renewcommand{\indexsubitem}{(audio port object method)}
+\setindexsubitem{(audio port object method)}
\begin{funcdesc}{closeport}{}
Close the port.
\samp{AL_} is omitted. Read the module source for a complete list of
the defined names. Suggested use:
-\bcode\begin{verbatim}
+\begin{verbatim}
import al
from AL import *
-\end{verbatim}\ecode
+\end{verbatim}
The module \code{amoeba} defines the following items:
-\renewcommand{\indexsubitem}{(in module amoeba)}
+\setindexsubitem{(in module amoeba)}
\begin{funcdesc}{name_append}{path\, cap}
Stores a capability in the Amoeba directory tree.
Arguments are the pathname (a string) and the capability (a capability
\emph{a2c}(U).
For example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> amoeba.name_lookup('/profile/cap')
aa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
The following methods are defined for capability objects.
-\renewcommand{\indexsubitem}{(capability method)}
+\setindexsubitem{(capability method)}
\begin{funcdesc}{dir_list}{}
Returns a list of the names of the entries in an Amoeba directory.
\end{funcdesc}
% not the best solution, but it's what you get for documenting both
% at the same time.
-\renewcommand{\indexsubitem}{(in modules anydbm, dumbdbm)}
+\setindexsubitem{(in modules anydbm, dumbdbm)}
\begin{funcdesc}{open}{filename\optional{\, flag\, mode}}
Open the database file \var{filename} and return a corresponding object.
The module defines the following function:
-\renewcommand{\indexsubitem}{(in module array)}
+\setindexsubitem{(in module array)}
\begin{funcdesc}{array}{typecode\optional{\, initializer}}
Return a new array whose items are restricted by \var{typecode}, and
an array with the same type and value using reverse quotes
(\code{``}). Examples:
-\bcode\begin{verbatim}
+\begin{verbatim}
array('l')
array('c', 'hello world')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])
-\end{verbatim}\ecode
+\end{verbatim}
The module defines the following variables and functions:
-\renewcommand{\indexsubitem}{(in module audioop)}
+\setindexsubitem{(in module audioop)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unknown number of bytes
per sample, etc.
treated equal. If this is a problem the stereo fragment should be split
into two mono fragments first and recombined later. Here is an example
of how to do that:
-\bcode\begin{verbatim}
+\begin{verbatim}
def mul_stereo(sample, width, lfactor, rfactor):
lsample = audioop.tomono(sample, width, 1, 0)
rsample = audioop.tomono(sample, width, 0, 1)
lsample = audioop.tostereo(lsample, width, 1, 0)
rsample = audioop.tostereo(rsample, width, 0, 1)
return audioop.add(lsample, rsample, width)
-\end{verbatim}\ecode
+\end{verbatim}
%
If you use the ADPCM coder to build network packets and you want your
protocol to be stateless (i.e.\ to be able to tolerate packet loss)
fast way to do this is to pick the most energetic piece of the output
sample, locate that in the input sample and subtract the whole output
sample from the input sample:
-\bcode\begin{verbatim}
+\begin{verbatim}
def echocancel(outputdata, inputdata):
pos = audioop.findmax(outputdata, 800) # one tenth second
out_test = outputdata[pos*2:]
postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
return audioop.add(inputdata, outputdata, 2)
-\end{verbatim}\ecode
+\end{verbatim}
string \code{'www.python.org'} is encoded as the string
\code{'d3d3LnB5dGhvbi5vcmc=\e n'}.
-\renewcommand{\indexsubitem}{(in module base64)}
+\setindexsubitem{(in module base64)}
\begin{funcdesc}{decode}{input, output}
Decode the contents of the \var{input} file and write the resulting
\index{URL}
\index{httpd}
-\renewcommand{\indexsubitem}{(in module BaseHTTPServer)}
+\setindexsubitem{(in module BaseHTTPServer)}
This module defines two classes for implementing HTTP servers
(web servers). Usually, this module isn't used directly, but is used
requests to a handler. Code to create and run the server looks like
this:
-\bcode\begin{verbatim}
+\begin{verbatim}
def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
-\end{verbatim}\ecode
+\end{verbatim}
%
The \code{HTTPServer} class builds on the \code{TCPServer} class by
storing the server address as instance
the relevant information is stored into instance variables of the
handler.
-\renewcommand{\indexsubitem}{(BaseHTTPRequestHandler instance variable)}
+\setindexsubitem{(BaseHTTPRequestHandler instance variable)}
\code{BaseHTTPRequestHandler} has the following instance variables:
to this stream.
\end{datadesc}
-\renewcommand{\indexsubitem}{(BaseHTTPRequestHandler class variable)}
+\setindexsubitem{(BaseHTTPRequestHandler class variable)}
\code{BaseHTTPRequestHandler} has the following class variables:
(see the \code{error_message_format} class variable).
\end{datadesc}
-\renewcommand{\indexsubitem}{(BaseHTTPRequestHandler method)}
+\setindexsubitem{(BaseHTTPRequestHandler method)}
A \code{BaseHTTPRequestHandler} instance has the following methods:
\section{Standard Module \sectcode{Bastion}}
\label{module-Bastion}
\stmodindex{Bastion}
-\renewcommand{\indexsubitem}{(in module Bastion)}
+\setindexsubitem{(in module Bastion)}
% I'm concerned that the word 'bastion' won't be understood by people
% for whom English is a second language, making the module name
The \code{binhex} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module binhex)}
+\setindexsubitem{(in module binhex)}
\begin{funcdesc}{binhex}{input\, output}
Convert a binary file with filename \var{input} to binhex file
The \code{uu} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module uu)}
+\setindexsubitem{(in module uu)}
\begin{funcdesc}{encode}{in_file\, out_file\optional{\, name\, mode}}
Uuencode file \var{in_file} into file \var{out_file}. The uuencoded
The \code{binascii} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module binascii)}
+\setindexsubitem{(in module binascii)}
\begin{funcdesc}{a2b_uu}{string}
Convert a single line of uuencoded data back to binary and return the
Module \code{cd} defines the following functions and constants:
-\renewcommand{\indexsubitem}{(in module cd)}
+\setindexsubitem{(in module cd)}
\begin{funcdesc}{createparser}{}
Create and return an opaque parser object. The methods of the parser
Player objects (returned by \code{cd.open()}) have the following
methods:
-\renewcommand{\indexsubitem}{(CD player object method)}
+\setindexsubitem{(CD player object method)}
\begin{funcdesc}{allowremoval}{}
Unlocks the eject button on the CD-ROM drive permitting the user to
Parser objects (returned by \code{cd.createparser()}) have the
following methods:
-\renewcommand{\indexsubitem}{(CD parser object method)}
+\setindexsubitem{(CD parser object method)}
\begin{funcdesc}{addcallback}{type\, func\, arg}
Adds a callback for the parser. The parser has callbacks for eight
\indexii{MIME}{headers}
\index{URL}
-\renewcommand{\indexsubitem}{(in module cgi)}
+\setindexsubitem{(in module cgi)}
Support module for CGI (Common Gateway Interface) scripts.
telling the client what kind of data is following. Python code to
generate a minimal header section looks like this:
-\bcode\begin{verbatim}
+\begin{verbatim}
print "Content-type: text/html" # HTML is following
print # blank line, end of headers
-\end{verbatim}\ecode
+\end{verbatim}
%
The second section is usually HTML, which allows the client software
to display nicely formatted text with header, in-line images, etc.
Here's Python code that prints a simple piece of HTML:
-\bcode\begin{verbatim}
+\begin{verbatim}
print "<TITLE>CGI script output</TITLE>"
print "<H1>This is my first CGI script</H1>"
print "Hello, world!"
-\end{verbatim}\ecode
+\end{verbatim}
%
(It may not be fully legal HTML according to the letter of the
standard, but any browser will understand it.)
\code{Content-type} header and blank line have already been printed) checks that
the fields \code{name} and \code{addr} are both set to a non-empty string:
-\bcode\begin{verbatim}
+\begin{verbatim}
form = cgi.FieldStorage()
form_ok = 0
if form.has_key("name") and form.has_key("addr"):
print "Please fill in the name and addr fields."
return
...further form processing here...
-\end{verbatim}\ecode
+\end{verbatim}
%
Here the fields, accessed through \code{form[key]}, are themselves instances
of \code{FieldStorage} (or \code{MiniFieldStorage}, depending on the form encoding).
instance or a list of instances. For example, here's code that
concatenates any number of username fields, separated by commas:
-\bcode\begin{verbatim}
+\begin{verbatim}
username = form["username"]
if type(username) is type([]):
# Multiple username fields specified
else:
# Single username field specified
usernames = username.value
-\end{verbatim}\ecode
+\end{verbatim}
%
If a field represents an uploaded file, the value attribute reads the
entire file in memory as a string. This may not be what you want. You can
file attribute. You can then read the data at leasure from the file
attribute:
-\bcode\begin{verbatim}
+\begin{verbatim}
fileitem = form["userfile"]
if fileitem.file:
# It's an uploaded file; count lines
line = fileitem.file.readline()
if not line: break
linecount = linecount + 1
-\end{verbatim}\ecode
+\end{verbatim}
%
The file upload draft standard entertains the possibility of uploading
multiple files from one field (using a recursive \code{multipart/*}
that the first line of the script contains \code{\#!} starting in column 1
followed by the pathname of the Python interpreter, for instance:
-\bcode\begin{verbatim}
+\begin{verbatim}
#!/usr/local/bin/python
-\end{verbatim}\ecode
+\end{verbatim}
%
Make sure the Python interpreter exists and is executable by ``others''.
default module search path, you can change the path in your script,
before importing other modules, e.g.:
-\bcode\begin{verbatim}
+\begin{verbatim}
import sys
sys.path.insert(0, "/usr/home/joe/lib/python")
sys.path.insert(0, "/usr/local/lib/python")
-\end{verbatim}\ecode
+\end{verbatim}
%
(This way, the directory inserted last will be searched first!)
in the standard \file{cgi-bin} directory, it should be possible to send it a
request by entering a URL into your browser of the form:
-\bcode\begin{verbatim}
+\begin{verbatim}
http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
-\end{verbatim}\ecode
+\end{verbatim}
%
If this gives an error of type 404, the server cannot find the script
-- perhaps you need to install it in a different directory. If it
function from your script: replace its main code with the single
statement
-\bcode\begin{verbatim}
+\begin{verbatim}
cgi.test()
-\end{verbatim}\ecode
+\end{verbatim}
%
This should produce the same results as those gotten from installing
the \file{cgi.py} file itself.
For example:
-\bcode\begin{verbatim}
+\begin{verbatim}
import sys
import traceback
print "Content-type: text/html"
except:
print "\n\n<PRE>"
traceback.print_exc()
-\end{verbatim}\ecode
+\end{verbatim}
%
Notes: The assignment to \code{sys.stderr} is needed because the traceback
prints to \code{sys.stderr}.
module, you can use an even more robust approach (which only uses
built-in modules):
-\bcode\begin{verbatim}
+\begin{verbatim}
import sys
sys.stderr = sys.stdout
print "Content-type: text/plain"
print
...your code here...
-\end{verbatim}\ecode
+\end{verbatim}
%
This relies on the Python interpreter to print the traceback. The
content type of the output is set to plain text, which disables all
\label{module-cmath}
\bimodindex{cmath}
-\renewcommand{\indexsubitem}{(in module cmath)}
+\setindexsubitem{(in module cmath)}
This module is always available.
It provides access to mathematical functions for complex numbers.
The functions are:
The \code{code} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module code)}
+\setindexsubitem{(in module code)}
\begin{funcdesc}{compile_command}{source, \optional{filename\optional{, symbol}}}
This function is useful for programs that want to emulate Python's
The \code{commands} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module commands)}
+\setindexsubitem{(in module commands)}
\begin{funcdesc}{getstatusoutput}{cmd}
Execute the string \var{cmd} in a shell with \code{os.popen()} and return
a 2-tuple (status, output). \var{cmd} is actually run as
\section{Standard Module \sectcode{copy}}
\label{module-copy}
\stmodindex{copy}
-\renewcommand{\indexsubitem}{(copy function)}
+\setindexsubitem{(copy function)}
\ttindex{copy}
\ttindex{deepcopy}
Interface summary:
-\bcode\begin{verbatim}
+\begin{verbatim}
import copy
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
-\end{verbatim}\ecode
+\end{verbatim}
%
For module specific errors, \code{copy.error} is raised.
\code{__setstate__()}. See the description of module \code{pickle}
for information on these methods.
\refstmodindex{pickle}
-\renewcommand{\indexsubitem}{(copy protocol)}
+\setindexsubitem{(copy protocol)}
\ttindex{__getinitargs__}
\ttindex{__getstate__}
\ttindex{__setstate__}
constructors which are not classes. Such constructors may be factory
functions or class instances.
-\renewcommand{\indexsubitem}{(in module copy_reg)}
+\setindexsubitem{(in module copy_reg)}
\begin{funcdesc}{constructor}{object}
Declares \var{object} to be a valid constructor.
attempting to crack \UNIX{} passwords with a dictionary.
\index{crypt(3)}
-\renewcommand{\indexsubitem}{(in module crypt)}
+\setindexsubitem{(in module crypt)}
\begin{funcdesc}{crypt}{word\, salt}
\var{word} will usually be a user's password. \var{salt} is a
2-character string which will be used to select one of 4096 variations
The module defines the following constant and functions:
-\renewcommand{\indexsubitem}{(in module dbm)}
+\setindexsubitem{(in module dbm)}
\begin{excdesc}{error}
Raised on dbm-specific errors, such as I/O errors. \code{KeyError} is
raised for general mapping errors like specifying an incorrect key.
Example: Given the function myfunc
-\bcode\begin{verbatim}
+\begin{verbatim}
def myfunc(alist):
return len(alist)
-\end{verbatim}\ecode
+\end{verbatim}
the following command can be used to get the disassembly of \code{myfunc()}:
The \code{dis} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module dis)}
+\setindexsubitem{(in module dis)}
\begin{funcdesc}{dis}{\optional{bytesource}}
Disassemble the \var{bytesource} object. \var{bytesource} can denote
The Python compiler currently generates the following byte code
instructions.
-\renewcommand{\indexsubitem}{(byte code insns)}
+\setindexsubitem{(byte code insns)}
\begin{opcodedesc}{STOP_CODE}{}
Indicates end-of-code to the compiler, not used by the interpreter.
Pushes a slice object on the stack. \var{argc} must be 2 or 3. If it
is 2, \code{slice(TOS1, TOS)} is pushed; if it is 3,
\code{slice(TOS2, TOS1, TOS)} is pushed.
-See the \code{slice()} built-in function.
+See the \code{slice()}\bifuncindex{slice} built-in function.
\end{opcodedesc}
\section{Standard Module \sectcode{errno}}
\stmodindex{errno}
-\renewcommand{\indexsubitem}{(in module errno)}
+\setindexsubitem{(in module errno)}
This module makes available standard errno system symbols.
The value of each symbol is the corresponding integer value.
beware that there is nothing to prevent user code from raising an
inappropriate error.
-\renewcommand{\indexsubitem}{(built-in exception base class)}
+\setindexsubitem{(built-in exception base class)}
The following exceptions are only used as base classes for other
exceptions. When string-based standard exceptions are used, they
\code{KeyError}.
\end{excdesc}
-\renewcommand{\indexsubitem}{(built-in exception)}
+\setindexsubitem{(built-in exception)}
The following exceptions are the exceptions that are actually raised.
They are class objects, except when the \code{-X} option is used to
The module defines the following functions:
-\renewcommand{\indexsubitem}{(in module struct)}
+\setindexsubitem{(in module struct)}
\begin{funcdesc}{fcntl}{fd\, op\optional{\, arg}}
Perform the requested operation on file descriptor \code{\var{fd}}.
Examples (all on a SVR4 compliant system):
-\bcode\begin{verbatim}
+\begin{verbatim}
import struct, FCNTL
file = open(...)
lockdata = struct.pack('hhllhh', FCNTL.F_WRLCK, 0, 0, 0, 0, 0)
rv = fcntl(file.fileno(), FCNTL.F_SETLKW, lockdata)
-\end{verbatim}\ecode
+\end{verbatim}
%
Note that in the first example the return value variable \code{rv} will
hold an integer value; in the second example it will hold a string
about what they do, see the description of the equivalent C function
in the FORMS documentation:
-\renewcommand{\indexsubitem}{(in module fl)}
+\setindexsubitem{(in module fl)}
\begin{funcdesc}{make_form}{type\, width\, height}
Create a form with given type, width and height. This returns a
\dfn{form} object, whose methods are described below.
these methods are listed here.
\begin{flushleft}
-\renewcommand{\indexsubitem}{(form object method)}
+\setindexsubitem{(form object method)}
\begin{funcdesc}{show_form}{placement\, bordertype\, name}
Show the form.
\end{funcdesc}
Besides methods specific to particular kinds of FORMS objects, all
FORMS objects also have the following methods:
-\renewcommand{\indexsubitem}{(FORMS object method)}
+\setindexsubitem{(FORMS object method)}
\begin{funcdesc}{set_call_back}{function\, argument}
Set the object's callback function and argument. When the object
needs interaction, the callback function will be called with two
\samp{FL_} is omitted. Read the module source for a complete list of
the defined names. Suggested use:
-\bcode\begin{verbatim}
+\begin{verbatim}
import fl
from FL import *
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{Standard Module \sectcode{flp}}
\label{module-flp}
It supports the following operations:
-\renewcommand{\indexsubitem}{(in module fm)}
+\setindexsubitem{(in module fm)}
\begin{funcdesc}{init}{}
Initialization function.
Calls \code{fminit()}.
Font handle objects support the following operations:
-\renewcommand{\indexsubitem}{(font handle method)}
+\setindexsubitem{(font handle method)}
\begin{funcdesc}{scalefont}{factor}
Returns a handle for a scaled version of this font.
Calls \code{fmscalefont(\var{fh}, \var{factor})}.
for pathname expansion (\code{glob} uses \code{fnmatch()} to
match filename segments).
-\renewcommand{\indexsubitem}{(in module fnmatch)}
+\setindexsubitem{(in module fnmatch)}
\begin{funcdesc}{fnmatch}{filename, pattern}
Test whether the \var{filename} string matches the \var{pattern}
\label{module-formatter}
\stmodindex{formatter}
-\renewcommand{\indexsubitem}{(in module formatter)}
+\setindexsubitem{(in module formatter)}
This module supports two interface definitions, each with mulitple
implementations. The \emph{formatter} interface is used by the
The following attributes are defined for formatter instance objects:
-\renewcommand{\indexsubitem}{(formatter object data)}
+\setindexsubitem{(formatter object data)}
\begin{datadesc}{writer}
The writer instance with which the formatter interacts.
\end{datadesc}
-\renewcommand{\indexsubitem}{(formatter object method)}
+\setindexsubitem{(formatter object method)}
\begin{funcdesc}{end_paragraph}{blanklines}
Close any open paragraphs and insert at least \code{blanklines}
Most applications may use one of these classes without modification or
subclassing.
-\renewcommand{\indexsubitem}{(in module formatter)}
+\setindexsubitem{(in module formatter)}
\begin{funcdesc}{NullFormatter}{\optional{writer\code{ = None}}}
A formatter which does nothing. If \code{writer} is omitted, a
class as a formatter, the writer must typically be provided by the
application.
-\renewcommand{\indexsubitem}{(writer object method)}
+\setindexsubitem{(writer object method)}
\begin{funcdesc}{flush}{}
Flush any buffered output or device control events.
examples by this module. Most applications will need to derive new
writer classes from the \code{NullWriter} class.
-\renewcommand{\indexsubitem}{(in module formatter)}
+\setindexsubitem{(in module formatter)}
\begin{funcdesc}{NullWriter}{}
A writer which only provides the interface definition; no actions are
\stmodindex{ftplib}
\indexii{FTP}{protocol}
-\renewcommand{\indexsubitem}{(in module ftplib)}
+\setindexsubitem{(in module ftplib)}
This module defines the class \code{FTP} and a few related items. The
\code{FTP} class implements the client side of the FTP protocol. You
Here's a sample session using the \code{ftplib} module:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> from ftplib import FTP
>>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
>>> ftp.login() # user anonymous, passwd user@hostname
.
.
>>> ftp.quit()
-\end{verbatim}\ecode
+\end{verbatim}
%
The module defines the following items:
FTP instances have the following methods:
-\renewcommand{\indexsubitem}{(FTP object method)}
+\setindexsubitem{(FTP object method)}
\begin{funcdesc}{set_debuglevel}{level}
Set the instance's debugging level. This controls the amount of
are always available. They are listed here in alphabetical order.
-\renewcommand{\indexsubitem}{(built-in function)}
+\setindexsubitem{(built-in function)}
\begin{funcdesc}{__import__}{name\optional{, globals\optional{, locals\optional{, fromlist}}}}
This function is invoked by the \code{import} statement. It
and for class instances, methods are not included.
The resulting list is sorted alphabetically. For example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import sys
>>> dir()
['sys']
>>> dir(sys)
['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
>>>
-\end{verbatim}\ecode
+\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{divmod}{a\, b}
called. The return value is the result of the evaluated expression.
Syntax errors are reported as exceptions. Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> x = 1
>>> print eval('x+1')
2
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
This function can also be used to execute arbitrary code objects
(e.g.\ created by \code{compile()}). In this case pass a code
greater than \var{stop}. \var{step} must not be zero (or else an
exception is raised). Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
>>> range(1, 0)
[]
>>>
-\end{verbatim}\ecode
+\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{raw_input}{\optional{prompt}}
converts it to a string (stripping a trailing newline), and returns that.
When \EOF{} is read, \code{EOFError} is raised. Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
>>>
-\end{verbatim}\ecode
+\end{verbatim}
If the \code{readline} module was loaded, then
\code{raw_input()} will use it to provide elaborate
\obindex{type}
For instance:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import types
>>> if isinstance(x, types.StringType): print "It's a string"
-\end{verbatim}\ecode
+\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{vars}{\optional{object}}
The module defines the following constant and functions:
-\renewcommand{\indexsubitem}{(in module gdbm)}
+\setindexsubitem{(in module gdbm)}
\begin{excdesc}{error}
Raised on \code{gdbm}-specific errors, such as I/O errors. \code{KeyError} is
raised for general mapping errors like specifying an incorrect key.
Returns the key that follows \var{key} in the traversal. The
following code prints every key in the database \code{db}, without having to
create a list in memory that contains them all:
-\bcode\begin{verbatim}
+\begin{verbatim}
k=db.firstkey()
while k!=None:
print k
k=db.nextkey(k)
-\end{verbatim}\ecode
+\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{reorganize}{}
An example using only \UNIX{} style options:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import getopt, string
>>> args = string.split('-a -b -cfoo -d bar a1 a2')
>>> args
>>> args
['a1', 'a2']
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
Using long option names is equally easy:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = string.split(s)
>>> args
>>> args
['a1', 'a2']
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
The exception
\code{getopt.error}
only used to specify the length of an array argument are omitted.
For example, the C call
-\bcode\begin{verbatim}
+\begin{verbatim}
lmdef(deftype, index, np, props)
-\end{verbatim}\ecode
+\end{verbatim}
%
is translated to Python as
-\bcode\begin{verbatim}
+\begin{verbatim}
lmdef(deftype, index, props)
-\end{verbatim}\ecode
+\end{verbatim}
%
\item
Output arguments are omitted from the argument list; they are
comes first in the tuple.
Examples: the C call
-\bcode\begin{verbatim}
+\begin{verbatim}
getmcolor(i, &red, &green, &blue)
-\end{verbatim}\ecode
+\end{verbatim}
%
is translated to Python as
-\bcode\begin{verbatim}
+\begin{verbatim}
red, green, blue = getmcolor(i)
-\end{verbatim}\ecode
+\end{verbatim}
%
\end{itemize}
The following functions are non-standard or have special argument
conventions:
-\renewcommand{\indexsubitem}{(in module gl)}
+\setindexsubitem{(in module gl)}
\begin{funcdesc}{varray}{argument}
%JHXXX the argument-argument added
Equivalent to but faster than a number of
Here is a tiny but complete example GL program in Python:
-\bcode\begin{verbatim}
+\begin{verbatim}
import gl, GL, time
def main():
time.sleep(5)
main()
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{Standard Modules \sectcode{GL} and \sectcode{DEVICE}}
\nodename{GL and DEVICE}
\section{Standard Module \sectcode{glob}}
\label{module-glob}
\stmodindex{glob}
-\renewcommand{\indexsubitem}{(in module glob)}
+\setindexsubitem{(in module glob)}
The \code{glob} module finds all the pathnames matching a specified
pattern according to the rules used by the \UNIX{} shell. No tilde
will produce the following results. Notice how any leading components
of the path are preserved.
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
-\end{verbatim}\ecode
+\end{verbatim}
\stmodindex{gopherlib}
\indexii{Gopher}{protocol}
-\renewcommand{\indexsubitem}{(in module gopherlib)}
+\setindexsubitem{(in module gopherlib)}
This module provides a minimal implementation of client side of the
the Gopher protocol. It is used by the module \code{urllib} to handle
It defines the following items:
-\renewcommand{\indexsubitem}{(in module grp)}
+\setindexsubitem{(in module grp)}
\begin{funcdesc}{getgrgid}{gid}
Return the group database entry for the given numeric group ID.
\end{funcdesc}
object, though it's not possible to use the \code{seek()} and
\code{tell()} methods to access the file randomly.
-\renewcommand{\indexsubitem}{(in module gzip)}
+\setindexsubitem{(in module gzip)}
\begin{funcdesc}{open}{fileobj\optional{\, filename\optional{\, mode\, compresslevel}}}
Returns a new \code{GzipFile} object on top of \var{fileobj}, which
can be a regular file, a \code{StringIO} object, or any object which
\index{HTML}
\index{hypertext}
-\renewcommand{\indexsubitem}{(in module htmllib)}
+\setindexsubitem{(in module htmllib)}
This module defines a class which can serve as a base for parsing text
files formatted in the HyperText Mark-up Language (HTML). The class
unprocessed data, call the \method{close()} method.
For example, to parse the entire contents of a file, use:
-\bcode\begin{verbatim}
+\begin{verbatim}
parser.feed(open('myfile.html').read())
parser.close()
-\end{verbatim}\ecode
+\end{verbatim}
%
\item
The interface to define semantics for HTML tags is very simple: derive
In addition to tag methods, the \class{HTMLParser} class provides some
additional methods and instance variables for use within tag methods.
-\renewcommand{\indexsubitem}{(HTMLParser attribute)}
+\setindexsubitem{(HTMLParser attribute)}
\begin{datadesc}{formatter}
This is the formatter instance associated with the parser.
affects the operation of \method{handle_data()} and \method{save_end()}.
\end{datadesc}
-\renewcommand{\indexsubitem}{(HTMLParser method)}
+\setindexsubitem{(HTMLParser method)}
\begin{funcdesc}{anchor_bgn}{href\, name\, type}
This method is called at the start of an anchor region. The arguments
\stmodindex{httplib}
\index{HTTP}
-\renewcommand{\indexsubitem}{(in module httplib)}
+\setindexsubitem{(in module httplib)}
This module defines a class which implements the client side of the
HTTP protocol. It is normally not used directly --- the module
following calls all create instances that connect to the server at the
same host and port:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> h1 = httplib.HTTP('www.cwi.nl')
>>> h2 = httplib.HTTP('www.cwi.nl:80')
>>> h3 = httplib.HTTP('www.cwi.nl', 80)
-\end{verbatim}\ecode
+\end{verbatim}
%
Once an \code{HTTP} instance has been connected to an HTTP server, it
should be used as follows:
\code{HTTP} instances have the following methods:
-\renewcommand{\indexsubitem}{(HTTP method)}
+\setindexsubitem{(HTTP method)}
\begin{funcdesc}{set_debuglevel}{level}
Set the debugging level (the amount of debugging output printed).
Here is an example session:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import httplib
>>> h = httplib.HTTP('www.cwi.nl')
>>> h.putrequest('GET', '/index.html')
>>> data = f.read() # Get the raw HTML
>>> f.close()
>>>
-\end{verbatim}\ecode
+\end{verbatim}
The module defines the following variables and functions:
-\renewcommand{\indexsubitem}{(in module imageop)}
+\setindexsubitem{(in module imageop)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unknown number of bits
The module defines the following variables and functions:
-\renewcommand{\indexsubitem}{(in module imgfile)}
+\setindexsubitem{(in module imgfile)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unsupported file type, etc.
\end{excdesc}
The \code{imghdr} module defines the following function:
-\renewcommand{\indexsubitem}{(in module imghdr)}
+\setindexsubitem{(in module imghdr)}
\begin{funcdesc}{what}{filename\optional{\, h}}
Tests the image data contained in the file named by \var{filename},
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import imghdr
>>> imghdr.what('/tmp/bass.gif')
'gif'
-\end{verbatim}\ecode
+\end{verbatim}
the \code{import} statement. It defines the following constants and
functions:
-\renewcommand{\indexsubitem}{(in module imp)}
+\setindexsubitem{(in module imp)}
\begin{funcdesc}{get_magic}{}
Return the magic string value used to recognize byte-compiled code
\code{imp.find_module()} has been extended and
\code{imp.load_module()} has been added in 1.4.)
-\bcode\begin{verbatim}
+\begin{verbatim}
import imp import sys
def __import__(name, globals=None, locals=None, fromlist=None):
# Since we may exit via an exception, close fp explicitly.
if fp:
fp.close()
-\end{verbatim}\ecode
+\end{verbatim}
A more complete example that implements hierarchical module names and
includes a \code{reload()} function can be found in the standard
The \code{jpeg} module defines these functions:
-\renewcommand{\indexsubitem}{(in module jpeg)}
+\setindexsubitem{(in module jpeg)}
\begin{funcdesc}{compress}{data\, w\, h\, b}
Treat data as a pixmap of width \var{w} and height \var{h}, with \var{b} bytes per
pixel. The data is in SGI GL order, so the first pixel is in the
The \code{locale} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module locale)}
+\setindexsubitem{(in module locale)}
\begin{funcdesc}{setlocale}{category\optional{\, value}}
If \var{value} is specified, modifies the locale setting for the
\code{setlocale()} is not thread safe on most systems. Applications
typically start with a call of
-\bcode\begin{verbatim}
+\begin{verbatim}
import locale
locale.setlocale(locale.LC_ALL,"")
-\end{verbatim}\ecode
+\end{verbatim}
This sets the locale for all categories to the user's default setting
(typically specified in the \code{LANG} environment variable). If the
locale is not changed thereafter, using multithreading should not
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import locale
>>> locale.open(locale.LC_ALL,"de") #setting locale to German
>>> locale.strcoll("f\344n","foo") #comparing a string containing an umlaut
>>> can.close()
-\end{verbatim}\ecode
+\end{verbatim}
\label{module-mailbox}
\stmodindex{mailbox}
-\renewcommand{\indexsubitem}{(in module mailbox)}
+\setindexsubitem{(in module mailbox)}
This module defines a number of classes that allow easy and uniform
access to mail messages in a (unix) mailbox.
\section{Standard Module \sectcode{mailcap}}
\label{module-mailcap}
\stmodindex{mailcap}
-\renewcommand{\indexsubitem}{(in module mailcap)}
+\setindexsubitem{(in module mailcap)}
Mailcap files are used to configure how MIME-aware applications such
as mail readers and Web browsers react to files with different MIME
\end{funcdesc}
An example usage:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import mailcap
>>> d=mailcap.getcaps()
>>> mailcap.findmatch(d, 'video/mpeg', filename='/tmp/tmp1223')
('xmpeg /tmp/tmp1223', {'view': 'xmpeg %s'})
-\end{verbatim}\ecode
+\end{verbatim}
The module defines these functions:
-\renewcommand{\indexsubitem}{(in module marshal)}
+\setindexsubitem{(in module marshal)}
\begin{funcdesc}{dump}{value\, file}
Write the value on the open file. The value must be a supported
\label{module-math}
\bimodindex{math}
-\renewcommand{\indexsubitem}{(in module math)}
+\setindexsubitem{(in module math)}
This module is always available.
It provides access to the mathematical functions defined by the \C{}
standard.
For example, to obtain the digest of the string {\tt"Nobody inspects
the spammish repetition"}:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import md5
>>> m = md5.new()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
-\end{verbatim}\ecode
+\end{verbatim}
%
More condensed:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> md5.new("Nobody inspects the spammish repetition").digest()
'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
-\end{verbatim}\ecode
+\end{verbatim}
%
-\renewcommand{\indexsubitem}{(in module md5)}
+\setindexsubitem{(in module md5)}
\begin{funcdesc}{new}{\optional{arg}}
Return a new md5 object. If \var{arg} is present, the method call
An md5 object has the following methods:
-\renewcommand{\indexsubitem}{(md5 method)}
+\setindexsubitem{(md5 method)}
\begin{funcdesc}{update}{arg}
Update the md5 object with the string \var{arg}. Repeated calls are
equivalent to a single call with the concatenation of all the
\label{module-mimetools}
\stmodindex{mimetools}
-\renewcommand{\indexsubitem}{(in module mimetools)}
+\setindexsubitem{(in module mimetools)}
This module defines a subclass of the class \code{rfc822.Message} and
a number of utility functions that are useful for the manipulation for
The \code{mimetools.Message} class defines the following methods in
addition to the \code{rfc822.Message} class:
-\renewcommand{\indexsubitem}{(mimetool.Message method)}
+\setindexsubitem{(mimetool.Message method)}
\begin{funcdesc}{getplist}{}
Return the parameter list of the \code{Content-type} header. This is
\section{Standard Module \sectcode{mimify}}
\stmodindex{mimify}
-\renewcommand{\indexsubitem}{(in module mimify)}
+\setindexsubitem{(in module mimify)}
The mimify module defines two functions to convert mail messages to
and from MIME format. The mail message can be either a simple message
below for an exact description). An mpz-number is printed like this:
\code{mpz(\var{value})}.
-\renewcommand{\indexsubitem}{(in module mpz)}
+\setindexsubitem{(in module mpz)}
\begin{funcdesc}{mpz}{value}
Create a new mpz-number. \var{value} can be an integer, a long,
another mpz-number, or even a string. If it is a string, it is
An mpz-number has one method:
-\renewcommand{\indexsubitem}{(mpz method)}
+\setindexsubitem{(mpz method)}
\begin{funcdesc}{binary}{}
Convert this mpz-number to a binary string, where the number has been
stored as an array of radix-256 digits, least significant digit first.
\code{hamneggs()} from that module, you can use any of the following
possibilities:
-\bcode\begin{verbatim}
+\begin{verbatim}
import spam.ham # *not* "import spam" !!!
spam.ham.hamneggs()
-\end{verbatim}\ecode
+\end{verbatim}
%
-\bcode\begin{verbatim}
+\begin{verbatim}
from spam import ham
ham.hamneggs()
-\end{verbatim}\ecode
+\end{verbatim}
%
-\bcode\begin{verbatim}
+\begin{verbatim}
from spam.ham import hamneggs
hamneggs()
-\end{verbatim}\ecode
+\end{verbatim}
%
\code{import spam} creates an
empty package named \code{spam} if one does not already exist, but it does
\code{spam.__init__} is a submodule of package spam. It can refer to
spam's namespace as \code{__} (two underscores):
-\bcode\begin{verbatim}
+\begin{verbatim}
__.spam_inited = 1 # Set a package-level variable
-\end{verbatim}\ecode
+\end{verbatim}
%
Additional initialization code (setting up variables, importing other
submodules) can be performed in \file{spam/__init__.py}.
\stmodindex{nntplib}
\indexii{NNTP}{protocol}
-\renewcommand{\indexsubitem}{(in module nntplib)}
+\setindexsubitem{(in module nntplib)}
This module defines the class \code{NNTP} which implements the client
side of the NNTP protocol. It can be used to implement a news reader
statistics about a newsgroup and print the subjects of the last 10
articles:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> s = NNTP('news.cwi.nl')
>>> resp, count, first, last, name = s.group('comp.lang.python')
>>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
>>> s.quit()
'205 news.cwi.nl closing connection. Goodbye.'
>>>
-\end{verbatim}\ecode
+\end{verbatim}
To post an article from a file (this assumes that the article has
valid headers):
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> s = NNTP('news.cwi.nl')
>>> f = open('/tmp/article')
>>> s.post(f)
>>> s.quit()
'205 news.cwi.nl closing connection. Goodbye.'
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
The module itself defines the following items:
If the server's response indicates an error, the method raises one of
the above exceptions.
-\renewcommand{\indexsubitem}{(NNTP object method)}
+\setindexsubitem{(NNTP object method)}
\begin{funcdesc}{getwelcome}{}
Return the welcome message sent by the server in reply to the initial
The \code{operator} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module operator)}
+\setindexsubitem{(in module operator)}
\begin{funcdesc}{add}{a, b}
Return \var{a} \code{+} \var{b}, for \var{a} and \var{b} numbers.
Example: Build a dictionary that maps the ordinals from \code{0} to
\code{256} to their character equivalents.
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import operator
>>> d = {}
>>> keys = range(256)
>>> vals = map(chr, keys)
>>> map(operator.setitem, [d]*len(keys), keys, vals)
-\end{verbatim}\ecode
+\end{verbatim}
In addition to whatever the correct OS dependent module exports, the
following variables and functions are always exported by \code{os}:
-\renewcommand{\indexsubitem}{(in module os)}
+\setindexsubitem{(in module os)}
\begin{datadesc}{name}
The name of the OS dependent module imported. The following names
The module is too large to document here in its entirety.
One interesting function:
-\renewcommand{\indexsubitem}{(in module panel)}
+\setindexsubitem{(in module panel)}
\begin{funcdesc}{defpanellist}{filename}
Parses a panel description file containing S-expressions written by the
\emph{Panel Editor}
and compiled code objects, but there are also functions which serve to
query the type of parse tree represented by an AST object.
-\renewcommand{\indexsubitem}{(in module parser)}
+\setindexsubitem{(in module parser)}
\subsection{Creating AST Objects}
this purpose, using the \module{parser} module to produce an
intermediate data structure is equivelent to the code
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> code = compile('a + 5', 'eval')
>>> a = 5
>>> eval(code)
10
-\end{verbatim}\ecode
+\end{verbatim}
%
The equivelent operation using the \module{parser} module is somewhat
longer, and allows the intermediate internal parse tree to be retained
as an AST object:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import parser
>>> ast = parser.expr('a + 5')
>>> code = parser.compileast(ast)
>>> a = 5
>>> eval(code)
10
-\end{verbatim}\ecode
+\end{verbatim}
%
An application which needs both AST and code objects can package this
code into readily available functions:
-\bcode\begin{verbatim}
+\begin{verbatim}
import parser
def load_suite(source_string):
ast = parser.expr(source_string)
code = parser.compileast(ast)
return ast, code
-\end{verbatim}\ecode
+\end{verbatim}
%
\subsubsection{Information Discovery}
a module consisting of a docstring and nothing else. (See file
\file{docstring.py}.)
-\bcode\begin{verbatim}
+\begin{verbatim}
"""Some documentation.
"""
-\end{verbatim}\ecode
+\end{verbatim}
%
Using the interpreter to take a look at the parse tree, we find a
bewildering mass of numbers and parentheses, with the documentation
buried deep in nested tuples.
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import parser
>>> import pprint
>>> ast = parser.suite(open('docstring.py').read())
(4, ''))),
(4, ''),
(0, ''))
-\end{verbatim}\ecode
+\end{verbatim}
%
The numbers at the first element of each node in the tree are the node
types; they map directly to terminal and non-terminal symbols in the
the pattern matching, returning a boolean and a dictionary of variable
name to value mappings. (See file \file{example.py}.)
-\bcode\begin{verbatim}
+\begin{verbatim}
from types import ListType, TupleType
def match(pattern, data, vars=None):
if not same:
break
return same, vars
-\end{verbatim}\ecode
+\end{verbatim}
%
Using this simple representation for syntactic variables and the symbolic
node types, the pattern for the candidate docstring subtrees becomes
fairly readable. (See file \file{example.py}.)
-\bcode\begin{verbatim}
+\begin{verbatim}
import symbol
import token
)))))))))))))))),
(token.NEWLINE, '')
))
-\end{verbatim}\ecode
+\end{verbatim}
%
Using the \function{match()} function with this pattern, extracting the
module docstring from the parse tree created previously is easy:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> found, vars = match(DOCSTRING_STMT_PATTERN, tup[1])
>>> found
1
>>> vars
{'docstring': '"""Some documentation.\012"""'}
-\end{verbatim}\ecode
+\end{verbatim}
%
Once specific data can be extracted from a location where it is
expected, the question of where information can be expected
objects requires further examination. Here is the relevant part of
the \class{SuiteInfoBase} definition from \file{example.py}:
-\bcode\begin{verbatim}
+\begin{verbatim}
class SuiteInfoBase:
_docstring = ''
_name = ''
elif cstmt[0] == symbol.classdef:
name = cstmt[2][1]
self._class_info[name] = ClassInfo(cstmt)
-\end{verbatim}\ecode
+\end{verbatim}
%
After initializing some internal state, the constructor calls the
\method{_extract_info()} method. This method performs the bulk of the
while the long form uses an indented block and allows nested
definitions:
-\bcode\begin{verbatim}
+\begin{verbatim}
def make_power(exp):
"Make a function that raises an argument to the exponent `exp'."
def raiser(x, y=exp):
return x ** y
return raiser
-\end{verbatim}\ecode
+\end{verbatim}
%
When the short form is used, the code block may contain a docstring as
the first, and possibly only, \constant{small_stmt} element. The
blocks. A high-level function can be used to extract the complete set
of information from a source file. (See file \file{example.py}.)
-\bcode\begin{verbatim}
+\begin{verbatim}
def get_docs(fileName):
source = open(fileName).read()
import os
ast = parser.suite(source)
tup = parser.ast2tuple(ast)
return ModuleInfo(tup, basename)
-\end{verbatim}\ecode
+\end{verbatim}
%
This provides an easy-to-use interface to the documentation of a
module. If information is required which is not extracted by the code
This module also provides one additional data object:
-\renewcommand{\indexsubitem}{(in module symbol)}
+\setindexsubitem{(in module symbol)}
\begin{datadesc}{sym_name}
This module also provides one data object and some functions. The
functions mirror definitions in the Python C header files.
-\renewcommand{\indexsubitem}{(in module token)}
+\setindexsubitem{(in module token)}
\begin{datadesc}{tok_name}
\stmodindex{pdb}
\index{debugging}
-\renewcommand{\indexsubitem}{(in module pdb)}
+\setindexsubitem{(in module pdb)}
The module \code{pdb} defines an interactive source code debugger for
Python programs. It supports setting
The debugger's prompt is ``\code{(Pdb) }''.
Typical usage to run a program under control of the debugger is:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import pdb
>>> import mymodule
>>> pdb.run('mymodule.test()')
NameError: 'spam'
> <string>(1)?()
(Pdb)
-\end{verbatim}\ecode
+\end{verbatim}
%
\code{pdb.py} can also be invoked as
a script to debug other scripts. For example:
Typical usage to inspect a crashed program is:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import pdb
>>> import mymodule
>>> mymodule.test()
> ./mymodule.py(3)test2()
-> print spam
(Pdb)
-\end{verbatim}\ecode
+\end{verbatim}
%
The module defines the following functions; each enters the debugger
in a slightly different way:
of the statement resembles a debugger command.
To set a global variable, you can prefix the assignment
command with a ``\code{global}'' command on the same line, e.g.:
-\bcode\begin{verbatim}
+\begin{verbatim}
(Pdb) global list_options; list_options = ['-l']
(Pdb)
-\end{verbatim}\ecode
+\end{verbatim}
%
\item[q(uit)]
\indexii{flattening}{objects}
\indexii{pickling}{objects}
-\renewcommand{\indexsubitem}{(in module pickle)}
+\setindexsubitem{(in module pickle)}
The \code{pickle} module implements a basic but powerful algorithm for
``pickling'' (a.k.a.\ serializing, marshalling or flattening) nearly
First of all, the class must be defined at the top level in a module.
Furthermore, all its instance variables must be picklable.
-\renewcommand{\indexsubitem}{(pickle protocol)}
+\setindexsubitem{(pickle protocol)}
When a pickled class instance is unpickled, its \code{__init__()} method
is normally \emph{not} invoked. \strong{Note:} This is a deviation
Therefore, the restriction that the class must be defined at the top
level in a module applies to pickled classes as well.
-\renewcommand{\indexsubitem}{(in module pickle)}
+\setindexsubitem{(in module pickle)}
The interface can be summarized as follows.
To pickle an object \code{x} onto a file \code{f}, open for writing:
-\bcode\begin{verbatim}
+\begin{verbatim}
p = pickle.Pickler(f)
p.dump(x)
-\end{verbatim}\ecode
+\end{verbatim}
%
A shorthand for this is:
-\bcode\begin{verbatim}
+\begin{verbatim}
pickle.dump(x, f)
-\end{verbatim}\ecode
+\end{verbatim}
%
To unpickle an object \code{x} from a file \code{f}, open for reading:
-\bcode\begin{verbatim}
+\begin{verbatim}
u = pickle.Unpickler(f)
x = u.load()
-\end{verbatim}\ecode
+\end{verbatim}
%
A shorthand is:
-\bcode\begin{verbatim}
+\begin{verbatim}
x = pickle.load(f)
-\end{verbatim}\ecode
+\end{verbatim}
%
The \code{Pickler} class only calls the method \code{f.write()} with a
string argument. The \code{Unpickler} calls the methods \code{f.read()}
Module \code{posix} defines the following data items:
-\renewcommand{\indexsubitem}{(data in module posix)}
+\setindexsubitem{(data in module posix)}
\begin{datadesc}{environ}
A dictionary representing the string environment at the time
the interpreter was started.
\code{putenv()} automatically called whenever an item is changed.
\end{datadesc}
-\renewcommand{\indexsubitem}{(exception in module posix)}
+\setindexsubitem{(exception in module posix)}
\begin{excdesc}{error}
This exception is raised when a \POSIX{} function returns a
\POSIX{}-related error (e.g., not for illegal argument types). Its
It defines the following functions and constants:
-\renewcommand{\indexsubitem}{(in module posix)}
+\setindexsubitem{(in module posix)}
\begin{funcdesc}{chdir}{path}
Change the current working directory to \var{path}.
\end{funcdesc}
The posixfile module defines the following constants:
-\renewcommand{\indexsubitem}{(in module posixfile)}
+\setindexsubitem{(in module posixfile)}
\begin{datadesc}{SEEK_SET}
offset is calculated from the start of the file
\end{datadesc}
The posixfile module defines the following functions:
-\renewcommand{\indexsubitem}{(in module posixfile)}
+\setindexsubitem{(in module posixfile)}
\begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}}
Create a new posixfile object with the given filename and mode. The
The posixfile object defines the following additional methods:
-\renewcommand{\indexsubitem}{(posixfile method)}
+\setindexsubitem{(posixfile method)}
\begin{funcdesc}{lock}{fmt\, \optional{len\optional{\, start\optional{\, whence}}}}
Lock the specified section of the file that the file object is
referring to. The format is explained
Examples:
-\bcode\begin{verbatim}
+\begin{verbatim}
from posixfile import *
file = open('/tmp/test', 'w')
...
file.lock('u')
file.close()
-\end{verbatim}\ecode
+\end{verbatim}
module \code{os} and use \code{os.path}.
\refstmodindex{os}
-\renewcommand{\indexsubitem}{(in module posixpath)}
+\setindexsubitem{(in module posixpath)}
\begin{funcdesc}{basename}{p}
Return the base name of pathname
The \code{pprint} module defines one class:
-\renewcommand{\indexsubitem}{(in module pprint)}
+\setindexsubitem{(in module pprint)}
% First the implementation class:
PrettyPrinter instances (returned by \code{PrettyPrinter()} above)
have the following methods.
-\renewcommand{\indexsubitem}{(PrettyPrinter method)}
+\setindexsubitem{(PrettyPrinter method)}
\begin{funcdesc}{pformat}{object}
Return the formatted representation of \var{object}. This takes into
To profile an application with a main entry point of \samp{foo()}, you
would add the following to your module:
-\bcode\begin{verbatim}
+\begin{verbatim}
import profile
profile.run("foo()")
-\end{verbatim}\ecode
+\end{verbatim}
%
The above action would cause \samp{foo()} to be run, and a series of
informative lines (the profile) to be printed. The above approach is
can supply a file name as the second argument to the \code{run()}
function:
-\bcode\begin{verbatim}
+\begin{verbatim}
import profile
profile.run("foo()", 'fooprof')
-\end{verbatim}\ecode
+\end{verbatim}
%
\code{profile.py} can also be invoked as
a script to profile another script. For example:
\code{pstats} module. Typically you would load the statistics data as
follows:
-\bcode\begin{verbatim}
+\begin{verbatim}
import pstats
p = pstats.Stats('fooprof')
-\end{verbatim}\ecode
+\end{verbatim}
%
The class \code{Stats} (the above code just created an instance of
this class) has a variety of methods for manipulating and printing the
\code{profile.run()} above, what was printed was the result of three
method calls:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.strip_dirs().sort_stats(-1).print_stats()
-\end{verbatim}\ecode
+\end{verbatim}
%
The first method removed the extraneous path from all the module
names. The second method sorted all the entries according to the
with the semantics of the old profiler). The third method printed out
all the statistics. You might try the following sort calls:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.sort_stats('name')
p.print_stats()
-\end{verbatim}\ecode
+\end{verbatim}
%
The first call will actually sort the list by function name, and the
second call will print out the statistics. The following are some
interesting calls to experiment with:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.sort_stats('cumulative').print_stats(10)
-\end{verbatim}\ecode
+\end{verbatim}
%
This sorts the profile by cumulative time in a function, and then only
prints the ten most significant lines. If you want to understand what
If you were looking to see what functions were looping a lot, and
taking a lot of time, you would do:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.sort_stats('time').print_stats(10)
-\end{verbatim}\ecode
+\end{verbatim}
%
to sort according to time spent within each function, and then print
the statistics for the top ten functions.
You might also try:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.sort_stats('file').print_stats('__init__')
-\end{verbatim}\ecode
+\end{verbatim}
%
This will sort all the statistics by file name, and then print out
statistics for only the class init methods ('cause they are spelled
with \code{__init__} in them). As one final example, you could try:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.sort_stats('time', 'cum').print_stats(.5, 'init')
-\end{verbatim}\ecode
+\end{verbatim}
%
This line sorts statistics with a primary key of time, and a secondary
key of cumulative time, and then prints out some of the statistics.
If you wondered what functions called the above functions, you could
now (\samp{p} is still sorted according to the last criteria) do:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.print_callers(.5, 'init')
-\end{verbatim}\ecode
+\end{verbatim}
%
and you would get a list of callers for each of the listed functions.
If you want more functionality, you're going to have to read the
manual, or guess what the following functions do:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.print_callees()
p.add('fooprof')
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{What Is Deterministic Profiling?}
\nodename{Deterministic Profiling}
\section{Reference Manual}
-\renewcommand{\indexsubitem}{(profiler function)}
+\setindexsubitem{(profiler function)}
The primary entry point for the profiler is the global function
\code{profile.run()}. It is typically used to create any profile
standard name string (file/line/function-name) that is presented in
each line. The following is a typical output from such a call:
-\bcode\begin{verbatim}
+\begin{verbatim}
main()
2706 function calls (2004 primitive calls) in 4.504 CPU seconds
2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects)
43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate)
...
-\end{verbatim}\ecode
+\end{verbatim}
The first line indicates that this profile was generated by the call:\\
\code{profile.run('main()')}, and hence the exec'ed string is
\subsection{The \sectcode{Stats} Class}
-\renewcommand{\indexsubitem}{(Stats method)}
+\setindexsubitem{(Stats method)}
\begin{funcdesc}{strip_dirs}{}
This method for the \code{Stats} class removes all leading path information
defined by the \code{re} module). If several restrictions are
provided, then they are applied sequentially. For example:
-\bcode\begin{verbatim}
+\begin{verbatim}
print_stats(.1, "foo:")
-\end{verbatim}\ecode
+\end{verbatim}
%
would first limit the printing to first 10\% of list, and then only
print functions that were part of filename \samp{.*foo:}. In
contrast, the command:
-\bcode\begin{verbatim}
+\begin{verbatim}
print_stats("foo:", .1)
-\end{verbatim}\ecode
+\end{verbatim}
%
would limit the list to all functions having file names \samp{.*foo:},
and then proceed to only print the first 10\% of them.
return the instance that is being processed, so that the commands can
be strung together. For example:
-\bcode\begin{verbatim}
+\begin{verbatim}
pstats.Stats('foofile').strip_dirs().sort_stats('cum') \
.print_stats().ignore()
-\end{verbatim}\ecode
+\end{verbatim}
%
would perform all the indicated functions, but it would not return
the final reference to the \code{Stats} instance.%
be used to obtain this constant for a given platform (see discussion
in section Limitations above).
-\bcode\begin{verbatim}
+\begin{verbatim}
import profile
pr = profile.Profile()
pr.calibrate(100)
pr.calibrate(100)
pr.calibrate(100)
-\end{verbatim}\ecode
+\end{verbatim}
%
The argument to calibrate() is the number of times to try to do the
sample calls to get the CPU times. If your computer is \emph{very}
fast, you might have to do:
-\bcode\begin{verbatim}
+\begin{verbatim}
pr.calibrate(1000)
-\end{verbatim}\ecode
+\end{verbatim}
%
or even:
-\bcode\begin{verbatim}
+\begin{verbatim}
pr.calibrate(10000)
-\end{verbatim}\ecode
+\end{verbatim}
%
The object of this exercise is to get a fairly consistent result.
When you have a consistent answer, you are ready to use that number in
class should be modified to install the calibration constant on a Sun
Sparcstation 1000:
-\bcode\begin{verbatim}
+\begin{verbatim}
def trace_dispatch(self, frame, event, arg):
t = self.timer()
t = t[0] + t[1] - self.t - .00053 # Calibration constant
r = self.timer()
self.t = r[0] + r[1] - t # put back unrecorded delta
return
-\end{verbatim}\ecode
+\end{verbatim}
%
Note that if there is no calibration constant, then the line
containing the callibration constant should simply say:
-\bcode\begin{verbatim}
+\begin{verbatim}
t = t[0] + t[1] - self.t # no calibration constant
-\end{verbatim}\ecode
+\end{verbatim}
%
You can also achieve the same results using a derived class (and the
profiler will actually run equally fast!!), but the above method is
the constructor for the class. Consider passing the name of a
function to call into the constructor:
-\bcode\begin{verbatim}
+\begin{verbatim}
pr = profile.Profile(your_time_func)
-\end{verbatim}\ecode
+\end{verbatim}
%
The resulting profiler will call \code{your_time_func()} instead of
\code{os.times()}. The function should return either a single number
user's code. It is also a lot more accurate than the old profiler, as
it does not charge all its overhead time to the user's code.
-\bcode\begin{verbatim}
+\begin{verbatim}
class OldProfile(Profile):
def trace_dispatch_exception(self, frame, t):
callers[func_caller]
nc = nc + callers[func_caller]
self.stats[nor_func] = nc, nc, tt, ct, nor_callers
-\end{verbatim}\ecode
+\end{verbatim}
%
\subsection{HotProfile Class}
the basic profiler is so fast, that is probably not worth the savings
to give up the data, but this class still provides a nice example.
-\bcode\begin{verbatim}
+\begin{verbatim}
class HotProfile(Profile):
def trace_dispatch_exception(self, frame, t):
nc, tt = self.timings[func]
nor_func = self.func_normalize(func)
self.stats[nor_func] = nc, nc, tt, 0, {}
-\end{verbatim}\ecode
+\end{verbatim}
It defines the following items:
-\renewcommand{\indexsubitem}{(in module pwd)}
+\setindexsubitem{(in module pwd)}
\begin{funcdesc}{getpwuid}{uid}
Return the password database entry for the given numeric user ID.
\end{funcdesc}
The \code{Queue} module defines the following exception:
-\renewcommand{\indexsubitem}{(in module Queue)}
+\setindexsubitem{(in module Queue)}
\begin{excdesc}{Empty}
Exception raised when non-blocking get (e.g. \code{get_nowait()}) is
is not described here. See the source code for details. The public
interface methods are:
-\renewcommand{\indexsubitem}{(__init__ method)}
+\setindexsubitem{(__init__ method)}
\begin{funcdesc}{__init__}{maxsize}
Constructor for the class. \var{maxsize} is an integer that sets the
zero, the queue size is infinite.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(qsize method)}
+\setindexsubitem{(qsize method)}
\begin{funcdesc}{qsize}{}
Returns the approximate size of the queue. Because of multithreading
semantics, this number is not reliable.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(empty method)}
+\setindexsubitem{(empty method)}
\begin{funcdesc}{empty}{}
Returns 1 if the queue is empty, 0 otherwise. Because of
multithreading semantics, this is not reliable.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(full method)}
+\setindexsubitem{(full method)}
\begin{funcdesc}{full}{}
Returns 1 if the queue is full, 0 otherwise. Because of
multithreading semantics, this is not reliable.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(put method)}
+\setindexsubitem{(put method)}
\begin{funcdesc}{put}{item}
Puts \var{item} into the queue.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(get method)}
+\setindexsubitem{(get method)}
\begin{funcdesc}{get}{}
Gets and returns an item from the queue, blocking if necessary until
one is available.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(get_nowait method)}
+\setindexsubitem{(get_nowait method)}
\begin{funcdesc}{get_nowait}{}
Gets and returns an item from the queue if one is immediately
\indexii{quoted printable}{encoding}
\index{MIME!quoted-printable encoding}
-\renewcommand{\indexsubitem}{(in module quopri)}
+\setindexsubitem{(in module quopri)}
\begin{funcdesc}{decode}{input\, output}
Decode the contents of the \var{input} file and write the resulting
compatibility, the \code{rand} module is now considered obsolete; if
possible, use the \code{whrandom} module instead.
-\renewcommand{\indexsubitem}{(in module rand)}
+\setindexsubitem{(in module rand)}
\begin{funcdesc}{choice}{seq}
Returns a random element from the sequence \var{seq}.
used in common mathematical practice; most of these equations can be
found in any statistics text.
-\renewcommand{\indexsubitem}{(in module random)}
+\setindexsubitem{(in module random)}
\begin{funcdesc}{betavariate}{alpha\, beta}
Beta distribution. Conditions on the parameters are \code{alpha>-1}
and \code{beta>-1}.
The module defines the following functions and constants, and an exception:
-\renewcommand{\indexsubitem}{(in module re)}
+\setindexsubitem{(in module re)}
\begin{funcdesc}{compile}{pattern\optional{\, flags}}
Compile a regular expression pattern into a regular expression
The sequence
%
-\bcode\begin{verbatim}
+\begin{verbatim}
prog = re.compile(pat)
result = prog.match(str)
-\end{verbatim}\ecode
+\end{verbatim}
%
is equivalent to
1.5 release, \var{maxsplit} was ignored. This has been fixed in
later releases.)
%
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> re.split('[\W]+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('([\W]+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('[\W]+', 'Words, words, words.', 1)
['Words', 'words, words.']
-\end{verbatim}\ecode
+\end{verbatim}
%
This function combines and extends the functionality of
the old \code{regsub.split()} and \code{regsub.splitx()}.
The function takes a single match object argument, and returns the
replacement string. For example:
%
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> def dashrepl(matchobj):
... if matchobj.group(0) == '-': return ' '
... else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
-\end{verbatim}\ecode
+\end{verbatim}
%
The pattern may be a string or a
regex object; if you need to specify
Compiled regular expression objects support the following methods and
attributes:
-\renewcommand{\indexsubitem}{(re method)}
+\setindexsubitem{(re method)}
\begin{funcdesc}{match}{string\optional{\, pos}\optional{\, endpos}}
If zero or more characters at the beginning of \var{string} match
this regular expression, return a corresponding
Identical to the \code{subn()} function, using the compiled pattern.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(regex attribute)}
+\setindexsubitem{(regex attribute)}
\begin{datadesc}{flags}
The flags argument used when the regex object was compiled, or 0 if no
The module defines these functions, and an exception:
-\renewcommand{\indexsubitem}{(in module regex)}
+\setindexsubitem{(in module regex)}
\begin{funcdesc}{match}{pattern\, string}
Return how many characters at the beginning of \var{string} match
The sequence
-\bcode\begin{verbatim}
+\begin{verbatim}
prog = regex.compile(pat)
result = prog.match(str)
-\end{verbatim}\ecode
+\end{verbatim}
%
is equivalent to
-\bcode\begin{verbatim}
+\begin{verbatim}
result = regex.match(pat, str)
-\end{verbatim}\ecode
+\end{verbatim}
but the version using \code{compile()} is more efficient when multiple
regular expressions are used concurrently in a single program. (The
\noindent
Compiled regular expression objects support these methods:
-\renewcommand{\indexsubitem}{(regex method)}
+\setindexsubitem{(regex method)}
\begin{funcdesc}{match}{string\optional{\, pos}}
Return how many characters at the beginning of \var{string} match
the compiled regular expression. Return \code{-1} if the string
\noindent
Compiled regular expressions support these data attributes:
-\renewcommand{\indexsubitem}{(regex attribute)}
+\setindexsubitem{(regex attribute)}
\begin{datadesc}{regs}
When the last call to the \code{match()} or \code{search()} method found a
conversion help, see the URL
\url{http://starship.skyport.net/crew/amk/regex/regex-to-re.html}.)
-\renewcommand{\indexsubitem}{(in module regsub)}
+\setindexsubitem{(in module regsub)}
\begin{funcdesc}{sub}{pat\, repl\, str}
Replace the first occurrence of pattern \var{pat} in string
A single exception is defined for errors:
-\renewcommand{\indexsubitem}{(in module resource)}
+\setindexsubitem{(in module resource)}
\begin{excdesc}{error}
The functions described below may raise this error if the underlying
\section{Standard Module \sectcode{rexec}}
\label{module-rexec}
\stmodindex{rexec}
-\renewcommand{\indexsubitem}{(in module rexec)}
+\setindexsubitem{(in module rexec)}
-This module contains the \code{RExec} class, which supports
+This module contains the \class{RExec} class, which supports
\code{r_exec()}, \code{r_eval()}, \code{r_execfile()}, and
\code{r_import()} methods, which are restricted versions of the standard
Python functions \code{exec()}, \code{eval()}, \code{execfile()}, and
the \code{import} statement.
Code executed in this restricted environment will
only have access to modules and functions that are deemed safe; you
-can subclass \code{RExec} to add or remove capabilities as desired.
+can subclass \class{RExec} to add or remove capabilities as desired.
-\emph{Note:} The \code{RExec} class can prevent code from performing
+\emph{Note:} The \class{RExec} class can prevent code from performing
unsafe operations like reading or writing disk files, or using TCP/IP
sockets. However, it does not protect against code using extremely
large amounts of memory or CPU time.
\begin{funcdesc}{RExec}{\optional{hooks\optional{\, verbose}}}
-Returns an instance of the \code{RExec} class.
+Returns an instance of the \class{RExec} class.
\var{hooks} is an instance of the \code{RHooks} class or a subclass of it.
If it is omitted or \code{None}, the default \code{RHooks} class is
instantiated.
-Whenever the RExec module searches for a module (even a built-in one)
-or reads a module's code, it doesn't actually go out to the file
-system itself. Rather, it calls methods of an RHooks instance that
-was passed to or created by its constructor. (Actually, the RExec
-object doesn't make these calls---they are made by a module loader
-object that's part of the RExec object. This allows another level of
-flexibility, e.g. using packages.)
-
-By providing an alternate RHooks object, we can control the
+Whenever the \module{RExec} module searches for a module (even a
+built-in one) or reads a module's code, it doesn't actually go out to
+the file system itself. Rather, it calls methods of an \class{RHooks}
+instance that was passed to or created by its constructor. (Actually,
+the \class{RExec} object doesn't make these calls --- they are made by
+a module loader object that's part of the \class{RExec} object. This
+allows another level of flexibility, e.g. using packages.)
+
+By providing an alternate \class{RHooks} object, we can control the
file system accesses made to import a module, without changing the
actual algorithm that controls the order in which those accesses are
-made. For instance, we could substitute an RHooks object that passes
-all filesystem requests to a file server elsewhere, via some RPC
-mechanism such as ILU. Grail's applet loader uses this to support
+made. For instance, we could substitute an \class{RHooks} object that
+passes all filesystem requests to a file server elsewhere, via some
+RPC mechanism such as ILU. Grail's applet loader uses this to support
importing applets from a URL for a directory.
If \var{verbose} is true, additional debugging output may be sent to
standard output.
\end{funcdesc}
-The RExec class has the following class attributes, which are used by the
-\code{__init__} method. Changing them on an existing instance won't
-have any effect; instead, create a subclass of \code{RExec} and assign
-them new values in the class definition. Instances of the new class
-will then use those new values. All these attributes are tuples of
-strings.
+The \class{RExec} class has the following class attributes, which are
+used by the \code{__init__()} method. Changing them on an existing
+instance won't have any effect; instead, create a subclass of
+\class{RExec} and assign them new values in the class definition.
+Instances of the new class will then use those new values. All these
+attributes are tuples of strings.
-\renewcommand{\indexsubitem}{(RExec object attribute)}
+\setindexsubitem{(RExec object attribute)}
\begin{datadesc}{nok_builtin_names}
Contains the names of built-in functions which will \emph{not} be
available to programs running in the restricted environment. The
-value for \code{RExec} is \code{('open',} \code{'reload',}
+value for \class{RExec} is \code{('open',} \code{'reload',}
\code{'__import__')}. (This gives the exceptions, because by far the
majority of built-in functions are harmless. A subclass that wants to
override this variable should probably start with the value from the
\begin{datadesc}{ok_builtin_modules}
Contains the names of built-in modules which can be safely imported.
-The value for \code{RExec} is \code{('audioop',} \code{'array',}
+The value for \class{RExec} is \code{('audioop',} \code{'array',}
\code{'binascii',} \code{'cmath',} \code{'errno',} \code{'imageop',}
\code{'marshal',} \code{'math',} \code{'md5',} \code{'operator',}
\code{'parser',} \code{'regex',} \code{'rotor',} \code{'select',}
\begin{datadesc}{ok_path}
Contains the directories which will be searched when an \code{import}
is performed in the restricted environment.
-The value for \code{RExec} is the same as \code{sys.path} (at the time
+The value for \class{RExec} is the same as \code{sys.path} (at the time
the module is loaded) for unrestricted code.
\end{datadesc}
% Should this be called ok_os_names?
Contains the names of the functions in the \code{os} module which will be
available to programs running in the restricted environment. The
-value for \code{RExec} is \code{('error',} \code{'fstat',}
+value for \class{RExec} is \code{('error',} \code{'fstat',}
\code{'listdir',} \code{'lstat',} \code{'readlink',} \code{'stat',}
\code{'times',} \code{'uname',} \code{'getpid',} \code{'getppid',}
\code{'getcwd',} \code{'getuid',} \code{'getgid',} \code{'geteuid',}
\begin{datadesc}{ok_sys_names}
Contains the names of the functions and variables in the \code{sys}
module which will be available to programs running in the restricted
-environment. The value for \code{RExec} is \code{('ps1',}
+environment. The value for \class{RExec} is \code{('ps1',}
\code{'ps2',} \code{'copyright',} \code{'version',} \code{'platform',}
\code{'exit',} \code{'maxint')}.
\end{datadesc}
-RExec instances support the following methods:
-\renewcommand{\indexsubitem}{(RExec object method)}
+\class{RExec} instances support the following methods:
+\setindexsubitem{(RExec object method)}
\begin{funcdesc}{r_eval}{code}
\var{code} must either be a string containing a Python expression, or
restricted environment.
\end{funcdesc}
-\code{RExec} objects must also support various methods which will be
+\class{RExec} objects must also support various methods which will be
implicitly called by code executing in the restricted environment.
Overriding these methods in a subclass is used to change the policies
enforced by a restricted environment.
Method called when \code{open()} is called in the restricted
environment. The arguments are identical to those of \code{open()},
and a file object (or a class instance compatible with file objects)
-should be returned. \code{RExec}'s default behaviour is allow opening
+should be returned. \class{RExec}'s default behaviour is allow opening
any file for reading, but forbidding any attempt to write a file. See
the example below for an implementation of a less restrictive
\code{r_open()}.
And their equivalents with access to restricted standard I/O streams:
\begin{funcdesc}{s_import}{modulename\optional{\, globals, locals, fromlist}}
-Import the module \var{modulename}, raising an \code{ImportError}
+Import the module \var{modulename}, raising an \exception{ImportError}
exception if the module is considered unsafe.
\end{funcdesc}
\subsection{An example}
Let us say that we want a slightly more relaxed policy than the
-standard RExec class. For example, if we're willing to allow files in
-\file{/tmp} to be written, we can subclass the \code{RExec} class:
+standard \class{RExec} class. For example, if we're willing to allow
+files in \file{/tmp} to be written, we can subclass the \class{RExec}
+class:
-\bcode\begin{verbatim}
+\begin{verbatim}
class TmpWriterRExec(rexec.RExec):
def r_open(self, file, mode='r', buf=-1):
if mode in ('r', 'rb'):
raise IOError, "'..' in filename forbidden"
else: raise IOError, "Illegal open() mode"
return open(file, mode, buf)
-\end{verbatim}\ecode
+\end{verbatim}
%
Notice that the above code will occasionally forbid a perfectly valid
filename; for example, code in the restricted environment won't be
\label{module-rfc822}
\stmodindex{rfc822}
-\renewcommand{\indexsubitem}{(in module rfc822)}
+\setindexsubitem{(in module rfc822)}
This module defines a class, \code{Message}, which represents a
collection of ``email headers'' as defined by the Internet standard
The module defines the following variables and functions:
-\renewcommand{\indexsubitem}{(in module rgbimg)}
+\setindexsubitem{(in module rgbimg)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unsupported file type, etc.
\end{excdesc}
The available functions in this module are:
-\renewcommand{\indexsubitem}{(in module rotor)}
+\setindexsubitem{(in module rotor)}
\begin{funcdesc}{newrotor}{key\optional{\, numrotors}}
Return a rotor object. \var{key} is a string containing the encryption key
for the object; it can contain arbitrary binary data. The key will be used
Rotor objects have the following methods:
-\renewcommand{\indexsubitem}{(rotor method)}
+\setindexsubitem{(rotor method)}
\begin{funcdesc}{setkey}{key}
Sets the rotor's key to \var{key}.
\end{funcdesc}
\end{funcdesc}
An example usage:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import rotor
>>> rt = rotor.newrotor('key', 12)
>>> rt.encrypt('bar')
>>> rt.decrypt('\357\375$')
'l(\315'
>>> del rt
-\end{verbatim}\ecode
+\end{verbatim}
%
The module's code is not an exact simulation of the original Enigma device;
it implements the rotor encryption scheme differently from the original. The
This module provides access to the function \code{select} available in
most \UNIX{} versions. It defines the following:
-\renewcommand{\indexsubitem}{(in module select)}
+\setindexsubitem{(in module select)}
\begin{excdesc}{error}
The exception raised when an error occurs. The accompanying value is
a pair containing the numeric error code from \code{errno} and the
The \code{SGMLParser} class must be instantiated without arguments.
It has the following interface methods:
-\renewcommand{\indexsubitem}{(SGMLParser method)}
+\setindexsubitem{(SGMLParser method)}
\begin{funcdesc}{reset}{}
Reset the instance. Loses all unprocessed data. This is called
To summarize the interface (\code{key} is a string, \code{data} is an
arbitrary object):
-\bcode\begin{verbatim}
+\begin{verbatim}
import shelve
d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
list = d.keys() # a list of all existing keys (slow!)
d.close() # close it
-\end{verbatim}\ecode
+\end{verbatim}
%
Restrictions:
The variables defined in the \module{signal} module are:
-\renewcommand{\indexsubitem}{(in module signal)}
+\setindexsubitem{(in module signal)}
\begin{datadesc}{SIG_DFL}
This is one of two standard signal handling options; it will simply
perform the default function for the signal. For example, on most
In earlier versions of Python (up to and including 1.5a3), scripts or
modules that needed to use site-specific modules would place
-\code{import site} somewhere near the top of their code. This is no
+\samp{import site} somewhere near the top of their code. This is no
longer necessary.
This will append site-specific paths to to the module search path.
files, \file{foo.pth} and \file{bar.pth}. Assume \file{foo.pth}
contains the following:
-\bcode\begin{verbatim}
+\begin{verbatim}
# foo package configuration
foo
bar
bletch
-\end{verbatim}\ecode
+\end{verbatim}
and \file{bar.pth} contains:
-\bcode\begin{verbatim}
+\begin{verbatim}
# bar package configuration
bar
-\end{verbatim}\ecode
+\end{verbatim}
Then the following directories are added to \code{sys.path}, in this
order:
-\bcode\begin{verbatim}
+\begin{verbatim}
/usr/local/python1.5/site-packages/bar
/usr/local/python1.5/site-packages/foo
-\end{verbatim}\ecode
+\end{verbatim}
Note that \file{bletch} is omitted because it doesn't exist; the
\file{bar} directory precedes the \file{foo} directory because
The module \code{socket} exports the following constants and functions:
-\renewcommand{\indexsubitem}{(in module socket)}
+\setindexsubitem{(in module socket)}
\begin{excdesc}{error}
This exception is raised for socket- or address-related errors.
The accompanying value is either a string telling what went wrong or a
\code{makefile()} these correspond to \UNIX{} system calls applicable to
sockets.
-\renewcommand{\indexsubitem}{(socket method)}
+\setindexsubitem{(socket method)}
\begin{funcdesc}{accept}{}
Accept a connection.
The socket must be bound to an address and listening for connections.
socket it is listening on but on the new socket returned by
\code{accept}.
-\bcode\begin{verbatim}
+\begin{verbatim}
# Echo server program
from socket import *
HOST = '' # Symbolic name meaning the local host
if not data: break
conn.send(data)
conn.close()
-\end{verbatim}\ecode
+\end{verbatim}
%
-\bcode\begin{verbatim}
+\begin{verbatim}
# Echo client program
from socket import *
HOST = 'daring.cwi.nl' # The remote host
data = s.recv(1024)
s.close()
print 'Received', `data`
-\end{verbatim}\ecode
+\end{verbatim}
%
\begin{seealso}
\seemodule{SocketServer}{classes that simplify writing network servers}
Server classes have the same external methods and attributes, no
matter what network protocol they use:
-\renewcommand{\indexsubitem}{(SocketServer protocol)}
+\setindexsubitem{(SocketServer protocol)}
%XXX should data and methods be intermingled, or separate?
% how should the distinction between class and instance variables be
\label{module-soundex}
\bimodindex{soundex}
-\renewcommand{\indexsubitem}{(in module soundex)}
+\setindexsubitem{(in module soundex)}
The soundex algorithm takes an English word, and returns an
easily-computed hash of it; this hash is intended to be the same for
words that sound alike. This module provides an interface to the
The \code{stat} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module stat)}
+\setindexsubitem{(in module stat)}
\begin{funcdesc}{S_ISDIR}{mode}
Return non-zero if the mode was gotten from a directory.
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
import os, sys
from stat import *
print 'frobbed', file
if __name__ == '__main__': process(sys.argv[1], f)
-\end{verbatim}\ecode
+\end{verbatim}
The following functions are defined in the \code{stdwin} module:
-\renewcommand{\indexsubitem}{(in module stdwin)}
+\setindexsubitem{(in module stdwin)}
\begin{funcdesc}{open}{title}
Open a new window whose initial title is given by the string argument.
Return a window object; window object methods are described below.%
Return the default foreground color for unknown color names.
Hint: the following code tests whether you are on a machine that
supports more than two colors:
-\bcode\begin{verbatim}
+\begin{verbatim}
if stdwin.fetchcolor('black') <> \
stdwin.fetchcolor('red') <> \
stdwin.fetchcolor('white'):
print 'color machine'
else:
print 'monochrome machine'
-\end{verbatim}\ecode
+\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{setfgcolor}{pixel}
by their \code{close()} method or when they are garbage-collected.
Window objects have the following methods:
-\renewcommand{\indexsubitem}{(window method)}
+\setindexsubitem{(window method)}
\begin{funcdesc}{begindrawing}{}
Return a drawing object, whose methods (described below) allow drawing
is called.
Drawing objects have the following methods:
-\renewcommand{\indexsubitem}{(drawing method)}
+\setindexsubitem{(drawing method)}
\begin{funcdesc}{box}{rect}
Draw a box just inside a rectangle.
The menu is destroyed when the menu object is deleted.
The following methods are defined:
-\renewcommand{\indexsubitem}{(menu method)}
+\setindexsubitem{(menu method)}
\begin{funcdesc}{additem}{text\, shortcut}
Add a menu item with given text.
The following methods are defined:
-\renewcommand{\indexsubitem}{(bitmap method)}
+\setindexsubitem{(bitmap method)}
\begin{funcdesc}{getsize}{}
Return a tuple representing the width and height of the bitmap.
For semantics, see the STDWIN documentation for C programmers.
The following methods exist:
-\renewcommand{\indexsubitem}{(text-edit method)}
+\setindexsubitem{(text-edit method)}
\begin{funcdesc}{arrow}{code}
Pass an arrow event to the text-edit block.
The window will be correctly redrawn when covered and re-exposed.
The program quits when the close icon or menu item is requested.
-\bcode\begin{verbatim}
+\begin{verbatim}
import stdwin
from stdwinevents import *
break
main()
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{Standard Module \sectcode{stdwinevents}}
\stmodindex{stdwinevents}
Read the file for details.
Suggested usage is
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> from stdwinevents import *
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{Standard Module \sectcode{rect}}
\stmodindex{rect}
a pair of points, where a point is a pair of integers.
For example, the rectangle
-\bcode\begin{verbatim}
+\begin{verbatim}
(10, 20), (90, 80)
-\end{verbatim}\ecode
+\end{verbatim}
%
is a rectangle whose left, top, right and bottom edges are 10, 20, 90
and 80, respectively.
The module defines the following objects:
-\renewcommand{\indexsubitem}{(in module rect)}
+\setindexsubitem{(in module rect)}
\begin{excdesc}{error}
The exception raised by functions in this module when they detect an
error.
The rectangle returned when some operations return an empty result.
This makes it possible to quickly check whether a result is empty:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import rect
>>> r1 = (10, 20), (90, 80)
>>> r2 = (0, 0), (10, 20)
>>> if r3 is rect.empty: print 'Empty intersection'
Empty intersection
>>>
-\end{verbatim}\ecode
+\end{verbatim}
\end{datadesc}
\begin{funcdesc}{is_empty}{r}
The constants defined in this module are are:
-\renewcommand{\indexsubitem}{(data in module string)}
+\setindexsubitem{(data in module string)}
\begin{datadesc}{digits}
The string \code{'0123456789'}.
\end{datadesc}
The functions defined in this module are:
-\renewcommand{\indexsubitem}{(in module string)}
+\setindexsubitem{(in module string)}
\begin{funcdesc}{atof}{s}
Convert a string to a floating point number. The string must have
The module defines the following exception and functions:
-\renewcommand{\indexsubitem}{(in module struct)}
+\setindexsubitem{(in module struct)}
\begin{excdesc}{error}
Exception raised on various occasions; argument is a string
describing what is wrong.
Examples (all using native byte order, size and alignment, on a
big-endian machine):
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\000\001\000\002\000\000\000\003'
>>> calcsize('hhl')
8
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
Hint: to align the end of a structure to the alignment requirement of
a particular type, end the format with the code for that type with a
The module defines the following variables and functions:
-\renewcommand{\indexsubitem}{(in module sunaudiodev)}
+\setindexsubitem{(in module sunaudiodev)}
\begin{excdesc}{error}
This exception is raised on all errors. The argument is a string
describing what went wrong.
following methods (except \code{control} objects which only provide
getinfo, setinfo and drain):
-\renewcommand{\indexsubitem}{(audio device method)}
+\setindexsubitem{(audio device method)}
\begin{funcdesc}{close}{}
This method explicitly closes the device. It is useful in situations
interpreter and to functions that interact strongly with the interpreter.
It is always available.
-\renewcommand{\indexsubitem}{(in module sys)}
+\setindexsubitem{(in module sys)}
\begin{datadesc}{argv}
The list of command line arguments passed to a Python script.
set at build time with the \code{--exec-prefix} argument to the
\code{configure} script. Specifically, all configuration files
(e.g. the \code{config.h} header file) are installed in the directory
-\code{sys.exec_prefix+"/lib/python\emph{VER}/config"}, and shared library
+\code{sys.exec_prefix+"/lib/python\var{version}/config"}, and shared library
modules are installed in
-\code{sys.exec_prefix+"/lib/python\emph{VER}/lib-dynload"},
-where \emph{VER} is equal to \code{sys.version[:3]}.
+\code{sys.exec_prefix+"/lib/python\var{version}/lib-dynload"},
+where \var{version} is equal to \code{sys.version[:3]}.
\end{datadesc}
\begin{funcdesc}{exit}{n}
\code{"/usr/local"}. This can be set at build time with the
\code{--prefix} argument to the \code{configure} script. The main
collection of Python library modules is installed in the directory
-\code{sys.prefix+"/lib/python\emph{VER}"} while the platform
+\code{sys.prefix+"/lib/python\var{version}"} while the platform
independent header files (all except \code{config.h}) are stored in
-\code{sys.prefix+"/include/python\emph{VER}"},
-where \emph{VER} is equal to \code{sys.version[:3]}.
+\code{sys.prefix+"/include/python\var{version}"},
+where \var{version} is equal to \code{sys.version[:3]}.
\end{datadesc}
The module defines the following functions:
-\renewcommand{\indexsubitem}{(in module syslog)}
+\setindexsubitem{(in module syslog)}
\begin{funcdesc}{syslog}{\optional{priority\,} message}
Send the string \var{message} to the system logger.
\indexii{temporary}{file name}
\indexii{temporary}{file}
-\renewcommand{\indexsubitem}{(in module tempfile)}
+\setindexsubitem{(in module tempfile)}
This module generates temporary file names. It is not \UNIX{} specific,
but it may require some help on non-\UNIX{} systems.
% Redefine the ``indexsubitem'' macro to point to this module
% (alternatively, you can put this at the top of the file):
-\renewcommand{\indexsubitem}{(in module spam)}
+\setindexsubitem{(in module spam)}
% ---- 3.2. ----
% For each function, use a ``funcdesc'' block. This has exactly two
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import spam
>>> can = spam.open('/etc/passwd')
>>> can.empty()
>>> can.close()
-\end{verbatim}\ecode
+\end{verbatim}
%
% ==== 5. ====
% If your module defines new object types (for a built-in module) or
Spam objects (returned by \code{open()} above) have the following
methods.
-\renewcommand{\indexsubitem}{(spam method)}
+\setindexsubitem{(spam method)}
\begin{funcdesc}{empty}{}
Empty the can into the trash.
\indexii{\POSIX{}}{I/O control}
\indexii{tty}{I/O control}
-\renewcommand{\indexsubitem}{(in module termios)}
+\setindexsubitem{(in module termios)}
This module provides an interface to the \POSIX{} calls for tty I/O
control. For a complete description of these calls, see the \POSIX{} or
and a \code{try \ldots{} finally} statement to ensure that the old tty
attributes are restored exactly no matter what happens:
-\bcode\begin{verbatim}
+\begin{verbatim}
def getpass(prompt = "Password: "):
import termios, TERMIOS, sys
fd = sys.stdin.fileno()
finally:
termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old)
return passwd
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{Standard Module \sectcode{TERMIOS}}
\stmodindex{TERMIOS}
\indexii{\POSIX{}}{I/O control}
\indexii{tty}{I/O control}
-\renewcommand{\indexsubitem}{(in module TERMIOS)}
+\setindexsubitem{(in module TERMIOS)}
This module defines the symbolic constants required to use the
\code{termios} module (see the previous section). See the \POSIX{} or
It defines the following constant and functions:
-\renewcommand{\indexsubitem}{(in module thread)}
+\setindexsubitem{(in module thread)}
\begin{excdesc}{error}
Raised on thread-specific errors.
\end{excdesc}
Lock objects have the following methods:
-\renewcommand{\indexsubitem}{(lock method)}
+\setindexsubitem{(lock method)}
\begin{funcdesc}{acquire}{\optional{waitflag}}
Without the optional argument, this method acquires the lock
unconditionally, if necessary waiting until it is released by another
The module defines the following functions and data items:
-\renewcommand{\indexsubitem}{(in module time)}
+\setindexsubitem{(in module time)}
\begin{datadesc}{altzone}
The offset of the local DST timezone, in seconds west of the 0th
\label{module-traceback}
\stmodindex{traceback}
-\renewcommand{\indexsubitem}{(in module traceback)}
+\setindexsubitem{(in module traceback)}
This module provides a standard interface to format and print stack
traces of Python programs. It exactly mimics the behavior of the
\index{false}
\begin{itemize}
-\renewcommand{\indexsubitem}{(Built-in object)}
+\setindexsubitem{(Built-in object)}
\item \code{None}
\ttindex{None}
the formats in the string must have a parenthesized key into that
dictionary inserted immediately after the \code{\%} character, and
each format formats the corresponding entry from the mapping. E.g.
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> count = 2
>>> language = 'Python'
>>> print '%(language)s has %(count)03d quote types.' % vars()
Python has 002 quote types.
>>>
-\end{verbatim}\ecode
+\end{verbatim}
In this case no * specifiers may occur in a format (since they
require a sequential parameter list).
\indexii{subscript}{assignment}
\indexii{slice}{assignment}
\stindex{del}
-\renewcommand{\indexsubitem}{(list method)}
+\setindexsubitem{(list method)}
\ttindex{append}
\ttindex{count}
\ttindex{index}
\indexiii{operations on}{dictionary}{type}
\stindex{del}
\bifuncindex{len}
-\renewcommand{\indexsubitem}{(dictionary method)}
+\setindexsubitem{(dictionary method)}
\ttindex{keys}
\ttindex{has_key}
Files have the following methods:
-\renewcommand{\indexsubitem}{(file method)}
+\setindexsubitem{(file method)}
\begin{funcdesc}{close}{}
Close the file. A closed file cannot be read or written anymore.
\label{module-types}
\stmodindex{types}
-\renewcommand{\indexsubitem}{(in module types)}
+\setindexsubitem{(in module types)}
This module defines names for all object types that are used by the
standard Python interpreter (but not for the types defined by various
Typical use is for functions that do different things depending on
their argument types, like the following:
-\bcode\begin{verbatim}
+\begin{verbatim}
from types import *
def delete(list, item):
if type(item) is IntType:
del list[item]
else:
list.remove(item)
-\end{verbatim}\ecode
+\end{verbatim}
%
The module defines the following names:
\index{World-Wide Web}
\index{URL}
-\renewcommand{\indexsubitem}{(in module urllib)}
+\setindexsubitem{(in module urllib)}
This module provides a high-level interface for fetching data across
the World-Wide Web. In particular, the \code{urlopen()} function is
\indexii{URL}{parsing}
\indexii{relative}{URL}
-\renewcommand{\indexsubitem}{(in module urlparse)}
+\setindexsubitem{(in module urlparse)}
This module defines a standard interface to break URL strings up in
components (addessing scheme, network location, path etc.), to combine
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
-\end{verbatim}\ecode
+\end{verbatim}
%
yields the tuple
-\bcode\begin{verbatim}
+\begin{verbatim}
('http', 'www.cwi.nl:80', '/%7Eguido/Python.html', '', '', '')
-\end{verbatim}\ecode
+\end{verbatim}
%
If the \var{default_scheme} argument is specified, it gives the
default addressing scheme, to be used only if the URL string does not
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
-\end{verbatim}\ecode
+\end{verbatim}
%
yields the string
-\bcode\begin{verbatim}
+\begin{verbatim}
'http://www.cwi.nl/%7Eguido/FAQ.html'
-\end{verbatim}\ecode
+\end{verbatim}
%
The \var{allow_fragments} argument has the same meaning as for
\code{urlparse()}.
your module. For example, a module \code{spam} that has a verbosity
level can look for a variable \code{user.spam_verbose}, as follows:
-\bcode\begin{verbatim}
+\begin{verbatim}
import user
try:
verbose = user.spam_verbose # user's verbosity preference
except AttributeError:
verbose = 0 # default verbosity
-\end{verbatim}\ecode
+\end{verbatim}
Programs with extensive customization needs are better off reading a
program-specific customization file.
them and override existing methods or add new ones. In this way one
can add new behaviours to dictionaries or lists.
-\renewcommand{\indexsubitem}{(in module UserDict)}
+\setindexsubitem{(in module UserDict)}
The \code{UserDict} module defines the \code{UserDict} class:
\begin{funcdesc}{UserDict}{}
\code{data} attribute of \code{UserDict} instances.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(in module UserList)}
+\setindexsubitem{(in module UserList)}
The \code{UserList} module defines the \code{UserList} class:
\begin{funcdesc}{UserList}{\optional{list}}
several simple database modules available--dbm, gdbm, or
dbhash--should be used to open a given file.
-\renewcommand{\indexsubitem}{(in module whichdb)}
+\setindexsubitem{(in module whichdb)}
\begin{funcdesc}{whichdb}{filename}
Returns one of the following values: \code{None} if the file can't be
opened because it's unreadable or doesn't exist; the empty string
This module implements a Wichmann-Hill pseudo-random number generator
class that is also named \code{whrandom}. Instances of the
\code{whrandom} class have the following methods:
-\renewcommand{\indexsubitem}{(in module whrandom)}
+\setindexsubitem{(in module whrandom)}
\begin{funcdesc}{choice}{seq}
Chooses a random element from the non-empty sequence \var{seq} and returns it.
the \code{whrandom} class, and makes the methods of that instance
available at the module level. Therefore one can write either
\code{N = whrandom.random()} or:
-\bcode\begin{verbatim}
+\begin{verbatim}
generator = whrandom.whrandom()
N = generator.random()
-\end{verbatim}\ecode
+\end{verbatim}
%
\begin{seealso}
\seemodule{random}{generators for various random distributions}
\index{XDR}
\index{External Data Representation}
-\renewcommand{\indexsubitem}{(in module xdrlib)}
+\setindexsubitem{(in module xdrlib)}
The \code{xdrlib} module supports the External Data Representation
Here is an example of how you would catch one of these exceptions:
-\bcode\begin{verbatim}
+\begin{verbatim}
import xdrlib
p = xdrlib.Packer()
try:
p.pack_double(8.01)
except xdrlib.ConversionError, instance:
print 'packing the double failed:', instance.msg
-\end{verbatim}\ecode
+\end{verbatim}
The \code{XMLParser} class must be instantiated without arguments. It
has the following interface methods:
-\renewcommand{\indexsubitem}{(XMLParser method)}
+\setindexsubitem{(XMLParser method)}
\begin{funcdesc}{reset}{}
Reset the instance. Loses all unprocessed data. This is called
The available functions in this module are:
-\renewcommand{\indexsubitem}{(in module zlib)}
+\setindexsubitem{(in module zlib)}
\begin{funcdesc}{adler32}{string\optional{\, value}}
Computes a Adler-32 checksum of \var{string}. (An Adler-32
checksum is almost as reliable as a CRC32 but can be computed much
Module \code{aifc} defines the following function:
-\renewcommand{\indexsubitem}{(in module aifc)}
+\setindexsubitem{(in module aifc)}
\begin{funcdesc}{open}{file\, mode}
Open an AIFF or AIFF-C file and return an object instance with
methods that are described below. The argument file is either a
Objects returned by \code{aifc.open()} when a file is opened for
reading have the following methods:
-\renewcommand{\indexsubitem}{(aifc object method)}
+\setindexsubitem{(aifc object method)}
\begin{funcdesc}{getnchannels}{}
Return the number of audio channels (1 for mono, 2 for stereo).
\end{funcdesc}
The module defines the following functions:
-\renewcommand{\indexsubitem}{(in module al)}
+\setindexsubitem{(in module al)}
\begin{funcdesc}{openport}{name\, direction\optional{\, config}}
The name and direction arguments are strings. The optional config
Configuration objects (returned by \code{al.newconfig()} have the
following methods:
-\renewcommand{\indexsubitem}{(audio configuration object method)}
+\setindexsubitem{(audio configuration object method)}
\begin{funcdesc}{getqueuesize}{}
Return the queue size.
Port objects (returned by \code{al.openport()} have the following
methods:
-\renewcommand{\indexsubitem}{(audio port object method)}
+\setindexsubitem{(audio port object method)}
\begin{funcdesc}{closeport}{}
Close the port.
\samp{AL_} is omitted. Read the module source for a complete list of
the defined names. Suggested use:
-\bcode\begin{verbatim}
+\begin{verbatim}
import al
from AL import *
-\end{verbatim}\ecode
+\end{verbatim}
The module \code{amoeba} defines the following items:
-\renewcommand{\indexsubitem}{(in module amoeba)}
+\setindexsubitem{(in module amoeba)}
\begin{funcdesc}{name_append}{path\, cap}
Stores a capability in the Amoeba directory tree.
Arguments are the pathname (a string) and the capability (a capability
\emph{a2c}(U).
For example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> amoeba.name_lookup('/profile/cap')
aa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
The following methods are defined for capability objects.
-\renewcommand{\indexsubitem}{(capability method)}
+\setindexsubitem{(capability method)}
\begin{funcdesc}{dir_list}{}
Returns a list of the names of the entries in an Amoeba directory.
\end{funcdesc}
% not the best solution, but it's what you get for documenting both
% at the same time.
-\renewcommand{\indexsubitem}{(in modules anydbm, dumbdbm)}
+\setindexsubitem{(in modules anydbm, dumbdbm)}
\begin{funcdesc}{open}{filename\optional{\, flag\, mode}}
Open the database file \var{filename} and return a corresponding object.
The module defines the following function:
-\renewcommand{\indexsubitem}{(in module array)}
+\setindexsubitem{(in module array)}
\begin{funcdesc}{array}{typecode\optional{\, initializer}}
Return a new array whose items are restricted by \var{typecode}, and
an array with the same type and value using reverse quotes
(\code{``}). Examples:
-\bcode\begin{verbatim}
+\begin{verbatim}
array('l')
array('c', 'hello world')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])
-\end{verbatim}\ecode
+\end{verbatim}
The module defines the following variables and functions:
-\renewcommand{\indexsubitem}{(in module audioop)}
+\setindexsubitem{(in module audioop)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unknown number of bytes
per sample, etc.
treated equal. If this is a problem the stereo fragment should be split
into two mono fragments first and recombined later. Here is an example
of how to do that:
-\bcode\begin{verbatim}
+\begin{verbatim}
def mul_stereo(sample, width, lfactor, rfactor):
lsample = audioop.tomono(sample, width, 1, 0)
rsample = audioop.tomono(sample, width, 0, 1)
lsample = audioop.tostereo(lsample, width, 1, 0)
rsample = audioop.tostereo(rsample, width, 0, 1)
return audioop.add(lsample, rsample, width)
-\end{verbatim}\ecode
+\end{verbatim}
%
If you use the ADPCM coder to build network packets and you want your
protocol to be stateless (i.e.\ to be able to tolerate packet loss)
fast way to do this is to pick the most energetic piece of the output
sample, locate that in the input sample and subtract the whole output
sample from the input sample:
-\bcode\begin{verbatim}
+\begin{verbatim}
def echocancel(outputdata, inputdata):
pos = audioop.findmax(outputdata, 800) # one tenth second
out_test = outputdata[pos*2:]
postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
return audioop.add(inputdata, outputdata, 2)
-\end{verbatim}\ecode
+\end{verbatim}
string \code{'www.python.org'} is encoded as the string
\code{'d3d3LnB5dGhvbi5vcmc=\e n'}.
-\renewcommand{\indexsubitem}{(in module base64)}
+\setindexsubitem{(in module base64)}
\begin{funcdesc}{decode}{input, output}
Decode the contents of the \var{input} file and write the resulting
\index{URL}
\index{httpd}
-\renewcommand{\indexsubitem}{(in module BaseHTTPServer)}
+\setindexsubitem{(in module BaseHTTPServer)}
This module defines two classes for implementing HTTP servers
(web servers). Usually, this module isn't used directly, but is used
requests to a handler. Code to create and run the server looks like
this:
-\bcode\begin{verbatim}
+\begin{verbatim}
def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
-\end{verbatim}\ecode
+\end{verbatim}
%
The \code{HTTPServer} class builds on the \code{TCPServer} class by
storing the server address as instance
the relevant information is stored into instance variables of the
handler.
-\renewcommand{\indexsubitem}{(BaseHTTPRequestHandler instance variable)}
+\setindexsubitem{(BaseHTTPRequestHandler instance variable)}
\code{BaseHTTPRequestHandler} has the following instance variables:
to this stream.
\end{datadesc}
-\renewcommand{\indexsubitem}{(BaseHTTPRequestHandler class variable)}
+\setindexsubitem{(BaseHTTPRequestHandler class variable)}
\code{BaseHTTPRequestHandler} has the following class variables:
(see the \code{error_message_format} class variable).
\end{datadesc}
-\renewcommand{\indexsubitem}{(BaseHTTPRequestHandler method)}
+\setindexsubitem{(BaseHTTPRequestHandler method)}
A \code{BaseHTTPRequestHandler} instance has the following methods:
\section{Standard Module \sectcode{Bastion}}
\label{module-Bastion}
\stmodindex{Bastion}
-\renewcommand{\indexsubitem}{(in module Bastion)}
+\setindexsubitem{(in module Bastion)}
% I'm concerned that the word 'bastion' won't be understood by people
% for whom English is a second language, making the module name
The \code{binhex} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module binhex)}
+\setindexsubitem{(in module binhex)}
\begin{funcdesc}{binhex}{input\, output}
Convert a binary file with filename \var{input} to binhex file
The \code{uu} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module uu)}
+\setindexsubitem{(in module uu)}
\begin{funcdesc}{encode}{in_file\, out_file\optional{\, name\, mode}}
Uuencode file \var{in_file} into file \var{out_file}. The uuencoded
The \code{binascii} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module binascii)}
+\setindexsubitem{(in module binascii)}
\begin{funcdesc}{a2b_uu}{string}
Convert a single line of uuencoded data back to binary and return the
Module \code{cd} defines the following functions and constants:
-\renewcommand{\indexsubitem}{(in module cd)}
+\setindexsubitem{(in module cd)}
\begin{funcdesc}{createparser}{}
Create and return an opaque parser object. The methods of the parser
Player objects (returned by \code{cd.open()}) have the following
methods:
-\renewcommand{\indexsubitem}{(CD player object method)}
+\setindexsubitem{(CD player object method)}
\begin{funcdesc}{allowremoval}{}
Unlocks the eject button on the CD-ROM drive permitting the user to
Parser objects (returned by \code{cd.createparser()}) have the
following methods:
-\renewcommand{\indexsubitem}{(CD parser object method)}
+\setindexsubitem{(CD parser object method)}
\begin{funcdesc}{addcallback}{type\, func\, arg}
Adds a callback for the parser. The parser has callbacks for eight
\indexii{MIME}{headers}
\index{URL}
-\renewcommand{\indexsubitem}{(in module cgi)}
+\setindexsubitem{(in module cgi)}
Support module for CGI (Common Gateway Interface) scripts.
telling the client what kind of data is following. Python code to
generate a minimal header section looks like this:
-\bcode\begin{verbatim}
+\begin{verbatim}
print "Content-type: text/html" # HTML is following
print # blank line, end of headers
-\end{verbatim}\ecode
+\end{verbatim}
%
The second section is usually HTML, which allows the client software
to display nicely formatted text with header, in-line images, etc.
Here's Python code that prints a simple piece of HTML:
-\bcode\begin{verbatim}
+\begin{verbatim}
print "<TITLE>CGI script output</TITLE>"
print "<H1>This is my first CGI script</H1>"
print "Hello, world!"
-\end{verbatim}\ecode
+\end{verbatim}
%
(It may not be fully legal HTML according to the letter of the
standard, but any browser will understand it.)
\code{Content-type} header and blank line have already been printed) checks that
the fields \code{name} and \code{addr} are both set to a non-empty string:
-\bcode\begin{verbatim}
+\begin{verbatim}
form = cgi.FieldStorage()
form_ok = 0
if form.has_key("name") and form.has_key("addr"):
print "Please fill in the name and addr fields."
return
...further form processing here...
-\end{verbatim}\ecode
+\end{verbatim}
%
Here the fields, accessed through \code{form[key]}, are themselves instances
of \code{FieldStorage} (or \code{MiniFieldStorage}, depending on the form encoding).
instance or a list of instances. For example, here's code that
concatenates any number of username fields, separated by commas:
-\bcode\begin{verbatim}
+\begin{verbatim}
username = form["username"]
if type(username) is type([]):
# Multiple username fields specified
else:
# Single username field specified
usernames = username.value
-\end{verbatim}\ecode
+\end{verbatim}
%
If a field represents an uploaded file, the value attribute reads the
entire file in memory as a string. This may not be what you want. You can
file attribute. You can then read the data at leasure from the file
attribute:
-\bcode\begin{verbatim}
+\begin{verbatim}
fileitem = form["userfile"]
if fileitem.file:
# It's an uploaded file; count lines
line = fileitem.file.readline()
if not line: break
linecount = linecount + 1
-\end{verbatim}\ecode
+\end{verbatim}
%
The file upload draft standard entertains the possibility of uploading
multiple files from one field (using a recursive \code{multipart/*}
that the first line of the script contains \code{\#!} starting in column 1
followed by the pathname of the Python interpreter, for instance:
-\bcode\begin{verbatim}
+\begin{verbatim}
#!/usr/local/bin/python
-\end{verbatim}\ecode
+\end{verbatim}
%
Make sure the Python interpreter exists and is executable by ``others''.
default module search path, you can change the path in your script,
before importing other modules, e.g.:
-\bcode\begin{verbatim}
+\begin{verbatim}
import sys
sys.path.insert(0, "/usr/home/joe/lib/python")
sys.path.insert(0, "/usr/local/lib/python")
-\end{verbatim}\ecode
+\end{verbatim}
%
(This way, the directory inserted last will be searched first!)
in the standard \file{cgi-bin} directory, it should be possible to send it a
request by entering a URL into your browser of the form:
-\bcode\begin{verbatim}
+\begin{verbatim}
http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
-\end{verbatim}\ecode
+\end{verbatim}
%
If this gives an error of type 404, the server cannot find the script
-- perhaps you need to install it in a different directory. If it
function from your script: replace its main code with the single
statement
-\bcode\begin{verbatim}
+\begin{verbatim}
cgi.test()
-\end{verbatim}\ecode
+\end{verbatim}
%
This should produce the same results as those gotten from installing
the \file{cgi.py} file itself.
For example:
-\bcode\begin{verbatim}
+\begin{verbatim}
import sys
import traceback
print "Content-type: text/html"
except:
print "\n\n<PRE>"
traceback.print_exc()
-\end{verbatim}\ecode
+\end{verbatim}
%
Notes: The assignment to \code{sys.stderr} is needed because the traceback
prints to \code{sys.stderr}.
module, you can use an even more robust approach (which only uses
built-in modules):
-\bcode\begin{verbatim}
+\begin{verbatim}
import sys
sys.stderr = sys.stdout
print "Content-type: text/plain"
print
...your code here...
-\end{verbatim}\ecode
+\end{verbatim}
%
This relies on the Python interpreter to print the traceback. The
content type of the output is set to plain text, which disables all
\label{module-cmath}
\bimodindex{cmath}
-\renewcommand{\indexsubitem}{(in module cmath)}
+\setindexsubitem{(in module cmath)}
This module is always available.
It provides access to mathematical functions for complex numbers.
The functions are:
The \code{code} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module code)}
+\setindexsubitem{(in module code)}
\begin{funcdesc}{compile_command}{source, \optional{filename\optional{, symbol}}}
This function is useful for programs that want to emulate Python's
The \code{commands} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module commands)}
+\setindexsubitem{(in module commands)}
\begin{funcdesc}{getstatusoutput}{cmd}
Execute the string \var{cmd} in a shell with \code{os.popen()} and return
a 2-tuple (status, output). \var{cmd} is actually run as
\section{Standard Module \sectcode{copy}}
\label{module-copy}
\stmodindex{copy}
-\renewcommand{\indexsubitem}{(copy function)}
+\setindexsubitem{(copy function)}
\ttindex{copy}
\ttindex{deepcopy}
Interface summary:
-\bcode\begin{verbatim}
+\begin{verbatim}
import copy
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
-\end{verbatim}\ecode
+\end{verbatim}
%
For module specific errors, \code{copy.error} is raised.
\code{__setstate__()}. See the description of module \code{pickle}
for information on these methods.
\refstmodindex{pickle}
-\renewcommand{\indexsubitem}{(copy protocol)}
+\setindexsubitem{(copy protocol)}
\ttindex{__getinitargs__}
\ttindex{__getstate__}
\ttindex{__setstate__}
constructors which are not classes. Such constructors may be factory
functions or class instances.
-\renewcommand{\indexsubitem}{(in module copy_reg)}
+\setindexsubitem{(in module copy_reg)}
\begin{funcdesc}{constructor}{object}
Declares \var{object} to be a valid constructor.
attempting to crack \UNIX{} passwords with a dictionary.
\index{crypt(3)}
-\renewcommand{\indexsubitem}{(in module crypt)}
+\setindexsubitem{(in module crypt)}
\begin{funcdesc}{crypt}{word\, salt}
\var{word} will usually be a user's password. \var{salt} is a
2-character string which will be used to select one of 4096 variations
\section{Built-in Module \sectcode{ctb}}
\label{module-ctb}
\bimodindex{ctb}
-\renewcommand{\indexsubitem}{(in module ctb)}
+\setindexsubitem{(in module ctb)}
This module provides a partial interface to the Macintosh
Communications Toolbox. Currently, only Connection Manager tools are
For all connection methods that take a \var{timeout} argument, a value
of \code{-1} is indefinite, meaning that the command runs to completion.
-\renewcommand{\indexsubitem}{(connection object attribute)}
+\setindexsubitem{(connection object attribute)}
\begin{datadesc}{callback}
If this member is set to a value other than \code{None} it should point
\end{datadesc}
-\renewcommand{\indexsubitem}{(connection object method)}
+\setindexsubitem{(connection object method)}
\begin{funcdesc}{Open}{timeout}
Open an outgoing connection, waiting at most \var{timeout} seconds for
The module defines the following constant and functions:
-\renewcommand{\indexsubitem}{(in module dbm)}
+\setindexsubitem{(in module dbm)}
\begin{excdesc}{error}
Raised on dbm-specific errors, such as I/O errors. \code{KeyError} is
raised for general mapping errors like specifying an incorrect key.
Example: Given the function myfunc
-\bcode\begin{verbatim}
+\begin{verbatim}
def myfunc(alist):
return len(alist)
-\end{verbatim}\ecode
+\end{verbatim}
the following command can be used to get the disassembly of \code{myfunc()}:
The \code{dis} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module dis)}
+\setindexsubitem{(in module dis)}
\begin{funcdesc}{dis}{\optional{bytesource}}
Disassemble the \var{bytesource} object. \var{bytesource} can denote
The Python compiler currently generates the following byte code
instructions.
-\renewcommand{\indexsubitem}{(byte code insns)}
+\setindexsubitem{(byte code insns)}
\begin{opcodedesc}{STOP_CODE}{}
Indicates end-of-code to the compiler, not used by the interpreter.
Pushes a slice object on the stack. \var{argc} must be 2 or 3. If it
is 2, \code{slice(TOS1, TOS)} is pushed; if it is 3,
\code{slice(TOS2, TOS1, TOS)} is pushed.
-See the \code{slice()} built-in function.
+See the \code{slice()}\bifuncindex{slice} built-in function.
\end{opcodedesc}
\section{Standard Module \sectcode{errno}}
\stmodindex{errno}
-\renewcommand{\indexsubitem}{(in module errno)}
+\setindexsubitem{(in module errno)}
This module makes available standard errno system symbols.
The value of each symbol is the corresponding integer value.
beware that there is nothing to prevent user code from raising an
inappropriate error.
-\renewcommand{\indexsubitem}{(built-in exception base class)}
+\setindexsubitem{(built-in exception base class)}
The following exceptions are only used as base classes for other
exceptions. When string-based standard exceptions are used, they
\code{KeyError}.
\end{excdesc}
-\renewcommand{\indexsubitem}{(built-in exception)}
+\setindexsubitem{(built-in exception)}
The following exceptions are the exceptions that are actually raised.
They are class objects, except when the \code{-X} option is used to
The module defines the following functions:
-\renewcommand{\indexsubitem}{(in module struct)}
+\setindexsubitem{(in module struct)}
\begin{funcdesc}{fcntl}{fd\, op\optional{\, arg}}
Perform the requested operation on file descriptor \code{\var{fd}}.
Examples (all on a SVR4 compliant system):
-\bcode\begin{verbatim}
+\begin{verbatim}
import struct, FCNTL
file = open(...)
lockdata = struct.pack('hhllhh', FCNTL.F_WRLCK, 0, 0, 0, 0, 0)
rv = fcntl(file.fileno(), FCNTL.F_SETLKW, lockdata)
-\end{verbatim}\ecode
+\end{verbatim}
%
Note that in the first example the return value variable \code{rv} will
hold an integer value; in the second example it will hold a string
about what they do, see the description of the equivalent C function
in the FORMS documentation:
-\renewcommand{\indexsubitem}{(in module fl)}
+\setindexsubitem{(in module fl)}
\begin{funcdesc}{make_form}{type\, width\, height}
Create a form with given type, width and height. This returns a
\dfn{form} object, whose methods are described below.
these methods are listed here.
\begin{flushleft}
-\renewcommand{\indexsubitem}{(form object method)}
+\setindexsubitem{(form object method)}
\begin{funcdesc}{show_form}{placement\, bordertype\, name}
Show the form.
\end{funcdesc}
Besides methods specific to particular kinds of FORMS objects, all
FORMS objects also have the following methods:
-\renewcommand{\indexsubitem}{(FORMS object method)}
+\setindexsubitem{(FORMS object method)}
\begin{funcdesc}{set_call_back}{function\, argument}
Set the object's callback function and argument. When the object
needs interaction, the callback function will be called with two
\samp{FL_} is omitted. Read the module source for a complete list of
the defined names. Suggested use:
-\bcode\begin{verbatim}
+\begin{verbatim}
import fl
from FL import *
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{Standard Module \sectcode{flp}}
\label{module-flp}
It supports the following operations:
-\renewcommand{\indexsubitem}{(in module fm)}
+\setindexsubitem{(in module fm)}
\begin{funcdesc}{init}{}
Initialization function.
Calls \code{fminit()}.
Font handle objects support the following operations:
-\renewcommand{\indexsubitem}{(font handle method)}
+\setindexsubitem{(font handle method)}
\begin{funcdesc}{scalefont}{factor}
Returns a handle for a scaled version of this font.
Calls \code{fmscalefont(\var{fh}, \var{factor})}.
for pathname expansion (\code{glob} uses \code{fnmatch()} to
match filename segments).
-\renewcommand{\indexsubitem}{(in module fnmatch)}
+\setindexsubitem{(in module fnmatch)}
\begin{funcdesc}{fnmatch}{filename, pattern}
Test whether the \var{filename} string matches the \var{pattern}
\label{module-formatter}
\stmodindex{formatter}
-\renewcommand{\indexsubitem}{(in module formatter)}
+\setindexsubitem{(in module formatter)}
This module supports two interface definitions, each with mulitple
implementations. The \emph{formatter} interface is used by the
The following attributes are defined for formatter instance objects:
-\renewcommand{\indexsubitem}{(formatter object data)}
+\setindexsubitem{(formatter object data)}
\begin{datadesc}{writer}
The writer instance with which the formatter interacts.
\end{datadesc}
-\renewcommand{\indexsubitem}{(formatter object method)}
+\setindexsubitem{(formatter object method)}
\begin{funcdesc}{end_paragraph}{blanklines}
Close any open paragraphs and insert at least \code{blanklines}
Most applications may use one of these classes without modification or
subclassing.
-\renewcommand{\indexsubitem}{(in module formatter)}
+\setindexsubitem{(in module formatter)}
\begin{funcdesc}{NullFormatter}{\optional{writer\code{ = None}}}
A formatter which does nothing. If \code{writer} is omitted, a
class as a formatter, the writer must typically be provided by the
application.
-\renewcommand{\indexsubitem}{(writer object method)}
+\setindexsubitem{(writer object method)}
\begin{funcdesc}{flush}{}
Flush any buffered output or device control events.
examples by this module. Most applications will need to derive new
writer classes from the \code{NullWriter} class.
-\renewcommand{\indexsubitem}{(in module formatter)}
+\setindexsubitem{(in module formatter)}
\begin{funcdesc}{NullWriter}{}
A writer which only provides the interface definition; no actions are
\stmodindex{ftplib}
\indexii{FTP}{protocol}
-\renewcommand{\indexsubitem}{(in module ftplib)}
+\setindexsubitem{(in module ftplib)}
This module defines the class \code{FTP} and a few related items. The
\code{FTP} class implements the client side of the FTP protocol. You
Here's a sample session using the \code{ftplib} module:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> from ftplib import FTP
>>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
>>> ftp.login() # user anonymous, passwd user@hostname
.
.
>>> ftp.quit()
-\end{verbatim}\ecode
+\end{verbatim}
%
The module defines the following items:
FTP instances have the following methods:
-\renewcommand{\indexsubitem}{(FTP object method)}
+\setindexsubitem{(FTP object method)}
\begin{funcdesc}{set_debuglevel}{level}
Set the instance's debugging level. This controls the amount of
are always available. They are listed here in alphabetical order.
-\renewcommand{\indexsubitem}{(built-in function)}
+\setindexsubitem{(built-in function)}
\begin{funcdesc}{__import__}{name\optional{, globals\optional{, locals\optional{, fromlist}}}}
This function is invoked by the \code{import} statement. It
and for class instances, methods are not included.
The resulting list is sorted alphabetically. For example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import sys
>>> dir()
['sys']
>>> dir(sys)
['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
>>>
-\end{verbatim}\ecode
+\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{divmod}{a\, b}
called. The return value is the result of the evaluated expression.
Syntax errors are reported as exceptions. Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> x = 1
>>> print eval('x+1')
2
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
This function can also be used to execute arbitrary code objects
(e.g.\ created by \code{compile()}). In this case pass a code
greater than \var{stop}. \var{step} must not be zero (or else an
exception is raised). Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
>>> range(1, 0)
[]
>>>
-\end{verbatim}\ecode
+\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{raw_input}{\optional{prompt}}
converts it to a string (stripping a trailing newline), and returns that.
When \EOF{} is read, \code{EOFError} is raised. Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
>>>
-\end{verbatim}\ecode
+\end{verbatim}
If the \code{readline} module was loaded, then
\code{raw_input()} will use it to provide elaborate
\obindex{type}
For instance:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import types
>>> if isinstance(x, types.StringType): print "It's a string"
-\end{verbatim}\ecode
+\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{vars}{\optional{object}}
The module defines the following constant and functions:
-\renewcommand{\indexsubitem}{(in module gdbm)}
+\setindexsubitem{(in module gdbm)}
\begin{excdesc}{error}
Raised on \code{gdbm}-specific errors, such as I/O errors. \code{KeyError} is
raised for general mapping errors like specifying an incorrect key.
Returns the key that follows \var{key} in the traversal. The
following code prints every key in the database \code{db}, without having to
create a list in memory that contains them all:
-\bcode\begin{verbatim}
+\begin{verbatim}
k=db.firstkey()
while k!=None:
print k
k=db.nextkey(k)
-\end{verbatim}\ecode
+\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{reorganize}{}
An example using only \UNIX{} style options:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import getopt, string
>>> args = string.split('-a -b -cfoo -d bar a1 a2')
>>> args
>>> args
['a1', 'a2']
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
Using long option names is equally easy:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = string.split(s)
>>> args
>>> args
['a1', 'a2']
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
The exception
\code{getopt.error}
only used to specify the length of an array argument are omitted.
For example, the C call
-\bcode\begin{verbatim}
+\begin{verbatim}
lmdef(deftype, index, np, props)
-\end{verbatim}\ecode
+\end{verbatim}
%
is translated to Python as
-\bcode\begin{verbatim}
+\begin{verbatim}
lmdef(deftype, index, props)
-\end{verbatim}\ecode
+\end{verbatim}
%
\item
Output arguments are omitted from the argument list; they are
comes first in the tuple.
Examples: the C call
-\bcode\begin{verbatim}
+\begin{verbatim}
getmcolor(i, &red, &green, &blue)
-\end{verbatim}\ecode
+\end{verbatim}
%
is translated to Python as
-\bcode\begin{verbatim}
+\begin{verbatim}
red, green, blue = getmcolor(i)
-\end{verbatim}\ecode
+\end{verbatim}
%
\end{itemize}
The following functions are non-standard or have special argument
conventions:
-\renewcommand{\indexsubitem}{(in module gl)}
+\setindexsubitem{(in module gl)}
\begin{funcdesc}{varray}{argument}
%JHXXX the argument-argument added
Equivalent to but faster than a number of
Here is a tiny but complete example GL program in Python:
-\bcode\begin{verbatim}
+\begin{verbatim}
import gl, GL, time
def main():
time.sleep(5)
main()
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{Standard Modules \sectcode{GL} and \sectcode{DEVICE}}
\nodename{GL and DEVICE}
\section{Standard Module \sectcode{glob}}
\label{module-glob}
\stmodindex{glob}
-\renewcommand{\indexsubitem}{(in module glob)}
+\setindexsubitem{(in module glob)}
The \code{glob} module finds all the pathnames matching a specified
pattern according to the rules used by the \UNIX{} shell. No tilde
will produce the following results. Notice how any leading components
of the path are preserved.
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
-\end{verbatim}\ecode
+\end{verbatim}
\stmodindex{gopherlib}
\indexii{Gopher}{protocol}
-\renewcommand{\indexsubitem}{(in module gopherlib)}
+\setindexsubitem{(in module gopherlib)}
This module provides a minimal implementation of client side of the
the Gopher protocol. It is used by the module \code{urllib} to handle
It defines the following items:
-\renewcommand{\indexsubitem}{(in module grp)}
+\setindexsubitem{(in module grp)}
\begin{funcdesc}{getgrgid}{gid}
Return the group database entry for the given numeric group ID.
\end{funcdesc}
object, though it's not possible to use the \code{seek()} and
\code{tell()} methods to access the file randomly.
-\renewcommand{\indexsubitem}{(in module gzip)}
+\setindexsubitem{(in module gzip)}
\begin{funcdesc}{open}{fileobj\optional{\, filename\optional{\, mode\, compresslevel}}}
Returns a new \code{GzipFile} object on top of \var{fileobj}, which
can be a regular file, a \code{StringIO} object, or any object which
\index{HTML}
\index{hypertext}
-\renewcommand{\indexsubitem}{(in module htmllib)}
+\setindexsubitem{(in module htmllib)}
This module defines a class which can serve as a base for parsing text
files formatted in the HyperText Mark-up Language (HTML). The class
unprocessed data, call the \method{close()} method.
For example, to parse the entire contents of a file, use:
-\bcode\begin{verbatim}
+\begin{verbatim}
parser.feed(open('myfile.html').read())
parser.close()
-\end{verbatim}\ecode
+\end{verbatim}
%
\item
The interface to define semantics for HTML tags is very simple: derive
In addition to tag methods, the \class{HTMLParser} class provides some
additional methods and instance variables for use within tag methods.
-\renewcommand{\indexsubitem}{(HTMLParser attribute)}
+\setindexsubitem{(HTMLParser attribute)}
\begin{datadesc}{formatter}
This is the formatter instance associated with the parser.
affects the operation of \method{handle_data()} and \method{save_end()}.
\end{datadesc}
-\renewcommand{\indexsubitem}{(HTMLParser method)}
+\setindexsubitem{(HTMLParser method)}
\begin{funcdesc}{anchor_bgn}{href\, name\, type}
This method is called at the start of an anchor region. The arguments
\stmodindex{httplib}
\index{HTTP}
-\renewcommand{\indexsubitem}{(in module httplib)}
+\setindexsubitem{(in module httplib)}
This module defines a class which implements the client side of the
HTTP protocol. It is normally not used directly --- the module
following calls all create instances that connect to the server at the
same host and port:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> h1 = httplib.HTTP('www.cwi.nl')
>>> h2 = httplib.HTTP('www.cwi.nl:80')
>>> h3 = httplib.HTTP('www.cwi.nl', 80)
-\end{verbatim}\ecode
+\end{verbatim}
%
Once an \code{HTTP} instance has been connected to an HTTP server, it
should be used as follows:
\code{HTTP} instances have the following methods:
-\renewcommand{\indexsubitem}{(HTTP method)}
+\setindexsubitem{(HTTP method)}
\begin{funcdesc}{set_debuglevel}{level}
Set the debugging level (the amount of debugging output printed).
Here is an example session:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import httplib
>>> h = httplib.HTTP('www.cwi.nl')
>>> h.putrequest('GET', '/index.html')
>>> data = f.read() # Get the raw HTML
>>> f.close()
>>>
-\end{verbatim}\ecode
+\end{verbatim}
The module defines the following variables and functions:
-\renewcommand{\indexsubitem}{(in module imageop)}
+\setindexsubitem{(in module imageop)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unknown number of bits
The module defines the following variables and functions:
-\renewcommand{\indexsubitem}{(in module imgfile)}
+\setindexsubitem{(in module imgfile)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unsupported file type, etc.
\end{excdesc}
The \code{imghdr} module defines the following function:
-\renewcommand{\indexsubitem}{(in module imghdr)}
+\setindexsubitem{(in module imghdr)}
\begin{funcdesc}{what}{filename\optional{\, h}}
Tests the image data contained in the file named by \var{filename},
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import imghdr
>>> imghdr.what('/tmp/bass.gif')
'gif'
-\end{verbatim}\ecode
+\end{verbatim}
the \code{import} statement. It defines the following constants and
functions:
-\renewcommand{\indexsubitem}{(in module imp)}
+\setindexsubitem{(in module imp)}
\begin{funcdesc}{get_magic}{}
Return the magic string value used to recognize byte-compiled code
\code{imp.find_module()} has been extended and
\code{imp.load_module()} has been added in 1.4.)
-\bcode\begin{verbatim}
+\begin{verbatim}
import imp import sys
def __import__(name, globals=None, locals=None, fromlist=None):
# Since we may exit via an exception, close fp explicitly.
if fp:
fp.close()
-\end{verbatim}\ecode
+\end{verbatim}
A more complete example that implements hierarchical module names and
includes a \code{reload()} function can be found in the standard
The \code{jpeg} module defines these functions:
-\renewcommand{\indexsubitem}{(in module jpeg)}
+\setindexsubitem{(in module jpeg)}
\begin{funcdesc}{compress}{data\, w\, h\, b}
Treat data as a pixmap of width \var{w} and height \var{h}, with \var{b} bytes per
pixel. The data is in SGI GL order, so the first pixel is in the
The \code{locale} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module locale)}
+\setindexsubitem{(in module locale)}
\begin{funcdesc}{setlocale}{category\optional{\, value}}
If \var{value} is specified, modifies the locale setting for the
\code{setlocale()} is not thread safe on most systems. Applications
typically start with a call of
-\bcode\begin{verbatim}
+\begin{verbatim}
import locale
locale.setlocale(locale.LC_ALL,"")
-\end{verbatim}\ecode
+\end{verbatim}
This sets the locale for all categories to the user's default setting
(typically specified in the \code{LANG} environment variable). If the
locale is not changed thereafter, using multithreading should not
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import locale
>>> locale.open(locale.LC_ALL,"de") #setting locale to German
>>> locale.strcoll("f\344n","foo") #comparing a string containing an umlaut
>>> can.close()
-\end{verbatim}\ecode
+\end{verbatim}
\label{module-macconsole}
\bimodindex{macconsole}
-\renewcommand{\indexsubitem}{(in module macconsole)}
+\setindexsubitem{(in module macconsole)}
This module is available on the Macintosh, provided Python has been
built using the Think C compiler. It provides an interface to the
\subsection{macconsole options object}
These options are examined when a window is created:
-\renewcommand{\indexsubitem}{(macconsole option)}
+\setindexsubitem{(macconsole option)}
\begin{datadesc}{top}
\dataline{left}
The origin of the window.
\subsection{console window object}
-\renewcommand{\indexsubitem}{(console window attribute)}
+\setindexsubitem{(console window attribute)}
\begin{datadesc}{file}
The file object corresponding to this console window. If the file is
and \code{read()} calls.
\end{datadesc}
-\renewcommand{\indexsubitem}{(console window method)}
+\setindexsubitem{(console window method)}
\begin{funcdesc}{setmode}{mode}
Set the input mode of the console to \var{C_ECHO}, etc.
The \code{macdnr} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module macdnr)}
+\setindexsubitem{(in module macdnr)}
\begin{funcdesc}{Open}{\optional{filename}}
Open the domain name resolver extension. If \var{filename} is given it
The \var{rtnCode} and \var{cname} attributes are always available, the
others depend on the type of query (address, hinfo or mx).
-\renewcommand{\indexsubitem}{(dnr result object method)}
+\setindexsubitem{(dnr result object method)}
% Add args, as in {arg1\, arg2 \optional{\, arg3}}
\begin{funcdesc}{wait}{}
Return 1 if the query is complete.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(dnr result object attribute)}
+\setindexsubitem{(dnr result object attribute)}
\begin{datadesc}{rtnCode}
The error code returned by the query.
The simplest way to use the module to convert names to dotted-decimal
strings, without worrying about idle time, etc:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> def gethostname(name):
... import macdnr
... dnrr = macdnr.StrToAddr(name)
... return macdnr.AddrToStr(dnrr.ip0)
-\end{verbatim}\ecode
+\end{verbatim}
\label{module-macfs}
\bimodindex{macfs}
-\renewcommand{\indexsubitem}{(in module macfs)}
+\setindexsubitem{(in module macfs)}
This module provides access to macintosh FSSpec handling, the Alias
Manager, finder aliases and the Standard File package.
\subsection{FSSpec objects}
-\renewcommand{\indexsubitem}{(FSSpec object attribute)}
+\setindexsubitem{(FSSpec object attribute)}
\begin{datadesc}{data}
The raw data from the FSSpec object, suitable for passing
to other applications, for instance.
\end{datadesc}
-\renewcommand{\indexsubitem}{(FSSpec object method)}
+\setindexsubitem{(FSSpec object method)}
\begin{funcdesc}{as_pathname}{}
Return the full pathname of the file described by the FSSpec object.
\end{funcdesc}
\subsection{alias objects}
-\renewcommand{\indexsubitem}{(alias object attribute)}
+\setindexsubitem{(alias object attribute)}
\begin{datadesc}{data}
The raw data for the Alias record, suitable for storing in a resource
or transmitting to other programs.
\end{datadesc}
-\renewcommand{\indexsubitem}{(alias object method)}
+\setindexsubitem{(alias object method)}
\begin{funcdesc}{Resolve}{\optional{file}}
Resolve the alias. If the alias was created as a relative alias you
should pass the file relative to which it is. Return the FSSpec for
See Inside Mac for a complete description of what the various fields
mean.
-\renewcommand{\indexsubitem}{(FInfo object attribute)}
+\setindexsubitem{(FInfo object attribute)}
\begin{datadesc}{Creator}
The 4-char creator code of the file.
\end{datadesc}
\section{Standard Module \sectcode{ic}}
\bimodindex{ic}
-\renewcommand{\indexsubitem}{(in module ic)}
+\setindexsubitem{(in module ic)}
This module provides access to macintosh Internet Config package,
which stores preferences for Internet programs such as mail address,
Besides the dictionary interface IC objects have the following methods:
-\renewcommand{\indexsubitem}{(IC object attribute)}
+\setindexsubitem{(IC object attribute)}
\begin{funcdesc}{launchurl}{url \optional{, hint}}
Parse the given URL, lauch the correct application and pass it the
\label{module-MacOS}
\bimodindex{MacOS}
-\renewcommand{\indexsubitem}{(in module MacOS)}
+\setindexsubitem{(in module MacOS)}
This module provides access to MacOS specific functionality in the
python interpreter, such as how the interpreter eventloop functions
The \code{macostools} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module macostools)}
+\setindexsubitem{(in module macostools)}
\begin{funcdesc}{copy}{src\, dst\optional{\, createpath, copytimes}}
Copy file \var{src} to \var{dst}. The files can be specified as
The \code{findertools} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module macostools)}
+\setindexsubitem{(in module macostools)}
\begin{funcdesc}{launch}{file}
Tell the finder to launch \var{file}. What launching means depends on the file:
\label{module-macspeech}
\bimodindex{macspeech}
-\renewcommand{\indexsubitem}{(in module macspeech)}
+\setindexsubitem{(in module macspeech)}
This module provides an interface to the Macintosh Speech Manager,
allowing you to let the Macintosh utter phrases. You need a version of
Voice objects contain the description of a voice. It is currently not
yet possible to access the parameters of a voice.
-\renewcommand{\indexsubitem}{(voice object method)}
+\setindexsubitem{(voice object method)}
\begin{funcdesc}{GetGender}{}
Return the gender of the voice: 0 for male, 1 for female and -1 for neuter.
interrelated in some way, so that to make your Macintosh sing you will
have to adjust both.
-\renewcommand{\indexsubitem}{(speech channel object method)}
+\setindexsubitem{(speech channel object method)}
\begin{funcdesc}{SpeakText}{str}
Start uttering the given string.
\end{funcdesc}
\label{module-mactcp}
\bimodindex{mactcp}
-\renewcommand{\indexsubitem}{(in module mactcp)}
+\setindexsubitem{(in module mactcp)}
This module provides an interface to the Macintosh TCP/IP driver
MacTCP\@. There is an accompanying module \code{macdnr} which provides an
\subsection{TCP Stream Objects}
-\renewcommand{\indexsubitem}{(TCP stream attribute)}
+\setindexsubitem{(TCP stream attribute)}
\begin{datadesc}{asr}
When set to a value different than \code{None} this should point to a
It is safe to do further calls from the \code{asr}.
\end{datadesc}
-\renewcommand{\indexsubitem}{(TCP stream method)}
+\setindexsubitem{(TCP stream method)}
\begin{funcdesc}{PassiveOpen}{port}
Wait for an incoming connection on TCP port \var{port} (zero makes the
the connection. A complete description of all fields in this objects
can be found in the Apple documentation. The most interesting ones are:
-\renewcommand{\indexsubitem}{(TCP status attribute)}
+\setindexsubitem{(TCP status attribute)}
\begin{datadesc}{localHost}
\dataline{localPort}
Note that, unlike the name suggests, there is nothing stream-like
about UDP.
-\renewcommand{\indexsubitem}{(UDP stream attribute)}
+\setindexsubitem{(UDP stream attribute)}
\begin{datadesc}{asr}
The asynchronous service routine to be called on events such as
A read-only member giving the port number of this UDP stream.
\end{datadesc}
-\renewcommand{\indexsubitem}{(UDP stream method)}
+\setindexsubitem{(UDP stream method)}
\begin{funcdesc}{Read}{timeout}
Read a datagram, waiting at most \var{timeout} seconds (-1 is
The \code{EasyDialogs} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module EasyDialogs)}
+\setindexsubitem{(in module EasyDialogs)}
\begin{funcdesc}{Message}{str}
A modal dialog with the message text \var{str}, which should be at
The \code{FrameWork} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module FrameWork)}
+\setindexsubitem{(in module FrameWork)}
\begin{funcdesc}{Application}{}
An object representing the complete application. See below for a
\subsection{Application objects}
Application objects have the following methods, among others:
-\renewcommand{\indexsubitem}{(Application method)}
+\setindexsubitem{(Application method)}
\begin{funcdesc}{makeusermenus}{}
Override this method if you need menus in your application. Append the
Window objects have the following methods, among others:
-\renewcommand{\indexsubitem}{(Window method)}
+\setindexsubitem{(Window method)}
\begin{funcdesc}{open}{}
Override this method to open a window. Store the MacOS window-id in
ControlsWindow objects have the following methods besides those of
\code{Window} objects:
-\renewcommand{\indexsubitem}{(ControlsWindow method)}
+\setindexsubitem{(ControlsWindow method)}
\begin{funcdesc}{do_controlhit}{window\, control\, pcode\, event}
Part \code{pcode} of control \code{control} was hit by the
ScrolledWindow objects are ControlsWindow objects with the following
extra methods:
-\renewcommand{\indexsubitem}{(ScrolledWindow method)}
+\setindexsubitem{(ScrolledWindow method)}
\begin{funcdesc}{scrollbars}{\optional{wantx\, wanty}}
Create (or destroy) horizontal and vertical scrollbars. The arguments
DialogWindow objects have the following methods besides those of
\code{Window} objects:
-\renewcommand{\indexsubitem}{(DialogWindow method)}
+\setindexsubitem{(DialogWindow method)}
\begin{funcdesc}{open}{resid}
Create the dialog window, from the DLOG resource with id
The \var{MiniAEFrame} module defines the following classes:
-\renewcommand{\indexsubitem}{(in module MiniAEFrame)}
+\setindexsubitem{(in module MiniAEFrame)}
\begin{funcdesc}{AEServer}{}
A class that handles AppleEvent dispatch. Your application should
\subsection{AEServer Objects}
-\renewcommand{\indexsubitem}{(AEServer method)}
+\setindexsubitem{(AEServer method)}
\begin{funcdesc}{installaehandler}{classe\, type\, callback}
Installs an AppleEvent handler. \code{Classe} and \code{type} are the
\label{module-mailbox}
\stmodindex{mailbox}
-\renewcommand{\indexsubitem}{(in module mailbox)}
+\setindexsubitem{(in module mailbox)}
This module defines a number of classes that allow easy and uniform
access to mail messages in a (unix) mailbox.
\section{Standard Module \sectcode{mailcap}}
\label{module-mailcap}
\stmodindex{mailcap}
-\renewcommand{\indexsubitem}{(in module mailcap)}
+\setindexsubitem{(in module mailcap)}
Mailcap files are used to configure how MIME-aware applications such
as mail readers and Web browsers react to files with different MIME
\end{funcdesc}
An example usage:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import mailcap
>>> d=mailcap.getcaps()
>>> mailcap.findmatch(d, 'video/mpeg', filename='/tmp/tmp1223')
('xmpeg /tmp/tmp1223', {'view': 'xmpeg %s'})
-\end{verbatim}\ecode
+\end{verbatim}
The module defines these functions:
-\renewcommand{\indexsubitem}{(in module marshal)}
+\setindexsubitem{(in module marshal)}
\begin{funcdesc}{dump}{value\, file}
Write the value on the open file. The value must be a supported
\label{module-math}
\bimodindex{math}
-\renewcommand{\indexsubitem}{(in module math)}
+\setindexsubitem{(in module math)}
This module is always available.
It provides access to the mathematical functions defined by the \C{}
standard.
For example, to obtain the digest of the string {\tt"Nobody inspects
the spammish repetition"}:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import md5
>>> m = md5.new()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
-\end{verbatim}\ecode
+\end{verbatim}
%
More condensed:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> md5.new("Nobody inspects the spammish repetition").digest()
'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
-\end{verbatim}\ecode
+\end{verbatim}
%
-\renewcommand{\indexsubitem}{(in module md5)}
+\setindexsubitem{(in module md5)}
\begin{funcdesc}{new}{\optional{arg}}
Return a new md5 object. If \var{arg} is present, the method call
An md5 object has the following methods:
-\renewcommand{\indexsubitem}{(md5 method)}
+\setindexsubitem{(md5 method)}
\begin{funcdesc}{update}{arg}
Update the md5 object with the string \var{arg}. Repeated calls are
equivalent to a single call with the concatenation of all the
\label{module-mimetools}
\stmodindex{mimetools}
-\renewcommand{\indexsubitem}{(in module mimetools)}
+\setindexsubitem{(in module mimetools)}
This module defines a subclass of the class \code{rfc822.Message} and
a number of utility functions that are useful for the manipulation for
The \code{mimetools.Message} class defines the following methods in
addition to the \code{rfc822.Message} class:
-\renewcommand{\indexsubitem}{(mimetool.Message method)}
+\setindexsubitem{(mimetool.Message method)}
\begin{funcdesc}{getplist}{}
Return the parameter list of the \code{Content-type} header. This is
\section{Standard Module \sectcode{mimify}}
\stmodindex{mimify}
-\renewcommand{\indexsubitem}{(in module mimify)}
+\setindexsubitem{(in module mimify)}
The mimify module defines two functions to convert mail messages to
and from MIME format. The mail message can be either a simple message
below for an exact description). An mpz-number is printed like this:
\code{mpz(\var{value})}.
-\renewcommand{\indexsubitem}{(in module mpz)}
+\setindexsubitem{(in module mpz)}
\begin{funcdesc}{mpz}{value}
Create a new mpz-number. \var{value} can be an integer, a long,
another mpz-number, or even a string. If it is a string, it is
An mpz-number has one method:
-\renewcommand{\indexsubitem}{(mpz method)}
+\setindexsubitem{(mpz method)}
\begin{funcdesc}{binary}{}
Convert this mpz-number to a binary string, where the number has been
stored as an array of radix-256 digits, least significant digit first.
\code{hamneggs()} from that module, you can use any of the following
possibilities:
-\bcode\begin{verbatim}
+\begin{verbatim}
import spam.ham # *not* "import spam" !!!
spam.ham.hamneggs()
-\end{verbatim}\ecode
+\end{verbatim}
%
-\bcode\begin{verbatim}
+\begin{verbatim}
from spam import ham
ham.hamneggs()
-\end{verbatim}\ecode
+\end{verbatim}
%
-\bcode\begin{verbatim}
+\begin{verbatim}
from spam.ham import hamneggs
hamneggs()
-\end{verbatim}\ecode
+\end{verbatim}
%
\code{import spam} creates an
empty package named \code{spam} if one does not already exist, but it does
\code{spam.__init__} is a submodule of package spam. It can refer to
spam's namespace as \code{__} (two underscores):
-\bcode\begin{verbatim}
+\begin{verbatim}
__.spam_inited = 1 # Set a package-level variable
-\end{verbatim}\ecode
+\end{verbatim}
%
Additional initialization code (setting up variables, importing other
submodules) can be performed in \file{spam/__init__.py}.
\stmodindex{nntplib}
\indexii{NNTP}{protocol}
-\renewcommand{\indexsubitem}{(in module nntplib)}
+\setindexsubitem{(in module nntplib)}
This module defines the class \code{NNTP} which implements the client
side of the NNTP protocol. It can be used to implement a news reader
statistics about a newsgroup and print the subjects of the last 10
articles:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> s = NNTP('news.cwi.nl')
>>> resp, count, first, last, name = s.group('comp.lang.python')
>>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
>>> s.quit()
'205 news.cwi.nl closing connection. Goodbye.'
>>>
-\end{verbatim}\ecode
+\end{verbatim}
To post an article from a file (this assumes that the article has
valid headers):
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> s = NNTP('news.cwi.nl')
>>> f = open('/tmp/article')
>>> s.post(f)
>>> s.quit()
'205 news.cwi.nl closing connection. Goodbye.'
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
The module itself defines the following items:
If the server's response indicates an error, the method raises one of
the above exceptions.
-\renewcommand{\indexsubitem}{(NNTP object method)}
+\setindexsubitem{(NNTP object method)}
\begin{funcdesc}{getwelcome}{}
Return the welcome message sent by the server in reply to the initial
The \code{operator} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module operator)}
+\setindexsubitem{(in module operator)}
\begin{funcdesc}{add}{a, b}
Return \var{a} \code{+} \var{b}, for \var{a} and \var{b} numbers.
Example: Build a dictionary that maps the ordinals from \code{0} to
\code{256} to their character equivalents.
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import operator
>>> d = {}
>>> keys = range(256)
>>> vals = map(chr, keys)
>>> map(operator.setitem, [d]*len(keys), keys, vals)
-\end{verbatim}\ecode
+\end{verbatim}
In addition to whatever the correct OS dependent module exports, the
following variables and functions are always exported by \code{os}:
-\renewcommand{\indexsubitem}{(in module os)}
+\setindexsubitem{(in module os)}
\begin{datadesc}{name}
The name of the OS dependent module imported. The following names
The module is too large to document here in its entirety.
One interesting function:
-\renewcommand{\indexsubitem}{(in module panel)}
+\setindexsubitem{(in module panel)}
\begin{funcdesc}{defpanellist}{filename}
Parses a panel description file containing S-expressions written by the
\emph{Panel Editor}
and compiled code objects, but there are also functions which serve to
query the type of parse tree represented by an AST object.
-\renewcommand{\indexsubitem}{(in module parser)}
+\setindexsubitem{(in module parser)}
\subsection{Creating AST Objects}
this purpose, using the \module{parser} module to produce an
intermediate data structure is equivelent to the code
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> code = compile('a + 5', 'eval')
>>> a = 5
>>> eval(code)
10
-\end{verbatim}\ecode
+\end{verbatim}
%
The equivelent operation using the \module{parser} module is somewhat
longer, and allows the intermediate internal parse tree to be retained
as an AST object:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import parser
>>> ast = parser.expr('a + 5')
>>> code = parser.compileast(ast)
>>> a = 5
>>> eval(code)
10
-\end{verbatim}\ecode
+\end{verbatim}
%
An application which needs both AST and code objects can package this
code into readily available functions:
-\bcode\begin{verbatim}
+\begin{verbatim}
import parser
def load_suite(source_string):
ast = parser.expr(source_string)
code = parser.compileast(ast)
return ast, code
-\end{verbatim}\ecode
+\end{verbatim}
%
\subsubsection{Information Discovery}
a module consisting of a docstring and nothing else. (See file
\file{docstring.py}.)
-\bcode\begin{verbatim}
+\begin{verbatim}
"""Some documentation.
"""
-\end{verbatim}\ecode
+\end{verbatim}
%
Using the interpreter to take a look at the parse tree, we find a
bewildering mass of numbers and parentheses, with the documentation
buried deep in nested tuples.
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import parser
>>> import pprint
>>> ast = parser.suite(open('docstring.py').read())
(4, ''))),
(4, ''),
(0, ''))
-\end{verbatim}\ecode
+\end{verbatim}
%
The numbers at the first element of each node in the tree are the node
types; they map directly to terminal and non-terminal symbols in the
the pattern matching, returning a boolean and a dictionary of variable
name to value mappings. (See file \file{example.py}.)
-\bcode\begin{verbatim}
+\begin{verbatim}
from types import ListType, TupleType
def match(pattern, data, vars=None):
if not same:
break
return same, vars
-\end{verbatim}\ecode
+\end{verbatim}
%
Using this simple representation for syntactic variables and the symbolic
node types, the pattern for the candidate docstring subtrees becomes
fairly readable. (See file \file{example.py}.)
-\bcode\begin{verbatim}
+\begin{verbatim}
import symbol
import token
)))))))))))))))),
(token.NEWLINE, '')
))
-\end{verbatim}\ecode
+\end{verbatim}
%
Using the \function{match()} function with this pattern, extracting the
module docstring from the parse tree created previously is easy:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> found, vars = match(DOCSTRING_STMT_PATTERN, tup[1])
>>> found
1
>>> vars
{'docstring': '"""Some documentation.\012"""'}
-\end{verbatim}\ecode
+\end{verbatim}
%
Once specific data can be extracted from a location where it is
expected, the question of where information can be expected
objects requires further examination. Here is the relevant part of
the \class{SuiteInfoBase} definition from \file{example.py}:
-\bcode\begin{verbatim}
+\begin{verbatim}
class SuiteInfoBase:
_docstring = ''
_name = ''
elif cstmt[0] == symbol.classdef:
name = cstmt[2][1]
self._class_info[name] = ClassInfo(cstmt)
-\end{verbatim}\ecode
+\end{verbatim}
%
After initializing some internal state, the constructor calls the
\method{_extract_info()} method. This method performs the bulk of the
while the long form uses an indented block and allows nested
definitions:
-\bcode\begin{verbatim}
+\begin{verbatim}
def make_power(exp):
"Make a function that raises an argument to the exponent `exp'."
def raiser(x, y=exp):
return x ** y
return raiser
-\end{verbatim}\ecode
+\end{verbatim}
%
When the short form is used, the code block may contain a docstring as
the first, and possibly only, \constant{small_stmt} element. The
blocks. A high-level function can be used to extract the complete set
of information from a source file. (See file \file{example.py}.)
-\bcode\begin{verbatim}
+\begin{verbatim}
def get_docs(fileName):
source = open(fileName).read()
import os
ast = parser.suite(source)
tup = parser.ast2tuple(ast)
return ModuleInfo(tup, basename)
-\end{verbatim}\ecode
+\end{verbatim}
%
This provides an easy-to-use interface to the documentation of a
module. If information is required which is not extracted by the code
This module also provides one additional data object:
-\renewcommand{\indexsubitem}{(in module symbol)}
+\setindexsubitem{(in module symbol)}
\begin{datadesc}{sym_name}
This module also provides one data object and some functions. The
functions mirror definitions in the Python C header files.
-\renewcommand{\indexsubitem}{(in module token)}
+\setindexsubitem{(in module token)}
\begin{datadesc}{tok_name}
\stmodindex{pdb}
\index{debugging}
-\renewcommand{\indexsubitem}{(in module pdb)}
+\setindexsubitem{(in module pdb)}
The module \code{pdb} defines an interactive source code debugger for
Python programs. It supports setting
The debugger's prompt is ``\code{(Pdb) }''.
Typical usage to run a program under control of the debugger is:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import pdb
>>> import mymodule
>>> pdb.run('mymodule.test()')
NameError: 'spam'
> <string>(1)?()
(Pdb)
-\end{verbatim}\ecode
+\end{verbatim}
%
\code{pdb.py} can also be invoked as
a script to debug other scripts. For example:
Typical usage to inspect a crashed program is:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import pdb
>>> import mymodule
>>> mymodule.test()
> ./mymodule.py(3)test2()
-> print spam
(Pdb)
-\end{verbatim}\ecode
+\end{verbatim}
%
The module defines the following functions; each enters the debugger
in a slightly different way:
of the statement resembles a debugger command.
To set a global variable, you can prefix the assignment
command with a ``\code{global}'' command on the same line, e.g.:
-\bcode\begin{verbatim}
+\begin{verbatim}
(Pdb) global list_options; list_options = ['-l']
(Pdb)
-\end{verbatim}\ecode
+\end{verbatim}
%
\item[q(uit)]
\indexii{flattening}{objects}
\indexii{pickling}{objects}
-\renewcommand{\indexsubitem}{(in module pickle)}
+\setindexsubitem{(in module pickle)}
The \code{pickle} module implements a basic but powerful algorithm for
``pickling'' (a.k.a.\ serializing, marshalling or flattening) nearly
First of all, the class must be defined at the top level in a module.
Furthermore, all its instance variables must be picklable.
-\renewcommand{\indexsubitem}{(pickle protocol)}
+\setindexsubitem{(pickle protocol)}
When a pickled class instance is unpickled, its \code{__init__()} method
is normally \emph{not} invoked. \strong{Note:} This is a deviation
Therefore, the restriction that the class must be defined at the top
level in a module applies to pickled classes as well.
-\renewcommand{\indexsubitem}{(in module pickle)}
+\setindexsubitem{(in module pickle)}
The interface can be summarized as follows.
To pickle an object \code{x} onto a file \code{f}, open for writing:
-\bcode\begin{verbatim}
+\begin{verbatim}
p = pickle.Pickler(f)
p.dump(x)
-\end{verbatim}\ecode
+\end{verbatim}
%
A shorthand for this is:
-\bcode\begin{verbatim}
+\begin{verbatim}
pickle.dump(x, f)
-\end{verbatim}\ecode
+\end{verbatim}
%
To unpickle an object \code{x} from a file \code{f}, open for reading:
-\bcode\begin{verbatim}
+\begin{verbatim}
u = pickle.Unpickler(f)
x = u.load()
-\end{verbatim}\ecode
+\end{verbatim}
%
A shorthand is:
-\bcode\begin{verbatim}
+\begin{verbatim}
x = pickle.load(f)
-\end{verbatim}\ecode
+\end{verbatim}
%
The \code{Pickler} class only calls the method \code{f.write()} with a
string argument. The \code{Unpickler} calls the methods \code{f.read()}
Module \code{posix} defines the following data items:
-\renewcommand{\indexsubitem}{(data in module posix)}
+\setindexsubitem{(data in module posix)}
\begin{datadesc}{environ}
A dictionary representing the string environment at the time
the interpreter was started.
\code{putenv()} automatically called whenever an item is changed.
\end{datadesc}
-\renewcommand{\indexsubitem}{(exception in module posix)}
+\setindexsubitem{(exception in module posix)}
\begin{excdesc}{error}
This exception is raised when a \POSIX{} function returns a
\POSIX{}-related error (e.g., not for illegal argument types). Its
It defines the following functions and constants:
-\renewcommand{\indexsubitem}{(in module posix)}
+\setindexsubitem{(in module posix)}
\begin{funcdesc}{chdir}{path}
Change the current working directory to \var{path}.
\end{funcdesc}
The posixfile module defines the following constants:
-\renewcommand{\indexsubitem}{(in module posixfile)}
+\setindexsubitem{(in module posixfile)}
\begin{datadesc}{SEEK_SET}
offset is calculated from the start of the file
\end{datadesc}
The posixfile module defines the following functions:
-\renewcommand{\indexsubitem}{(in module posixfile)}
+\setindexsubitem{(in module posixfile)}
\begin{funcdesc}{open}{filename\optional{\, mode\optional{\, bufsize}}}
Create a new posixfile object with the given filename and mode. The
The posixfile object defines the following additional methods:
-\renewcommand{\indexsubitem}{(posixfile method)}
+\setindexsubitem{(posixfile method)}
\begin{funcdesc}{lock}{fmt\, \optional{len\optional{\, start\optional{\, whence}}}}
Lock the specified section of the file that the file object is
referring to. The format is explained
Examples:
-\bcode\begin{verbatim}
+\begin{verbatim}
from posixfile import *
file = open('/tmp/test', 'w')
...
file.lock('u')
file.close()
-\end{verbatim}\ecode
+\end{verbatim}
module \code{os} and use \code{os.path}.
\refstmodindex{os}
-\renewcommand{\indexsubitem}{(in module posixpath)}
+\setindexsubitem{(in module posixpath)}
\begin{funcdesc}{basename}{p}
Return the base name of pathname
The \code{pprint} module defines one class:
-\renewcommand{\indexsubitem}{(in module pprint)}
+\setindexsubitem{(in module pprint)}
% First the implementation class:
PrettyPrinter instances (returned by \code{PrettyPrinter()} above)
have the following methods.
-\renewcommand{\indexsubitem}{(PrettyPrinter method)}
+\setindexsubitem{(PrettyPrinter method)}
\begin{funcdesc}{pformat}{object}
Return the formatted representation of \var{object}. This takes into
To profile an application with a main entry point of \samp{foo()}, you
would add the following to your module:
-\bcode\begin{verbatim}
+\begin{verbatim}
import profile
profile.run("foo()")
-\end{verbatim}\ecode
+\end{verbatim}
%
The above action would cause \samp{foo()} to be run, and a series of
informative lines (the profile) to be printed. The above approach is
can supply a file name as the second argument to the \code{run()}
function:
-\bcode\begin{verbatim}
+\begin{verbatim}
import profile
profile.run("foo()", 'fooprof')
-\end{verbatim}\ecode
+\end{verbatim}
%
\code{profile.py} can also be invoked as
a script to profile another script. For example:
\code{pstats} module. Typically you would load the statistics data as
follows:
-\bcode\begin{verbatim}
+\begin{verbatim}
import pstats
p = pstats.Stats('fooprof')
-\end{verbatim}\ecode
+\end{verbatim}
%
The class \code{Stats} (the above code just created an instance of
this class) has a variety of methods for manipulating and printing the
\code{profile.run()} above, what was printed was the result of three
method calls:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.strip_dirs().sort_stats(-1).print_stats()
-\end{verbatim}\ecode
+\end{verbatim}
%
The first method removed the extraneous path from all the module
names. The second method sorted all the entries according to the
with the semantics of the old profiler). The third method printed out
all the statistics. You might try the following sort calls:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.sort_stats('name')
p.print_stats()
-\end{verbatim}\ecode
+\end{verbatim}
%
The first call will actually sort the list by function name, and the
second call will print out the statistics. The following are some
interesting calls to experiment with:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.sort_stats('cumulative').print_stats(10)
-\end{verbatim}\ecode
+\end{verbatim}
%
This sorts the profile by cumulative time in a function, and then only
prints the ten most significant lines. If you want to understand what
If you were looking to see what functions were looping a lot, and
taking a lot of time, you would do:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.sort_stats('time').print_stats(10)
-\end{verbatim}\ecode
+\end{verbatim}
%
to sort according to time spent within each function, and then print
the statistics for the top ten functions.
You might also try:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.sort_stats('file').print_stats('__init__')
-\end{verbatim}\ecode
+\end{verbatim}
%
This will sort all the statistics by file name, and then print out
statistics for only the class init methods ('cause they are spelled
with \code{__init__} in them). As one final example, you could try:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.sort_stats('time', 'cum').print_stats(.5, 'init')
-\end{verbatim}\ecode
+\end{verbatim}
%
This line sorts statistics with a primary key of time, and a secondary
key of cumulative time, and then prints out some of the statistics.
If you wondered what functions called the above functions, you could
now (\samp{p} is still sorted according to the last criteria) do:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.print_callers(.5, 'init')
-\end{verbatim}\ecode
+\end{verbatim}
%
and you would get a list of callers for each of the listed functions.
If you want more functionality, you're going to have to read the
manual, or guess what the following functions do:
-\bcode\begin{verbatim}
+\begin{verbatim}
p.print_callees()
p.add('fooprof')
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{What Is Deterministic Profiling?}
\nodename{Deterministic Profiling}
\section{Reference Manual}
-\renewcommand{\indexsubitem}{(profiler function)}
+\setindexsubitem{(profiler function)}
The primary entry point for the profiler is the global function
\code{profile.run()}. It is typically used to create any profile
standard name string (file/line/function-name) that is presented in
each line. The following is a typical output from such a call:
-\bcode\begin{verbatim}
+\begin{verbatim}
main()
2706 function calls (2004 primitive calls) in 4.504 CPU seconds
2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects)
43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate)
...
-\end{verbatim}\ecode
+\end{verbatim}
The first line indicates that this profile was generated by the call:\\
\code{profile.run('main()')}, and hence the exec'ed string is
\subsection{The \sectcode{Stats} Class}
-\renewcommand{\indexsubitem}{(Stats method)}
+\setindexsubitem{(Stats method)}
\begin{funcdesc}{strip_dirs}{}
This method for the \code{Stats} class removes all leading path information
defined by the \code{re} module). If several restrictions are
provided, then they are applied sequentially. For example:
-\bcode\begin{verbatim}
+\begin{verbatim}
print_stats(.1, "foo:")
-\end{verbatim}\ecode
+\end{verbatim}
%
would first limit the printing to first 10\% of list, and then only
print functions that were part of filename \samp{.*foo:}. In
contrast, the command:
-\bcode\begin{verbatim}
+\begin{verbatim}
print_stats("foo:", .1)
-\end{verbatim}\ecode
+\end{verbatim}
%
would limit the list to all functions having file names \samp{.*foo:},
and then proceed to only print the first 10\% of them.
return the instance that is being processed, so that the commands can
be strung together. For example:
-\bcode\begin{verbatim}
+\begin{verbatim}
pstats.Stats('foofile').strip_dirs().sort_stats('cum') \
.print_stats().ignore()
-\end{verbatim}\ecode
+\end{verbatim}
%
would perform all the indicated functions, but it would not return
the final reference to the \code{Stats} instance.%
be used to obtain this constant for a given platform (see discussion
in section Limitations above).
-\bcode\begin{verbatim}
+\begin{verbatim}
import profile
pr = profile.Profile()
pr.calibrate(100)
pr.calibrate(100)
pr.calibrate(100)
-\end{verbatim}\ecode
+\end{verbatim}
%
The argument to calibrate() is the number of times to try to do the
sample calls to get the CPU times. If your computer is \emph{very}
fast, you might have to do:
-\bcode\begin{verbatim}
+\begin{verbatim}
pr.calibrate(1000)
-\end{verbatim}\ecode
+\end{verbatim}
%
or even:
-\bcode\begin{verbatim}
+\begin{verbatim}
pr.calibrate(10000)
-\end{verbatim}\ecode
+\end{verbatim}
%
The object of this exercise is to get a fairly consistent result.
When you have a consistent answer, you are ready to use that number in
class should be modified to install the calibration constant on a Sun
Sparcstation 1000:
-\bcode\begin{verbatim}
+\begin{verbatim}
def trace_dispatch(self, frame, event, arg):
t = self.timer()
t = t[0] + t[1] - self.t - .00053 # Calibration constant
r = self.timer()
self.t = r[0] + r[1] - t # put back unrecorded delta
return
-\end{verbatim}\ecode
+\end{verbatim}
%
Note that if there is no calibration constant, then the line
containing the callibration constant should simply say:
-\bcode\begin{verbatim}
+\begin{verbatim}
t = t[0] + t[1] - self.t # no calibration constant
-\end{verbatim}\ecode
+\end{verbatim}
%
You can also achieve the same results using a derived class (and the
profiler will actually run equally fast!!), but the above method is
the constructor for the class. Consider passing the name of a
function to call into the constructor:
-\bcode\begin{verbatim}
+\begin{verbatim}
pr = profile.Profile(your_time_func)
-\end{verbatim}\ecode
+\end{verbatim}
%
The resulting profiler will call \code{your_time_func()} instead of
\code{os.times()}. The function should return either a single number
user's code. It is also a lot more accurate than the old profiler, as
it does not charge all its overhead time to the user's code.
-\bcode\begin{verbatim}
+\begin{verbatim}
class OldProfile(Profile):
def trace_dispatch_exception(self, frame, t):
callers[func_caller]
nc = nc + callers[func_caller]
self.stats[nor_func] = nc, nc, tt, ct, nor_callers
-\end{verbatim}\ecode
+\end{verbatim}
%
\subsection{HotProfile Class}
the basic profiler is so fast, that is probably not worth the savings
to give up the data, but this class still provides a nice example.
-\bcode\begin{verbatim}
+\begin{verbatim}
class HotProfile(Profile):
def trace_dispatch_exception(self, frame, t):
nc, tt = self.timings[func]
nor_func = self.func_normalize(func)
self.stats[nor_func] = nc, nc, tt, 0, {}
-\end{verbatim}\ecode
+\end{verbatim}
It defines the following items:
-\renewcommand{\indexsubitem}{(in module pwd)}
+\setindexsubitem{(in module pwd)}
\begin{funcdesc}{getpwuid}{uid}
Return the password database entry for the given numeric user ID.
\end{funcdesc}
The \code{Queue} module defines the following exception:
-\renewcommand{\indexsubitem}{(in module Queue)}
+\setindexsubitem{(in module Queue)}
\begin{excdesc}{Empty}
Exception raised when non-blocking get (e.g. \code{get_nowait()}) is
is not described here. See the source code for details. The public
interface methods are:
-\renewcommand{\indexsubitem}{(__init__ method)}
+\setindexsubitem{(__init__ method)}
\begin{funcdesc}{__init__}{maxsize}
Constructor for the class. \var{maxsize} is an integer that sets the
zero, the queue size is infinite.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(qsize method)}
+\setindexsubitem{(qsize method)}
\begin{funcdesc}{qsize}{}
Returns the approximate size of the queue. Because of multithreading
semantics, this number is not reliable.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(empty method)}
+\setindexsubitem{(empty method)}
\begin{funcdesc}{empty}{}
Returns 1 if the queue is empty, 0 otherwise. Because of
multithreading semantics, this is not reliable.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(full method)}
+\setindexsubitem{(full method)}
\begin{funcdesc}{full}{}
Returns 1 if the queue is full, 0 otherwise. Because of
multithreading semantics, this is not reliable.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(put method)}
+\setindexsubitem{(put method)}
\begin{funcdesc}{put}{item}
Puts \var{item} into the queue.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(get method)}
+\setindexsubitem{(get method)}
\begin{funcdesc}{get}{}
Gets and returns an item from the queue, blocking if necessary until
one is available.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(get_nowait method)}
+\setindexsubitem{(get_nowait method)}
\begin{funcdesc}{get_nowait}{}
Gets and returns an item from the queue if one is immediately
\indexii{quoted printable}{encoding}
\index{MIME!quoted-printable encoding}
-\renewcommand{\indexsubitem}{(in module quopri)}
+\setindexsubitem{(in module quopri)}
\begin{funcdesc}{decode}{input\, output}
Decode the contents of the \var{input} file and write the resulting
compatibility, the \code{rand} module is now considered obsolete; if
possible, use the \code{whrandom} module instead.
-\renewcommand{\indexsubitem}{(in module rand)}
+\setindexsubitem{(in module rand)}
\begin{funcdesc}{choice}{seq}
Returns a random element from the sequence \var{seq}.
used in common mathematical practice; most of these equations can be
found in any statistics text.
-\renewcommand{\indexsubitem}{(in module random)}
+\setindexsubitem{(in module random)}
\begin{funcdesc}{betavariate}{alpha\, beta}
Beta distribution. Conditions on the parameters are \code{alpha>-1}
and \code{beta>-1}.
The module defines the following functions and constants, and an exception:
-\renewcommand{\indexsubitem}{(in module re)}
+\setindexsubitem{(in module re)}
\begin{funcdesc}{compile}{pattern\optional{\, flags}}
Compile a regular expression pattern into a regular expression
The sequence
%
-\bcode\begin{verbatim}
+\begin{verbatim}
prog = re.compile(pat)
result = prog.match(str)
-\end{verbatim}\ecode
+\end{verbatim}
%
is equivalent to
1.5 release, \var{maxsplit} was ignored. This has been fixed in
later releases.)
%
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> re.split('[\W]+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('([\W]+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('[\W]+', 'Words, words, words.', 1)
['Words', 'words, words.']
-\end{verbatim}\ecode
+\end{verbatim}
%
This function combines and extends the functionality of
the old \code{regsub.split()} and \code{regsub.splitx()}.
The function takes a single match object argument, and returns the
replacement string. For example:
%
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> def dashrepl(matchobj):
... if matchobj.group(0) == '-': return ' '
... else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
-\end{verbatim}\ecode
+\end{verbatim}
%
The pattern may be a string or a
regex object; if you need to specify
Compiled regular expression objects support the following methods and
attributes:
-\renewcommand{\indexsubitem}{(re method)}
+\setindexsubitem{(re method)}
\begin{funcdesc}{match}{string\optional{\, pos}\optional{\, endpos}}
If zero or more characters at the beginning of \var{string} match
this regular expression, return a corresponding
Identical to the \code{subn()} function, using the compiled pattern.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(regex attribute)}
+\setindexsubitem{(regex attribute)}
\begin{datadesc}{flags}
The flags argument used when the regex object was compiled, or 0 if no
The module defines these functions, and an exception:
-\renewcommand{\indexsubitem}{(in module regex)}
+\setindexsubitem{(in module regex)}
\begin{funcdesc}{match}{pattern\, string}
Return how many characters at the beginning of \var{string} match
The sequence
-\bcode\begin{verbatim}
+\begin{verbatim}
prog = regex.compile(pat)
result = prog.match(str)
-\end{verbatim}\ecode
+\end{verbatim}
%
is equivalent to
-\bcode\begin{verbatim}
+\begin{verbatim}
result = regex.match(pat, str)
-\end{verbatim}\ecode
+\end{verbatim}
but the version using \code{compile()} is more efficient when multiple
regular expressions are used concurrently in a single program. (The
\noindent
Compiled regular expression objects support these methods:
-\renewcommand{\indexsubitem}{(regex method)}
+\setindexsubitem{(regex method)}
\begin{funcdesc}{match}{string\optional{\, pos}}
Return how many characters at the beginning of \var{string} match
the compiled regular expression. Return \code{-1} if the string
\noindent
Compiled regular expressions support these data attributes:
-\renewcommand{\indexsubitem}{(regex attribute)}
+\setindexsubitem{(regex attribute)}
\begin{datadesc}{regs}
When the last call to the \code{match()} or \code{search()} method found a
conversion help, see the URL
\url{http://starship.skyport.net/crew/amk/regex/regex-to-re.html}.)
-\renewcommand{\indexsubitem}{(in module regsub)}
+\setindexsubitem{(in module regsub)}
\begin{funcdesc}{sub}{pat\, repl\, str}
Replace the first occurrence of pattern \var{pat} in string
A single exception is defined for errors:
-\renewcommand{\indexsubitem}{(in module resource)}
+\setindexsubitem{(in module resource)}
\begin{excdesc}{error}
The functions described below may raise this error if the underlying
\section{Standard Module \sectcode{rexec}}
\label{module-rexec}
\stmodindex{rexec}
-\renewcommand{\indexsubitem}{(in module rexec)}
+\setindexsubitem{(in module rexec)}
-This module contains the \code{RExec} class, which supports
+This module contains the \class{RExec} class, which supports
\code{r_exec()}, \code{r_eval()}, \code{r_execfile()}, and
\code{r_import()} methods, which are restricted versions of the standard
Python functions \code{exec()}, \code{eval()}, \code{execfile()}, and
the \code{import} statement.
Code executed in this restricted environment will
only have access to modules and functions that are deemed safe; you
-can subclass \code{RExec} to add or remove capabilities as desired.
+can subclass \class{RExec} to add or remove capabilities as desired.
-\emph{Note:} The \code{RExec} class can prevent code from performing
+\emph{Note:} The \class{RExec} class can prevent code from performing
unsafe operations like reading or writing disk files, or using TCP/IP
sockets. However, it does not protect against code using extremely
large amounts of memory or CPU time.
\begin{funcdesc}{RExec}{\optional{hooks\optional{\, verbose}}}
-Returns an instance of the \code{RExec} class.
+Returns an instance of the \class{RExec} class.
\var{hooks} is an instance of the \code{RHooks} class or a subclass of it.
If it is omitted or \code{None}, the default \code{RHooks} class is
instantiated.
-Whenever the RExec module searches for a module (even a built-in one)
-or reads a module's code, it doesn't actually go out to the file
-system itself. Rather, it calls methods of an RHooks instance that
-was passed to or created by its constructor. (Actually, the RExec
-object doesn't make these calls---they are made by a module loader
-object that's part of the RExec object. This allows another level of
-flexibility, e.g. using packages.)
-
-By providing an alternate RHooks object, we can control the
+Whenever the \module{RExec} module searches for a module (even a
+built-in one) or reads a module's code, it doesn't actually go out to
+the file system itself. Rather, it calls methods of an \class{RHooks}
+instance that was passed to or created by its constructor. (Actually,
+the \class{RExec} object doesn't make these calls --- they are made by
+a module loader object that's part of the \class{RExec} object. This
+allows another level of flexibility, e.g. using packages.)
+
+By providing an alternate \class{RHooks} object, we can control the
file system accesses made to import a module, without changing the
actual algorithm that controls the order in which those accesses are
-made. For instance, we could substitute an RHooks object that passes
-all filesystem requests to a file server elsewhere, via some RPC
-mechanism such as ILU. Grail's applet loader uses this to support
+made. For instance, we could substitute an \class{RHooks} object that
+passes all filesystem requests to a file server elsewhere, via some
+RPC mechanism such as ILU. Grail's applet loader uses this to support
importing applets from a URL for a directory.
If \var{verbose} is true, additional debugging output may be sent to
standard output.
\end{funcdesc}
-The RExec class has the following class attributes, which are used by the
-\code{__init__} method. Changing them on an existing instance won't
-have any effect; instead, create a subclass of \code{RExec} and assign
-them new values in the class definition. Instances of the new class
-will then use those new values. All these attributes are tuples of
-strings.
+The \class{RExec} class has the following class attributes, which are
+used by the \code{__init__()} method. Changing them on an existing
+instance won't have any effect; instead, create a subclass of
+\class{RExec} and assign them new values in the class definition.
+Instances of the new class will then use those new values. All these
+attributes are tuples of strings.
-\renewcommand{\indexsubitem}{(RExec object attribute)}
+\setindexsubitem{(RExec object attribute)}
\begin{datadesc}{nok_builtin_names}
Contains the names of built-in functions which will \emph{not} be
available to programs running in the restricted environment. The
-value for \code{RExec} is \code{('open',} \code{'reload',}
+value for \class{RExec} is \code{('open',} \code{'reload',}
\code{'__import__')}. (This gives the exceptions, because by far the
majority of built-in functions are harmless. A subclass that wants to
override this variable should probably start with the value from the
\begin{datadesc}{ok_builtin_modules}
Contains the names of built-in modules which can be safely imported.
-The value for \code{RExec} is \code{('audioop',} \code{'array',}
+The value for \class{RExec} is \code{('audioop',} \code{'array',}
\code{'binascii',} \code{'cmath',} \code{'errno',} \code{'imageop',}
\code{'marshal',} \code{'math',} \code{'md5',} \code{'operator',}
\code{'parser',} \code{'regex',} \code{'rotor',} \code{'select',}
\begin{datadesc}{ok_path}
Contains the directories which will be searched when an \code{import}
is performed in the restricted environment.
-The value for \code{RExec} is the same as \code{sys.path} (at the time
+The value for \class{RExec} is the same as \code{sys.path} (at the time
the module is loaded) for unrestricted code.
\end{datadesc}
% Should this be called ok_os_names?
Contains the names of the functions in the \code{os} module which will be
available to programs running in the restricted environment. The
-value for \code{RExec} is \code{('error',} \code{'fstat',}
+value for \class{RExec} is \code{('error',} \code{'fstat',}
\code{'listdir',} \code{'lstat',} \code{'readlink',} \code{'stat',}
\code{'times',} \code{'uname',} \code{'getpid',} \code{'getppid',}
\code{'getcwd',} \code{'getuid',} \code{'getgid',} \code{'geteuid',}
\begin{datadesc}{ok_sys_names}
Contains the names of the functions and variables in the \code{sys}
module which will be available to programs running in the restricted
-environment. The value for \code{RExec} is \code{('ps1',}
+environment. The value for \class{RExec} is \code{('ps1',}
\code{'ps2',} \code{'copyright',} \code{'version',} \code{'platform',}
\code{'exit',} \code{'maxint')}.
\end{datadesc}
-RExec instances support the following methods:
-\renewcommand{\indexsubitem}{(RExec object method)}
+\class{RExec} instances support the following methods:
+\setindexsubitem{(RExec object method)}
\begin{funcdesc}{r_eval}{code}
\var{code} must either be a string containing a Python expression, or
restricted environment.
\end{funcdesc}
-\code{RExec} objects must also support various methods which will be
+\class{RExec} objects must also support various methods which will be
implicitly called by code executing in the restricted environment.
Overriding these methods in a subclass is used to change the policies
enforced by a restricted environment.
Method called when \code{open()} is called in the restricted
environment. The arguments are identical to those of \code{open()},
and a file object (or a class instance compatible with file objects)
-should be returned. \code{RExec}'s default behaviour is allow opening
+should be returned. \class{RExec}'s default behaviour is allow opening
any file for reading, but forbidding any attempt to write a file. See
the example below for an implementation of a less restrictive
\code{r_open()}.
And their equivalents with access to restricted standard I/O streams:
\begin{funcdesc}{s_import}{modulename\optional{\, globals, locals, fromlist}}
-Import the module \var{modulename}, raising an \code{ImportError}
+Import the module \var{modulename}, raising an \exception{ImportError}
exception if the module is considered unsafe.
\end{funcdesc}
\subsection{An example}
Let us say that we want a slightly more relaxed policy than the
-standard RExec class. For example, if we're willing to allow files in
-\file{/tmp} to be written, we can subclass the \code{RExec} class:
+standard \class{RExec} class. For example, if we're willing to allow
+files in \file{/tmp} to be written, we can subclass the \class{RExec}
+class:
-\bcode\begin{verbatim}
+\begin{verbatim}
class TmpWriterRExec(rexec.RExec):
def r_open(self, file, mode='r', buf=-1):
if mode in ('r', 'rb'):
raise IOError, "'..' in filename forbidden"
else: raise IOError, "Illegal open() mode"
return open(file, mode, buf)
-\end{verbatim}\ecode
+\end{verbatim}
%
Notice that the above code will occasionally forbid a perfectly valid
filename; for example, code in the restricted environment won't be
\label{module-rfc822}
\stmodindex{rfc822}
-\renewcommand{\indexsubitem}{(in module rfc822)}
+\setindexsubitem{(in module rfc822)}
This module defines a class, \code{Message}, which represents a
collection of ``email headers'' as defined by the Internet standard
The module defines the following variables and functions:
-\renewcommand{\indexsubitem}{(in module rgbimg)}
+\setindexsubitem{(in module rgbimg)}
\begin{excdesc}{error}
This exception is raised on all errors, such as unsupported file type, etc.
\end{excdesc}
The available functions in this module are:
-\renewcommand{\indexsubitem}{(in module rotor)}
+\setindexsubitem{(in module rotor)}
\begin{funcdesc}{newrotor}{key\optional{\, numrotors}}
Return a rotor object. \var{key} is a string containing the encryption key
for the object; it can contain arbitrary binary data. The key will be used
Rotor objects have the following methods:
-\renewcommand{\indexsubitem}{(rotor method)}
+\setindexsubitem{(rotor method)}
\begin{funcdesc}{setkey}{key}
Sets the rotor's key to \var{key}.
\end{funcdesc}
\end{funcdesc}
An example usage:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import rotor
>>> rt = rotor.newrotor('key', 12)
>>> rt.encrypt('bar')
>>> rt.decrypt('\357\375$')
'l(\315'
>>> del rt
-\end{verbatim}\ecode
+\end{verbatim}
%
The module's code is not an exact simulation of the original Enigma device;
it implements the rotor encryption scheme differently from the original. The
This module provides access to the function \code{select} available in
most \UNIX{} versions. It defines the following:
-\renewcommand{\indexsubitem}{(in module select)}
+\setindexsubitem{(in module select)}
\begin{excdesc}{error}
The exception raised when an error occurs. The accompanying value is
a pair containing the numeric error code from \code{errno} and the
The \code{SGMLParser} class must be instantiated without arguments.
It has the following interface methods:
-\renewcommand{\indexsubitem}{(SGMLParser method)}
+\setindexsubitem{(SGMLParser method)}
\begin{funcdesc}{reset}{}
Reset the instance. Loses all unprocessed data. This is called
To summarize the interface (\code{key} is a string, \code{data} is an
arbitrary object):
-\bcode\begin{verbatim}
+\begin{verbatim}
import shelve
d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
list = d.keys() # a list of all existing keys (slow!)
d.close() # close it
-\end{verbatim}\ecode
+\end{verbatim}
%
Restrictions:
The variables defined in the \module{signal} module are:
-\renewcommand{\indexsubitem}{(in module signal)}
+\setindexsubitem{(in module signal)}
\begin{datadesc}{SIG_DFL}
This is one of two standard signal handling options; it will simply
perform the default function for the signal. For example, on most
In earlier versions of Python (up to and including 1.5a3), scripts or
modules that needed to use site-specific modules would place
-\code{import site} somewhere near the top of their code. This is no
+\samp{import site} somewhere near the top of their code. This is no
longer necessary.
This will append site-specific paths to to the module search path.
files, \file{foo.pth} and \file{bar.pth}. Assume \file{foo.pth}
contains the following:
-\bcode\begin{verbatim}
+\begin{verbatim}
# foo package configuration
foo
bar
bletch
-\end{verbatim}\ecode
+\end{verbatim}
and \file{bar.pth} contains:
-\bcode\begin{verbatim}
+\begin{verbatim}
# bar package configuration
bar
-\end{verbatim}\ecode
+\end{verbatim}
Then the following directories are added to \code{sys.path}, in this
order:
-\bcode\begin{verbatim}
+\begin{verbatim}
/usr/local/python1.5/site-packages/bar
/usr/local/python1.5/site-packages/foo
-\end{verbatim}\ecode
+\end{verbatim}
Note that \file{bletch} is omitted because it doesn't exist; the
\file{bar} directory precedes the \file{foo} directory because
The module \code{socket} exports the following constants and functions:
-\renewcommand{\indexsubitem}{(in module socket)}
+\setindexsubitem{(in module socket)}
\begin{excdesc}{error}
This exception is raised for socket- or address-related errors.
The accompanying value is either a string telling what went wrong or a
\code{makefile()} these correspond to \UNIX{} system calls applicable to
sockets.
-\renewcommand{\indexsubitem}{(socket method)}
+\setindexsubitem{(socket method)}
\begin{funcdesc}{accept}{}
Accept a connection.
The socket must be bound to an address and listening for connections.
socket it is listening on but on the new socket returned by
\code{accept}.
-\bcode\begin{verbatim}
+\begin{verbatim}
# Echo server program
from socket import *
HOST = '' # Symbolic name meaning the local host
if not data: break
conn.send(data)
conn.close()
-\end{verbatim}\ecode
+\end{verbatim}
%
-\bcode\begin{verbatim}
+\begin{verbatim}
# Echo client program
from socket import *
HOST = 'daring.cwi.nl' # The remote host
data = s.recv(1024)
s.close()
print 'Received', `data`
-\end{verbatim}\ecode
+\end{verbatim}
%
\begin{seealso}
\seemodule{SocketServer}{classes that simplify writing network servers}
Server classes have the same external methods and attributes, no
matter what network protocol they use:
-\renewcommand{\indexsubitem}{(SocketServer protocol)}
+\setindexsubitem{(SocketServer protocol)}
%XXX should data and methods be intermingled, or separate?
% how should the distinction between class and instance variables be
\label{module-soundex}
\bimodindex{soundex}
-\renewcommand{\indexsubitem}{(in module soundex)}
+\setindexsubitem{(in module soundex)}
The soundex algorithm takes an English word, and returns an
easily-computed hash of it; this hash is intended to be the same for
words that sound alike. This module provides an interface to the
The \code{stat} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module stat)}
+\setindexsubitem{(in module stat)}
\begin{funcdesc}{S_ISDIR}{mode}
Return non-zero if the mode was gotten from a directory.
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
import os, sys
from stat import *
print 'frobbed', file
if __name__ == '__main__': process(sys.argv[1], f)
-\end{verbatim}\ecode
+\end{verbatim}
The following functions are defined in the \code{stdwin} module:
-\renewcommand{\indexsubitem}{(in module stdwin)}
+\setindexsubitem{(in module stdwin)}
\begin{funcdesc}{open}{title}
Open a new window whose initial title is given by the string argument.
Return a window object; window object methods are described below.%
Return the default foreground color for unknown color names.
Hint: the following code tests whether you are on a machine that
supports more than two colors:
-\bcode\begin{verbatim}
+\begin{verbatim}
if stdwin.fetchcolor('black') <> \
stdwin.fetchcolor('red') <> \
stdwin.fetchcolor('white'):
print 'color machine'
else:
print 'monochrome machine'
-\end{verbatim}\ecode
+\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{setfgcolor}{pixel}
by their \code{close()} method or when they are garbage-collected.
Window objects have the following methods:
-\renewcommand{\indexsubitem}{(window method)}
+\setindexsubitem{(window method)}
\begin{funcdesc}{begindrawing}{}
Return a drawing object, whose methods (described below) allow drawing
is called.
Drawing objects have the following methods:
-\renewcommand{\indexsubitem}{(drawing method)}
+\setindexsubitem{(drawing method)}
\begin{funcdesc}{box}{rect}
Draw a box just inside a rectangle.
The menu is destroyed when the menu object is deleted.
The following methods are defined:
-\renewcommand{\indexsubitem}{(menu method)}
+\setindexsubitem{(menu method)}
\begin{funcdesc}{additem}{text\, shortcut}
Add a menu item with given text.
The following methods are defined:
-\renewcommand{\indexsubitem}{(bitmap method)}
+\setindexsubitem{(bitmap method)}
\begin{funcdesc}{getsize}{}
Return a tuple representing the width and height of the bitmap.
For semantics, see the STDWIN documentation for C programmers.
The following methods exist:
-\renewcommand{\indexsubitem}{(text-edit method)}
+\setindexsubitem{(text-edit method)}
\begin{funcdesc}{arrow}{code}
Pass an arrow event to the text-edit block.
The window will be correctly redrawn when covered and re-exposed.
The program quits when the close icon or menu item is requested.
-\bcode\begin{verbatim}
+\begin{verbatim}
import stdwin
from stdwinevents import *
break
main()
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{Standard Module \sectcode{stdwinevents}}
\stmodindex{stdwinevents}
Read the file for details.
Suggested usage is
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> from stdwinevents import *
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{Standard Module \sectcode{rect}}
\stmodindex{rect}
a pair of points, where a point is a pair of integers.
For example, the rectangle
-\bcode\begin{verbatim}
+\begin{verbatim}
(10, 20), (90, 80)
-\end{verbatim}\ecode
+\end{verbatim}
%
is a rectangle whose left, top, right and bottom edges are 10, 20, 90
and 80, respectively.
The module defines the following objects:
-\renewcommand{\indexsubitem}{(in module rect)}
+\setindexsubitem{(in module rect)}
\begin{excdesc}{error}
The exception raised by functions in this module when they detect an
error.
The rectangle returned when some operations return an empty result.
This makes it possible to quickly check whether a result is empty:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import rect
>>> r1 = (10, 20), (90, 80)
>>> r2 = (0, 0), (10, 20)
>>> if r3 is rect.empty: print 'Empty intersection'
Empty intersection
>>>
-\end{verbatim}\ecode
+\end{verbatim}
\end{datadesc}
\begin{funcdesc}{is_empty}{r}
The constants defined in this module are are:
-\renewcommand{\indexsubitem}{(data in module string)}
+\setindexsubitem{(data in module string)}
\begin{datadesc}{digits}
The string \code{'0123456789'}.
\end{datadesc}
The functions defined in this module are:
-\renewcommand{\indexsubitem}{(in module string)}
+\setindexsubitem{(in module string)}
\begin{funcdesc}{atof}{s}
Convert a string to a floating point number. The string must have
The module defines the following exception and functions:
-\renewcommand{\indexsubitem}{(in module struct)}
+\setindexsubitem{(in module struct)}
\begin{excdesc}{error}
Exception raised on various occasions; argument is a string
describing what is wrong.
Examples (all using native byte order, size and alignment, on a
big-endian machine):
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\000\001\000\002\000\000\000\003'
>>> calcsize('hhl')
8
>>>
-\end{verbatim}\ecode
+\end{verbatim}
%
Hint: to align the end of a structure to the alignment requirement of
a particular type, end the format with the code for that type with a
The module defines the following variables and functions:
-\renewcommand{\indexsubitem}{(in module sunaudiodev)}
+\setindexsubitem{(in module sunaudiodev)}
\begin{excdesc}{error}
This exception is raised on all errors. The argument is a string
describing what went wrong.
following methods (except \code{control} objects which only provide
getinfo, setinfo and drain):
-\renewcommand{\indexsubitem}{(audio device method)}
+\setindexsubitem{(audio device method)}
\begin{funcdesc}{close}{}
This method explicitly closes the device. It is useful in situations
interpreter and to functions that interact strongly with the interpreter.
It is always available.
-\renewcommand{\indexsubitem}{(in module sys)}
+\setindexsubitem{(in module sys)}
\begin{datadesc}{argv}
The list of command line arguments passed to a Python script.
set at build time with the \code{--exec-prefix} argument to the
\code{configure} script. Specifically, all configuration files
(e.g. the \code{config.h} header file) are installed in the directory
-\code{sys.exec_prefix+"/lib/python\emph{VER}/config"}, and shared library
+\code{sys.exec_prefix+"/lib/python\var{version}/config"}, and shared library
modules are installed in
-\code{sys.exec_prefix+"/lib/python\emph{VER}/lib-dynload"},
-where \emph{VER} is equal to \code{sys.version[:3]}.
+\code{sys.exec_prefix+"/lib/python\var{version}/lib-dynload"},
+where \var{version} is equal to \code{sys.version[:3]}.
\end{datadesc}
\begin{funcdesc}{exit}{n}
\code{"/usr/local"}. This can be set at build time with the
\code{--prefix} argument to the \code{configure} script. The main
collection of Python library modules is installed in the directory
-\code{sys.prefix+"/lib/python\emph{VER}"} while the platform
+\code{sys.prefix+"/lib/python\var{version}"} while the platform
independent header files (all except \code{config.h}) are stored in
-\code{sys.prefix+"/include/python\emph{VER}"},
-where \emph{VER} is equal to \code{sys.version[:3]}.
+\code{sys.prefix+"/include/python\var{version}"},
+where \var{version} is equal to \code{sys.version[:3]}.
\end{datadesc}
The module defines the following functions:
-\renewcommand{\indexsubitem}{(in module syslog)}
+\setindexsubitem{(in module syslog)}
\begin{funcdesc}{syslog}{\optional{priority\,} message}
Send the string \var{message} to the system logger.
\indexii{temporary}{file name}
\indexii{temporary}{file}
-\renewcommand{\indexsubitem}{(in module tempfile)}
+\setindexsubitem{(in module tempfile)}
This module generates temporary file names. It is not \UNIX{} specific,
but it may require some help on non-\UNIX{} systems.
% Redefine the ``indexsubitem'' macro to point to this module
% (alternatively, you can put this at the top of the file):
-\renewcommand{\indexsubitem}{(in module spam)}
+\setindexsubitem{(in module spam)}
% ---- 3.2. ----
% For each function, use a ``funcdesc'' block. This has exactly two
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import spam
>>> can = spam.open('/etc/passwd')
>>> can.empty()
>>> can.close()
-\end{verbatim}\ecode
+\end{verbatim}
%
% ==== 5. ====
% If your module defines new object types (for a built-in module) or
Spam objects (returned by \code{open()} above) have the following
methods.
-\renewcommand{\indexsubitem}{(spam method)}
+\setindexsubitem{(spam method)}
\begin{funcdesc}{empty}{}
Empty the can into the trash.
\indexii{\POSIX{}}{I/O control}
\indexii{tty}{I/O control}
-\renewcommand{\indexsubitem}{(in module termios)}
+\setindexsubitem{(in module termios)}
This module provides an interface to the \POSIX{} calls for tty I/O
control. For a complete description of these calls, see the \POSIX{} or
and a \code{try \ldots{} finally} statement to ensure that the old tty
attributes are restored exactly no matter what happens:
-\bcode\begin{verbatim}
+\begin{verbatim}
def getpass(prompt = "Password: "):
import termios, TERMIOS, sys
fd = sys.stdin.fileno()
finally:
termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old)
return passwd
-\end{verbatim}\ecode
+\end{verbatim}
%
\section{Standard Module \sectcode{TERMIOS}}
\stmodindex{TERMIOS}
\indexii{\POSIX{}}{I/O control}
\indexii{tty}{I/O control}
-\renewcommand{\indexsubitem}{(in module TERMIOS)}
+\setindexsubitem{(in module TERMIOS)}
This module defines the symbolic constants required to use the
\code{termios} module (see the previous section). See the \POSIX{} or
It defines the following constant and functions:
-\renewcommand{\indexsubitem}{(in module thread)}
+\setindexsubitem{(in module thread)}
\begin{excdesc}{error}
Raised on thread-specific errors.
\end{excdesc}
Lock objects have the following methods:
-\renewcommand{\indexsubitem}{(lock method)}
+\setindexsubitem{(lock method)}
\begin{funcdesc}{acquire}{\optional{waitflag}}
Without the optional argument, this method acquires the lock
unconditionally, if necessary waiting until it is released by another
The module defines the following functions and data items:
-\renewcommand{\indexsubitem}{(in module time)}
+\setindexsubitem{(in module time)}
\begin{datadesc}{altzone}
The offset of the local DST timezone, in seconds west of the 0th
\label{module-traceback}
\stmodindex{traceback}
-\renewcommand{\indexsubitem}{(in module traceback)}
+\setindexsubitem{(in module traceback)}
This module provides a standard interface to format and print stack
traces of Python programs. It exactly mimics the behavior of the
\index{false}
\begin{itemize}
-\renewcommand{\indexsubitem}{(Built-in object)}
+\setindexsubitem{(Built-in object)}
\item \code{None}
\ttindex{None}
the formats in the string must have a parenthesized key into that
dictionary inserted immediately after the \code{\%} character, and
each format formats the corresponding entry from the mapping. E.g.
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> count = 2
>>> language = 'Python'
>>> print '%(language)s has %(count)03d quote types.' % vars()
Python has 002 quote types.
>>>
-\end{verbatim}\ecode
+\end{verbatim}
In this case no * specifiers may occur in a format (since they
require a sequential parameter list).
\indexii{subscript}{assignment}
\indexii{slice}{assignment}
\stindex{del}
-\renewcommand{\indexsubitem}{(list method)}
+\setindexsubitem{(list method)}
\ttindex{append}
\ttindex{count}
\ttindex{index}
\indexiii{operations on}{dictionary}{type}
\stindex{del}
\bifuncindex{len}
-\renewcommand{\indexsubitem}{(dictionary method)}
+\setindexsubitem{(dictionary method)}
\ttindex{keys}
\ttindex{has_key}
Files have the following methods:
-\renewcommand{\indexsubitem}{(file method)}
+\setindexsubitem{(file method)}
\begin{funcdesc}{close}{}
Close the file. A closed file cannot be read or written anymore.
\label{module-types}
\stmodindex{types}
-\renewcommand{\indexsubitem}{(in module types)}
+\setindexsubitem{(in module types)}
This module defines names for all object types that are used by the
standard Python interpreter (but not for the types defined by various
Typical use is for functions that do different things depending on
their argument types, like the following:
-\bcode\begin{verbatim}
+\begin{verbatim}
from types import *
def delete(list, item):
if type(item) is IntType:
del list[item]
else:
list.remove(item)
-\end{verbatim}\ecode
+\end{verbatim}
%
The module defines the following names:
\index{World-Wide Web}
\index{URL}
-\renewcommand{\indexsubitem}{(in module urllib)}
+\setindexsubitem{(in module urllib)}
This module provides a high-level interface for fetching data across
the World-Wide Web. In particular, the \code{urlopen()} function is
\indexii{URL}{parsing}
\indexii{relative}{URL}
-\renewcommand{\indexsubitem}{(in module urlparse)}
+\setindexsubitem{(in module urlparse)}
This module defines a standard interface to break URL strings up in
components (addessing scheme, network location, path etc.), to combine
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
-\end{verbatim}\ecode
+\end{verbatim}
%
yields the tuple
-\bcode\begin{verbatim}
+\begin{verbatim}
('http', 'www.cwi.nl:80', '/%7Eguido/Python.html', '', '', '')
-\end{verbatim}\ecode
+\end{verbatim}
%
If the \var{default_scheme} argument is specified, it gives the
default addressing scheme, to be used only if the URL string does not
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
-\end{verbatim}\ecode
+\end{verbatim}
%
yields the string
-\bcode\begin{verbatim}
+\begin{verbatim}
'http://www.cwi.nl/%7Eguido/FAQ.html'
-\end{verbatim}\ecode
+\end{verbatim}
%
The \var{allow_fragments} argument has the same meaning as for
\code{urlparse()}.
your module. For example, a module \code{spam} that has a verbosity
level can look for a variable \code{user.spam_verbose}, as follows:
-\bcode\begin{verbatim}
+\begin{verbatim}
import user
try:
verbose = user.spam_verbose # user's verbosity preference
except AttributeError:
verbose = 0 # default verbosity
-\end{verbatim}\ecode
+\end{verbatim}
Programs with extensive customization needs are better off reading a
program-specific customization file.
them and override existing methods or add new ones. In this way one
can add new behaviours to dictionaries or lists.
-\renewcommand{\indexsubitem}{(in module UserDict)}
+\setindexsubitem{(in module UserDict)}
The \code{UserDict} module defines the \code{UserDict} class:
\begin{funcdesc}{UserDict}{}
\code{data} attribute of \code{UserDict} instances.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(in module UserList)}
+\setindexsubitem{(in module UserList)}
The \code{UserList} module defines the \code{UserList} class:
\begin{funcdesc}{UserList}{\optional{list}}
several simple database modules available--dbm, gdbm, or
dbhash--should be used to open a given file.
-\renewcommand{\indexsubitem}{(in module whichdb)}
+\setindexsubitem{(in module whichdb)}
\begin{funcdesc}{whichdb}{filename}
Returns one of the following values: \code{None} if the file can't be
opened because it's unreadable or doesn't exist; the empty string
This module implements a Wichmann-Hill pseudo-random number generator
class that is also named \code{whrandom}. Instances of the
\code{whrandom} class have the following methods:
-\renewcommand{\indexsubitem}{(in module whrandom)}
+\setindexsubitem{(in module whrandom)}
\begin{funcdesc}{choice}{seq}
Chooses a random element from the non-empty sequence \var{seq} and returns it.
the \code{whrandom} class, and makes the methods of that instance
available at the module level. Therefore one can write either
\code{N = whrandom.random()} or:
-\bcode\begin{verbatim}
+\begin{verbatim}
generator = whrandom.whrandom()
N = generator.random()
-\end{verbatim}\ecode
+\end{verbatim}
%
\begin{seealso}
\seemodule{random}{generators for various random distributions}
\index{XDR}
\index{External Data Representation}
-\renewcommand{\indexsubitem}{(in module xdrlib)}
+\setindexsubitem{(in module xdrlib)}
The \code{xdrlib} module supports the External Data Representation
Here is an example of how you would catch one of these exceptions:
-\bcode\begin{verbatim}
+\begin{verbatim}
import xdrlib
p = xdrlib.Packer()
try:
p.pack_double(8.01)
except xdrlib.ConversionError, instance:
print 'packing the double failed:', instance.msg
-\end{verbatim}\ecode
+\end{verbatim}
The \code{XMLParser} class must be instantiated without arguments. It
has the following interface methods:
-\renewcommand{\indexsubitem}{(XMLParser method)}
+\setindexsubitem{(XMLParser method)}
\begin{funcdesc}{reset}{}
Reset the instance. Loses all unprocessed data. This is called
The available functions in this module are:
-\renewcommand{\indexsubitem}{(in module zlib)}
+\setindexsubitem{(in module zlib)}
\begin{funcdesc}{adler32}{string\optional{\, value}}
Computes a Adler-32 checksum of \var{string}. (An Adler-32
checksum is almost as reliable as a CRC32 but can be computed much
\section{Built-in Module \sectcode{ctb}}
\label{module-ctb}
\bimodindex{ctb}
-\renewcommand{\indexsubitem}{(in module ctb)}
+\setindexsubitem{(in module ctb)}
This module provides a partial interface to the Macintosh
Communications Toolbox. Currently, only Connection Manager tools are
For all connection methods that take a \var{timeout} argument, a value
of \code{-1} is indefinite, meaning that the command runs to completion.
-\renewcommand{\indexsubitem}{(connection object attribute)}
+\setindexsubitem{(connection object attribute)}
\begin{datadesc}{callback}
If this member is set to a value other than \code{None} it should point
\end{datadesc}
-\renewcommand{\indexsubitem}{(connection object method)}
+\setindexsubitem{(connection object method)}
\begin{funcdesc}{Open}{timeout}
Open an outgoing connection, waiting at most \var{timeout} seconds for
\label{module-macconsole}
\bimodindex{macconsole}
-\renewcommand{\indexsubitem}{(in module macconsole)}
+\setindexsubitem{(in module macconsole)}
This module is available on the Macintosh, provided Python has been
built using the Think C compiler. It provides an interface to the
\subsection{macconsole options object}
These options are examined when a window is created:
-\renewcommand{\indexsubitem}{(macconsole option)}
+\setindexsubitem{(macconsole option)}
\begin{datadesc}{top}
\dataline{left}
The origin of the window.
\subsection{console window object}
-\renewcommand{\indexsubitem}{(console window attribute)}
+\setindexsubitem{(console window attribute)}
\begin{datadesc}{file}
The file object corresponding to this console window. If the file is
and \code{read()} calls.
\end{datadesc}
-\renewcommand{\indexsubitem}{(console window method)}
+\setindexsubitem{(console window method)}
\begin{funcdesc}{setmode}{mode}
Set the input mode of the console to \var{C_ECHO}, etc.
The \code{macdnr} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module macdnr)}
+\setindexsubitem{(in module macdnr)}
\begin{funcdesc}{Open}{\optional{filename}}
Open the domain name resolver extension. If \var{filename} is given it
The \var{rtnCode} and \var{cname} attributes are always available, the
others depend on the type of query (address, hinfo or mx).
-\renewcommand{\indexsubitem}{(dnr result object method)}
+\setindexsubitem{(dnr result object method)}
% Add args, as in {arg1\, arg2 \optional{\, arg3}}
\begin{funcdesc}{wait}{}
Return 1 if the query is complete.
\end{funcdesc}
-\renewcommand{\indexsubitem}{(dnr result object attribute)}
+\setindexsubitem{(dnr result object attribute)}
\begin{datadesc}{rtnCode}
The error code returned by the query.
The simplest way to use the module to convert names to dotted-decimal
strings, without worrying about idle time, etc:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> def gethostname(name):
... import macdnr
... dnrr = macdnr.StrToAddr(name)
... return macdnr.AddrToStr(dnrr.ip0)
-\end{verbatim}\ecode
+\end{verbatim}
\label{module-macfs}
\bimodindex{macfs}
-\renewcommand{\indexsubitem}{(in module macfs)}
+\setindexsubitem{(in module macfs)}
This module provides access to macintosh FSSpec handling, the Alias
Manager, finder aliases and the Standard File package.
\subsection{FSSpec objects}
-\renewcommand{\indexsubitem}{(FSSpec object attribute)}
+\setindexsubitem{(FSSpec object attribute)}
\begin{datadesc}{data}
The raw data from the FSSpec object, suitable for passing
to other applications, for instance.
\end{datadesc}
-\renewcommand{\indexsubitem}{(FSSpec object method)}
+\setindexsubitem{(FSSpec object method)}
\begin{funcdesc}{as_pathname}{}
Return the full pathname of the file described by the FSSpec object.
\end{funcdesc}
\subsection{alias objects}
-\renewcommand{\indexsubitem}{(alias object attribute)}
+\setindexsubitem{(alias object attribute)}
\begin{datadesc}{data}
The raw data for the Alias record, suitable for storing in a resource
or transmitting to other programs.
\end{datadesc}
-\renewcommand{\indexsubitem}{(alias object method)}
+\setindexsubitem{(alias object method)}
\begin{funcdesc}{Resolve}{\optional{file}}
Resolve the alias. If the alias was created as a relative alias you
should pass the file relative to which it is. Return the FSSpec for
See Inside Mac for a complete description of what the various fields
mean.
-\renewcommand{\indexsubitem}{(FInfo object attribute)}
+\setindexsubitem{(FInfo object attribute)}
\begin{datadesc}{Creator}
The 4-char creator code of the file.
\end{datadesc}
\section{Standard Module \sectcode{ic}}
\bimodindex{ic}
-\renewcommand{\indexsubitem}{(in module ic)}
+\setindexsubitem{(in module ic)}
This module provides access to macintosh Internet Config package,
which stores preferences for Internet programs such as mail address,
Besides the dictionary interface IC objects have the following methods:
-\renewcommand{\indexsubitem}{(IC object attribute)}
+\setindexsubitem{(IC object attribute)}
\begin{funcdesc}{launchurl}{url \optional{, hint}}
Parse the given URL, lauch the correct application and pass it the
\label{module-MacOS}
\bimodindex{MacOS}
-\renewcommand{\indexsubitem}{(in module MacOS)}
+\setindexsubitem{(in module MacOS)}
This module provides access to MacOS specific functionality in the
python interpreter, such as how the interpreter eventloop functions
The \code{macostools} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module macostools)}
+\setindexsubitem{(in module macostools)}
\begin{funcdesc}{copy}{src\, dst\optional{\, createpath, copytimes}}
Copy file \var{src} to \var{dst}. The files can be specified as
The \code{findertools} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module macostools)}
+\setindexsubitem{(in module macostools)}
\begin{funcdesc}{launch}{file}
Tell the finder to launch \var{file}. What launching means depends on the file:
\label{module-macspeech}
\bimodindex{macspeech}
-\renewcommand{\indexsubitem}{(in module macspeech)}
+\setindexsubitem{(in module macspeech)}
This module provides an interface to the Macintosh Speech Manager,
allowing you to let the Macintosh utter phrases. You need a version of
Voice objects contain the description of a voice. It is currently not
yet possible to access the parameters of a voice.
-\renewcommand{\indexsubitem}{(voice object method)}
+\setindexsubitem{(voice object method)}
\begin{funcdesc}{GetGender}{}
Return the gender of the voice: 0 for male, 1 for female and -1 for neuter.
interrelated in some way, so that to make your Macintosh sing you will
have to adjust both.
-\renewcommand{\indexsubitem}{(speech channel object method)}
+\setindexsubitem{(speech channel object method)}
\begin{funcdesc}{SpeakText}{str}
Start uttering the given string.
\end{funcdesc}
\label{module-mactcp}
\bimodindex{mactcp}
-\renewcommand{\indexsubitem}{(in module mactcp)}
+\setindexsubitem{(in module mactcp)}
This module provides an interface to the Macintosh TCP/IP driver
MacTCP\@. There is an accompanying module \code{macdnr} which provides an
\subsection{TCP Stream Objects}
-\renewcommand{\indexsubitem}{(TCP stream attribute)}
+\setindexsubitem{(TCP stream attribute)}
\begin{datadesc}{asr}
When set to a value different than \code{None} this should point to a
It is safe to do further calls from the \code{asr}.
\end{datadesc}
-\renewcommand{\indexsubitem}{(TCP stream method)}
+\setindexsubitem{(TCP stream method)}
\begin{funcdesc}{PassiveOpen}{port}
Wait for an incoming connection on TCP port \var{port} (zero makes the
the connection. A complete description of all fields in this objects
can be found in the Apple documentation. The most interesting ones are:
-\renewcommand{\indexsubitem}{(TCP status attribute)}
+\setindexsubitem{(TCP status attribute)}
\begin{datadesc}{localHost}
\dataline{localPort}
Note that, unlike the name suggests, there is nothing stream-like
about UDP.
-\renewcommand{\indexsubitem}{(UDP stream attribute)}
+\setindexsubitem{(UDP stream attribute)}
\begin{datadesc}{asr}
The asynchronous service routine to be called on events such as
A read-only member giving the port number of this UDP stream.
\end{datadesc}
-\renewcommand{\indexsubitem}{(UDP stream method)}
+\setindexsubitem{(UDP stream method)}
\begin{funcdesc}{Read}{timeout}
Read a datagram, waiting at most \var{timeout} seconds (-1 is
The \code{EasyDialogs} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module EasyDialogs)}
+\setindexsubitem{(in module EasyDialogs)}
\begin{funcdesc}{Message}{str}
A modal dialog with the message text \var{str}, which should be at
The \code{FrameWork} module defines the following functions:
-\renewcommand{\indexsubitem}{(in module FrameWork)}
+\setindexsubitem{(in module FrameWork)}
\begin{funcdesc}{Application}{}
An object representing the complete application. See below for a
\subsection{Application objects}
Application objects have the following methods, among others:
-\renewcommand{\indexsubitem}{(Application method)}
+\setindexsubitem{(Application method)}
\begin{funcdesc}{makeusermenus}{}
Override this method if you need menus in your application. Append the
Window objects have the following methods, among others:
-\renewcommand{\indexsubitem}{(Window method)}
+\setindexsubitem{(Window method)}
\begin{funcdesc}{open}{}
Override this method to open a window. Store the MacOS window-id in
ControlsWindow objects have the following methods besides those of
\code{Window} objects:
-\renewcommand{\indexsubitem}{(ControlsWindow method)}
+\setindexsubitem{(ControlsWindow method)}
\begin{funcdesc}{do_controlhit}{window\, control\, pcode\, event}
Part \code{pcode} of control \code{control} was hit by the
ScrolledWindow objects are ControlsWindow objects with the following
extra methods:
-\renewcommand{\indexsubitem}{(ScrolledWindow method)}
+\setindexsubitem{(ScrolledWindow method)}
\begin{funcdesc}{scrollbars}{\optional{wantx\, wanty}}
Create (or destroy) horizontal and vertical scrollbars. The arguments
DialogWindow objects have the following methods besides those of
\code{Window} objects:
-\renewcommand{\indexsubitem}{(DialogWindow method)}
+\setindexsubitem{(DialogWindow method)}
\begin{funcdesc}{open}{resid}
Create the dialog window, from the DLOG resource with id
The \var{MiniAEFrame} module defines the following classes:
-\renewcommand{\indexsubitem}{(in module MiniAEFrame)}
+\setindexsubitem{(in module MiniAEFrame)}
\begin{funcdesc}{AEServer}{}
A class that handles AppleEvent dispatch. Your application should
\subsection{AEServer Objects}
-\renewcommand{\indexsubitem}{(AEServer method)}
+\setindexsubitem{(AEServer method)}
\begin{funcdesc}{installaehandler}{classe\, type\, callback}
Installs an AppleEvent handler. \code{Classe} and \code{type} are the
% Redefine the ``indexsubitem'' macro to point to this module
% (alternatively, you can put this at the top of the file):
-\renewcommand{\indexsubitem}{(in module spam)}
+\setindexsubitem{(in module spam)}
% ---- 3.2. ----
% For each function, use a ``funcdesc'' block. This has exactly two
Example:
-\bcode\begin{verbatim}
+\begin{verbatim}
>>> import spam
>>> can = spam.open('/etc/passwd')
>>> can.empty()
>>> can.close()
-\end{verbatim}\ecode
+\end{verbatim}
%
% ==== 5. ====
% If your module defines new object types (for a built-in module) or
Spam objects (returned by \code{open()} above) have the following
methods.
-\renewcommand{\indexsubitem}{(spam method)}
+\setindexsubitem{(spam method)}
\begin{funcdesc}{empty}{}
Empty the can into the trash.