getopt -- Python library reference

getopt -- Python library reference
Prev: time (time.html)
Top: Top (top.html)
# 6.3. Standard Module `getopt`
This module helps scripts to parse the command line arguments in
`sys.argv`.
It uses the same conventions as the UNIX
`getopt()`
function (including the special meanings of arguments of the form
`-' and `--').
It defines the function
`getopt.getopt(args, options)`
and the exception
`getopt.error`.
The first argument to
`getopt()`
is the argument list passed to the script with its first element
chopped off (i.e.,
`sys.argv[1:]`).
The second argument is the string of option letters that the
script wants to recognize, with options that require an argument
followed by a colon (i.e., the same format that UNIX
`getopt()`
uses).
The return value consists of two elements: the first is a list of
option-and-value pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice of the
first argument).
Each option-and-value pair returned has the option as its first element,
prefixed with a hyphen (e.g.,
`'-x'`),
and the option argument as its second element, or an empty string if the
option has no argument.
The options occur in the list in the same order in which they were
found, thus allowing multiple occurrences.
Example:
The exception
`getopt.error = 'getopt error'`
is raised when an unrecognized option is found in the argument list or
when an option requiring an argument is given none.
The argument to the exception is a string indicating the cause of the
error.


gl -- Python library reference

gl -- Python library reference
Prev: fm (fm.html)
Top: Top (top.html)
# 16.8. Built-in Module `gl`
This module provides access to the Silicon Graphics
Graphics Library.
It is available only on Silicon Graphics machines.
Warning:
Some illegal calls to the GL library cause the Python interpreter to dump
core.
In particular, the use of most GL calls is unsafe before the first
window is opened.
The module is too large to document here in its entirety, but the
following should help you to get started.
The parameter conventions for the C functions are translated to Python as
follows:
- • All (short, long, unsigned) int values are represented by Python
integers.
• All float and double values are represented by Python floating point
numbers.
In most cases, Python integers are also allowed.
• All arrays are represented by one-dimensional Python lists.
In most cases, tuples are also allowed.
• All string and character arguments are represented by Python strings,
for instance,
`winopen('Hi There!')`
and
`rotate(900, 'z')`.
• All (short, long, unsigned) integer arguments or return values that are
only used to specify the length of an array argument are omitted.
For example, the C call
is translated to Python as
• Output arguments are omitted from the argument list; they are
transmitted as function return values instead.
If more than one value must be returned, the return value is a tuple.
If the C function has both a regular return value (that is not omitted
because of the previous rule) and an output argument, the return value
comes first in the tuple.
Examples: the C call
is translated to Python as
The following functions are non-standard or have special argument
conventions:
Here is a tiny but complete example GL program in Python:


GL and DEVICE -- Python library reference
Prev: gl (gl.html)
Top: Top (top.html)
# 16.9. Standard Modules `GL` and `DEVICE`
These modules define the constants used by the Silicon Graphics
Graphics Library
that C programmers find in the header files
<gl/gl.h>
and
<gl/device.h>.
Read the module source files for details.


gopherlib -- Python library reference

gopherlib -- Python library reference
Prev: ftplib (ftplib.html)
Top: Top (top.html)
# 11.5. Standard Module `gopherlib`
This module provides a minimal implementation of client side of the
the Gopher protocol.  It is used by the module `urllib` to handle
URLs that use the Gopher protocol.
The module defines the following functions:
Note that the data returned by the Gopher server can be of any type,
depending on the first character of the selector string. If the data
is text (first character of the selector is `0'), lines are
terminated by CRLF, and the data is terminated by a line consisting of
a single `.', and a leading `.' should be stripped from
lines that begin with `..'. Directory listings (first charactger
of the selector is `1') are transferred using the same protocol.


grp -- Python library reference

grp -- Python library reference
Prev: pwd (pwd.html)
Top: Top (top.html)
# 8.4. Built-in Module `grp`
This module provides access to the UNIX group database.
It is available on all UNIX versions.
Group database entries are reported as 4-tuples containing the
following items from the group database (see <grp.h>), in order:
`gr_name`,
`gr_passwd`,
`gr_gid`,
`gr_mem`.
The gid is an integer, name and password are strings, and the member
list is a list of strings.
(Note that most users are not explicitly listed as members of the
group they are in according to the password database.)
An exception is raised if the entry asked for cannot be found.
It defines the following items:


HotProfile Class -- Python library reference
Prev: OldProfile Class (oldprofile_class.html)
Top: Top (top.html)
## 10.8.2. HotProfile Class
This profiler is the fastest derived profile example.  It does not
calculate caller-callee relationships, and does not calculate
cumulative time under a function.  It only calculates time spent in a
function, so it runs very quickly (re: very low overhead).  In truth,
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.


How It Works -- Python library reference
Prev: Debugger Commands (debugger_commands.html)
Top: Top (top.html)
# 9.2. How It Works
Some changes were made to the interpreter:
- • sys.settrace(func) sets the global trace function
• there can also a local trace function (see later)
Trace functions have three arguments: (frame, event, arg)
A trace function should return a new trace function or None.
Class methods are accepted (and most useful!) as trace methods.
The events have the following meaning:
Note that as an exception is propagated down the chain of callers, an
`'exception'` event is generated at each level.
Stack frame objects have the following read-only attributes:
Code objects have the following read-only attributes:


htmllib -- Python library reference

htmllib -- Python library reference
Prev: urlparse (urlparse.html)
Top: Top (top.html)
# 11.8. Standard Module `htmllib`
This module defines a number of classes which can serve as a basis for
parsing text files formatted in HTML (HyperText Mark-up Language).
The classes are not directly concerned with I/O --- the have to be fed
their input in string form, and will make calls to methods of a
``formatter'' object in order to produce output.  The classes are
designed to be used as base classes for other classes in order to add
functionality, and allow most of their methods to be extended or
overridden.  In turn, the classes are derived from and extend the
class `SGMLParser` defined in module `sgmllib`.
The following is a summary of the interface defined by
`sgmllib.SGMLParser`:
- • The interface to feed data to an instance is through the `feed()`
method, which takes a string argument. This can be called with as
little or as much text at a time as desired;
`p.feed(a); p.feed(b)` has the same effect as `p.feed(a+b)`.
When the data contains complete
HTML elements, these are processed immediately; incomplete elements
are saved in a buffer. To force processing of all unprocessed data,
call the `close()` method.
Example: to parse the entire contents of a file, do*
`parser.feed(open(file).read()); parser.close()`.
• The interface to define semantics for HTML tags is very simple: derive
a class and define methods called `start_ tag ()`,
`end_ tag ()`, or `do_ tag ()`. The parser will
call these at appropriate moments: `start_ tag` or
`do_ tag` is called when an opening tag of the form
`< tag ...>` is encountered; `end_ tag` is called
when a closing tag of the form `< tag >` is encountered. If
an opening tag requires a corresponding closing tag, like `<H1>`
... `</H1>`, the class should define the `start_ tag`
method; if a tag requires no closing tag, like `<P>`, the class
should define the `do_ tag` method.
The module defines the following classes:
Instances of `CollectingParser` (and thus also instances of
`FormattingParser` and `AnchoringParser`) have the following
instance variables:
The `anchors`, `anchornames` and `anchortypes` lists
are ``parallel arrays'': items in these lists with the same index
pertain to the same anchor. Missing attributes default to the empty
string. Anchors with neither a `HREF` nor a `NAME`
attribute are not entered in these lists at all.
The module also defines a number of style sheet classes. These should
never be instantiated --- their class variables are the only behavior
required. Note that style sheets are specifically designed for a
particular formatter implementation. The currently defined style
sheets are:
Style sheets have the following class variables:
Although no documented implementation of a formatter exists, the
`FormattingParser` class assumes that formatters have a
certain interface. This interface requires the following methods:
A sample formatter implementation can be found in the module
`fmt`, which in turn uses the module `Para`. These modules are
not intended as standard library modules; they are available as an
example of how to write a formatter.


HTTP Example -- Python library reference
Prev: HTTP Objects (http_objects.html)
Top: Top (top.html)
## 11.3.2. Example
Here is an example session:


HTTP Objects -- Python library reference
Prev: httplib (httplib.html)
Top: Top (top.html)
## 11.3.1. HTTP Objects
`HTTP` instances have the following methods:


httplib -- Python library reference

httplib -- Python library reference
Prev: urllib (urllib.html)
Top: Top (top.html)
# 11.3. Standard Module `httplib`
This module defines a class which implements the client side of the
HTTP protocol.  It is normally not used directly --- the module
`urllib` uses it to handle URLs that use HTTP.
The module defines one class, `HTTP`.  An `HTTP` instance
represents one transaction with an HTTP server.  It should be
instantiated passing it a host and optional port number.  If no port
number is passed, the port is extracted from the host string if it has
the form `host:port`, else the default HTTP port (80) is used.
If no host is passed, no connection is made, and the `connect`
method should be used to connect to a server.  For example, the
following calls all create instances that connect to the server at the
same host and port:
Once an `HTTP` instance has been connected to an HTTP server, it
should be used as follows:
- 1. 1. Make exactly one call to the `putrequest()` method.
2. 2. Make zero or more calls to the `putheader()` method.
3. 3. Call the `endheaders()` method (this can be omitted if
step 4 makes no calls).
4. 4. Optional calls to the `send()` method.
5. 5. Call the `getreply()` method.
6. 6. Call the `getfile()` method and read the data off the
file object that it returns.
## Menu


imageop -- Python library reference

imageop -- Python library reference
Prev: audioop (audioop.html)
Top: Top (top.html)
# 12.2. Built-in Module `imageop`
The `imageop` module contains some useful operations on images.
It operates on images consisting of 8 or 32 bit pixels
stored in Python strings.  This is the same format as used
by `gl.lrectwrite` and the `imgfile` module.
The module defines the following variables and functions:


imgfile -- Python library reference

imgfile -- Python library reference
Prev: GL and DEVICE (gl_and_device.html)
Top: Top (top.html)
# 16.10. Built-in Module `imgfile`
The imgfile module allows python programs to access SGI imglib image
files (also known as .rgb files).  The module is far from
complete, but is provided anyway since the functionality that there is
is enough in some cases.  Currently, colormap files are not supported.
The module defines the following variables and functions:


imp -- Python library reference

imp -- Python library reference
Prev: marshal (marshal.html)
Top: Top (top.html)
# 3.8. Built-in Module `imp`
This module provides an interface to the mechanisms used to implement
the `import` statement.  It defines the following constants and
functions:
The following constants with integer values, defined in the module,
are used to indicate the search result of `imp.find_module`.
## Menu


Instant Users Manual -- Python library reference
Prev: Profiler Changes (profiler_changes.html)
Top: Top (top.html)
# 10.3. Instant Users Manual
This section is provided for users that ``don't want to read the
manual.'' It provides a very brief overview, and allows a user to
rapidly perform profiling on an existing application.
To profile an application with a main entry point of `foo()', you
would add the following to your module:
The above action would cause `foo()' to be run, and a series of
informative lines (the profile) to be printed. The above approach is
most useful when working with the interpreter. If you would like to
save the results of a profile into a file for later examination, you
can supply a file name as the second argument to the `run()`
function:
When you wish to review the profile, you should use the methods in the
`pstats` module. Typically you would load the statistics data as
follows:
The class `Stats` (the above code just created an instance of
this class) has a variety of methods for manipulating and printing the
data that was just read into `p'. When you ran
`profile.run()` above, what was printed was the result of three
method calls:
The first method removed the extraneous path from all the module
names. The second method sorted all the entries according to the
standard module/line/name string that is printed (this is to comply
with the semantics of the old profiler). The third method printed out
all the statistics. You might try the following sort calls:
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:
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
algorithms are taking time, the above line is what you would use.
If you were looking to see what functions were looping a lot, and
taking a lot of time, you would do:
to sort according to time spent within each function, and then print
the statistics for the top ten functions.
You might also try:
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 `__init__` in them). As one final example, you could try:
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.
To be specific, the list is first culled down to 50% (re: `.5')
of its original size, then only lines containing `init` are
maintained, and that sub-sub-list is printed.
If you wondered what functions called the above functions, you could
now (`p' is still sorted according to the last criteria) do:
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:


Internal Objects -- Python library reference
Prev: File Objects (file_objects.html)
Top: Top (top.html)
### 2.1.7.9. Internal Objects
(See the Python Reference Manual for these.)


Internet and WWW -- Python library reference
Prev: The Python Profiler (the_python_profiler.html)
Top: Top (top.html)
# 11. Internet and WWW Services
The modules described in this chapter provide various services to
World-Wide Web (WWW) clients and/or services, and a few modules
related to news and email.  They are all implemented in Python.  Some
of these modules require the presence of the system-dependent module
`sockets`, which is currently only fully supported on Unix and
Windows NT.  Here is an overview:
## Menu


Introduction -- Python library reference
Prev: Top (top.html)
Top: Top (top.html)
# 1. Introduction
The ``Python library'' contains several different kinds of components.
It contains data types that would normally be considered part of the
``core'' of a language, such as numbers and lists. For these types,
the Python language core defines the form of literals and places some
constraints on their semantics, but does not fully define the
semantics. (On the other hand, the language core does define
syntactic properties like the spelling and priorities of operators.)
The library also contains built-in functions and exceptions ---
objects that can be used by all Python code without the need of an
`import` statement. Some of these are defined by the core
language, but many are not essential for the core semantics and are
only described here.
The bulk of the library, however, consists of a collection of modules.
There are many ways to dissect this collection. Some modules are
written in C and built in to the Python interpreter; others are
written in Python and imported in source form. Some modules provide
interfaces that are highly specific to Python, like printing a stack
trace; some provide interfaces that are specific to particular
operating systems, like socket I/O; others provide interfaces that are
specific to a particular application domain, like the World-Wide Web.
Some modules are avaiable in all versions and ports of Python; others
are only available when the underlying system supports or requires
them; yet others are available only when a particular configuration
option was chosen at the time when Python was compiled and installed.
This manual is organized ``from the inside out'': it first describes
the built-in data types, then the built-in functions and exceptions,
and finally the modules, grouped in chapters of related modules. The
ordering of the chapters as well as the ordering of the modules within
each chapter is roughly from most relevant to least important.
This means that if you start reading this manual from the start, and
skip to the next chapter when you get bored, you will get a reasonable
overview of the available modules and application areas that are
supported by the Python library. Of course, you don't have to
read it like a novel --- you can also browse the table of contents (in
front of the manual), or look for a specific function, module or term
in the index (in the back). And finally, if you enjoy learning about
random subjects, you choose a random page number (see module
`rand`) and read a section or two.
Let the show begin!


jpeg -- Python library reference

jpeg -- Python library reference
Prev: aifc (aifc.html)
Top: Top (top.html)
# 12.4. Built-in Module `jpeg`
The module `jpeg` provides access to the jpeg compressor and
decompressor written by the Independent JPEG Group. JPEG is a (draft?)
standard for compressing pictures.  For details on jpeg or the
Independent JPEG Group software refer to the JPEG standard or the
documentation provided with the software.
The `jpeg` module defines these functions:
Compress and uncompress raise the error `jpeg.error` in case of errors.


Limitations -- Python library reference

Limitations -- Python library reference
Prev: Reference Manual (reference_manual.html)
Top: Top (top.html)
# 10.6. Limitations
There are two fundamental limitations on this profiler.  The first is
that it relies on the Python interpreter to dispatch call,
return, and exception events.  Compiled C code does not
get interpreted, and hence is ``invisible'' to the profiler.  All time
spent in C code (including builtin functions) will be charged to the
Python function that invoked the C code.  If the C code calls out
to some native Python code, then those calls will be profiled
properly.
The second limitation has to do with accuracy of timing information.
There is a fundamental problem with deterministic profilers involving
accuracy. The most obvious restriction is that the underlying ``clock''
is only ticking at a rate (typically) of about .001 seconds. Hence no
measurements will be more accurate that that underlying clock. If
enough measurements are taken, then the ``error'' will tend to average
out. Unfortunately, removing this first error induces a second source
of error...
The second problem is that it ``takes a while'' from when an event is
dispatched until the profiler's call to get the time actually
gets the state of the clock. Similarly, there is a certain lag
when exiting the profiler event handler from the time that the clock's
value was obtained (and then squirreled away), until the user's code
is once again executing. As a result, functions that are called many
times, or call many functions, will typically accumulate this error.
The error that accumulates in this fashion is typically less than the
accuracy of the clock (i.e., less than one clock tick), but it
can accumulate and become very significant. This profiler
provides a means of calibrating itself for a given platform so that
this error can be probabilistically (i.e., on the average) removed.
After the profiler is calibrated, it will be more accurate (in a least
square sense), but it will sometimes produce negative numbers (when
call counts are exceptionally low, and the gods of probability work
against you :-). ) Do NOT be alarmed by negative numbers in
the profile. They should only appear if you have calibrated
your profiler, and the results are actually better than without
calibration.


mac -- Python library reference

mac -- Python library reference
Prev: Macintosh Specific Services (macintosh_specific_services.html)
Top: Top (top.html)
# 14.1. Built-in Module `mac`
This module provides a subset of the operating system dependent
functionality provided by the optional built-in module `posix`.
It is best accessed through the more portable standard module
`os`.
The following functions are available in this module:
`chdir`,
`getcwd`,
`listdir`,
`mkdir`,
`rename`,
`rmdir`,
`stat`,
`sync`,
`unlink`,
as well as the exception `error`.


macconsole -- Python library reference

macconsole -- Python library reference
Prev: ctb (ctb.html)
Top: Top (top.html)
# 14.4. Built-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
Think console package, with which basic text windows can be created.
## Menu


macconsole options object -- Python library reference
Prev: macconsole (macconsole.html)
Top: Top (top.html)
## 14.4.1. macconsole options object
These options are examined when a window is created:


macdnr -- Python library reference

macdnr -- Python library reference
Prev: macconsole (macconsole.html)
Top: Top (top.html)
# 14.5. Built-in Module `macdnr`
This module provides an interface to the Macintosh Domain Name
Resolver.  It is usually used in conjunction with the mactcp
module, to map hostnames to IP-addresses.  It may not be available in
all Mac Python versions.
The `macdnr` module defines the following functions:
## Menu


macfs -- Python library reference

macfs -- Python library reference
Prev: macdnr (macdnr.html)
Top: Top (top.html)
# 14.6. Built-in Module `macfs`
This module provides access to macintosh FSSpec handling, the Alias
Manager, finder aliases and the Standard File package.
Whenever a function or method expects a file argument, this
argument can be one of three things: (1) a full or partial Macintosh
pathname, (2) an FSSpec object or (3) a 3-tuple `(wdRefNum,
parID, name)` as described in Inside Mac VI.
and the standard file package can also be found there.
## Menu


Macintosh Specific Services -- Python library reference
Prev: Cryptographic Services (cryptographic_services.html)
Top: Top (top.html)
# 14. Macintosh Specific Services
The modules in this chapter are available on the Apple Macintosh only.
## Menu


macpath -- Python library reference

macpath -- Python library reference
Prev: mac (mac.html)
Top: Top (top.html)
# 14.2. Standard Module `macpath`
This module provides a subset of the pathname manipulation functions
available from the optional standard module `posixpath`.  It is
best accessed through the more portable standard module `os`, as
`os.path`.
The following functions are available in this module:
`normcase`,
`isabs`,
`join`,
`split`,
`isdir`,
`isfile`,
`exists`.


macspeech -- Python library reference

macspeech -- Python library reference
Prev: mactcp (mactcp.html)
Top: Top (top.html)
# 14.8. Built-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
the speech manager extension (version 1 and 2 have been tested) in
your `Extensions` folder for this to work. The module does not
provide full access to all features of the Speech Manager yet.  It may
not be available in all Mac Python versions.
## Menu


mactcp -- Python library reference

mactcp -- Python library reference
Prev: macfs (macfs.html)
Top: Top (top.html)
# 14.7. Built-in Module `mactcp`
This module provides an interface to the Macintosh TCP/IP driver
MacTCP.`macdnr` which provides an
interface to the name-server (allowing you to translate hostnames to
ip-addresses), a module `MACTCP` which has symbolic names for
constants constants used by MacTCP and a wrapper module `socket`
which mimics the UNIX socket interface (as far as possible).  It may
not be available in all Mac Python versions.
A complete description of the MacTCP interface can be found in the
Apple MacTCP API documentation.
## Menu


Mapping Types -- Python library reference
Prev: Sequence Types (sequence_types.html)
Top: Top (top.html)
## 2.1.6. Mapping Types
A mapping object maps values of one type (the key type) to
arbitrary objects.  Mappings are mutable objects.  There is currently
only one standard mapping type, the dictionary.  A dictionary's keys are
almost arbitrary values.  The only types of values not acceptable as
keys are values containing lists or dictionaries or other mutable
types that are compared by value rather than by object identity.
Numeric types used for keys obey the normal rules for numeric
comparison: if two numbers compare equal (e.g. 1 and 1.0) then they
can be used interchangeably to index the same dictionary entry.
Dictionaries are created by placing a comma-separated list of
`key :,varvalue` pairs within braces, for example:
`{'jack':,4098, 'sjoerd':,4127}` or
`{4098:,'jack', 4127:,'sjoerd'}`.
The following operations are defined on mappings (where a is a
mapping, k is a key and x is an arbitrary object):
Notes:


marshal -- Python library reference

marshal -- Python library reference
Prev: copy (copy.html)
Top: Top (top.html)
# 3.7. Built-in Module `marshal`
This module contains functions that can read and write Python
values in a binary format.  The format is specific to Python, but
independent of machine architecture issues (e.g., you can write a
Python value to a file on a PC, transport the file to a Sun, and read
it back there).  Details of the format are undocumented on purpose;
it may change between Python versions (although it rarely does).(1) (#footnotetext1)
This is not a general ``persistency'' module. For general persistency
and transfer of Python objects through RPC calls, see the modules
`pickle` and `shelve`. The `marshal` module exists
mainly to support reading and writing the ``pseudo-compiled'' code for
Python modules of `.pyc' files.
Not all Python object types are supported; in general, only objects
whose value is independent from a particular invocation of Python can
be written and read by this module. The following types are supported:
`None`, integers, long integers, floating point numbers,
strings, tuples, lists, dictionaries, and code objects, where it
should be understood that tuples, lists and dictionaries are only
supported as long as the values contained therein are themselves
supported; and recursive lists and dictionaries should not be written
(they will cause infinite loops).
Caveat: On machines where C's `long int` type has more than
32 bits (such as the DEC Alpha or the HP Precision Architecture), it
is possible to create plain Python integers that are longer than 32
bits. Since the current `marshal` module uses 32 bits to
transfer plain Python integers, such values are silently truncated.
This particularly affects the use of very long integer literals in
Python modules --- these will be accepted by the parser on such
machines, but will be silently be truncated when the module is read
from the `.pyc` instead.(2) (#footnotetext2)
There are functions that read/write files as well as functions
operating on strings.
The module defines these functions:
## ---------- Footnotes ----------
(1) (#footnoteref1)
The name of this module stems from a bit of terminology used
by the designers of Modula-3 (amongst others), who use the term
``marshalling'' for shipping of data around in a self-contained form.
Strictly speaking, ``to marshal'' means to convert some data from
internal to external form (in an RPC buffer for instance) and
``unmarshalling'' for the reverse process.
(2) (#footnoteref2)
A solution would be to refuse such literals in the parser,
since they are inherently non-portable. Another solution would be to
let the `marshal` module raise an exception when an integer value
would be truncated. At least one of these solutions will be
implemented in a future version.


math -- Python library reference

math -- Python library reference
Prev: Miscellaneous Services (miscellaneous_services.html)
Top: Top (top.html)
# 5.1. Built-in Module `math`
This module is always available.
It provides access to the mathematical functions defined by the C
standard.
They are:
Note that `frexp` and `modf` have a different call/return
pattern than their C equivalents: they take a single argument and
return a pair of values, rather than returning their second return
value through an `output parameter' (there is no such thing in Python).
The `hypot` function, which is not standard C, is not available
on all platforms.
The module also defines two mathematical constants:


md5 -- Python library reference

md5 -- Python library reference
Prev: Cryptographic Services (cryptographic_services.html)
Top: Top (top.html)
# 13.1. Built-in Module `md5`
This module implements the interface to RSA's MD5 message digest
algorithm (see also Internet RFC 1321).  Its use is quite
straightforward: use the `md5.new()` to create an md5 object.
You can now feed this object with arbitrary strings using the
`update()` method, and at any point you can ask it for the
digest (a strong kind of 128-bit checksum,
a.k.a. ``fingerprint'') of the contatenation of the strings fed to it
so far using the `digest()` method.
For example, to obtain the digest of the string `"Nobody inspects
the spammish repetition"`:
More condensed:
An md5 object has the following methods:


Menu Objects -- Python library reference
Prev: Drawing Objects (drawing_objects.html)
Top: Top (top.html)
## 15.1.4. Menu Objects
A menu object represents a menu.
The menu is destroyed when the menu object is deleted.
The following methods are defined:


Message Objects -- Python library reference
Prev: rfc822 (rfc822.html)
Top: Top (top.html)
## 11.10.1. Message Objects
A `Message` instance has the following methods:
`Message` instances also support a read-only mapping interface.
In particular: `m[name]` is the same as `m.getheader(name)`;
and `len(m)`, `m.has_key(name)`, `m.keys()`,
`m.values()` and `m.items()` act as expected (and
consistently).
Finally, `Message` instances have two public instance variables:


Methods -- Python library reference

Methods -- Python library reference
Prev: Functions (functions.html)
Top: Top (top.html)
### 2.1.7.4. Methods
Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods (such as `append()` on
lists) and class instance methods.  Built-in methods are described
with the types that support them.
The implementation adds two special read-only attributes to class
instance methods: `m .im_self` is the object whose method this
is, and `m .im_func` is the function implementing the method.
Calling `m ( arg-1 , arg-2 , ... , arg-n )` is completely equivalent to calling
`m .im_func( m .im_self, arg-1 , arg-2 , ... , arg-n )`.
(See the Python Reference Manual for more info.)


mimetools -- Python library reference

mimetools -- Python library reference
Prev: rfc822 (rfc822.html)
Top: Top (top.html)
# 11.11. Standard Module `mimetools`
This module defines a subclass of the class `rfc822.Message` and
a number of utility functions that are useful for the manipulation for
MIME style multipart or encoded message.
It defines the following items:
## Menu


mimetools.Message Methods -- Python library reference
Prev: mimetools (mimetools.html)
Top: Top (top.html)
## 11.11.1. Additional Methods of Message objects
The `mimetools.Message` class defines the following methods in
addition to the `rfc822.Message` class:


Miscellaneous Services -- Python library reference
Prev: String Services (string_services.html)
Top: Top (top.html)
# 5. Miscellaneous Services
The modules described in this chapter provide miscellaneous services
that are available in all Python versions.  Here's an overview:
## Menu


Module Index -- Python library reference
Prev: Variable Index (variable_index.html)
Top: Top (top.html)
# Module Index


Modules -- Python library reference

Modules -- Python library reference
Prev: Other Built-in Types (other_built-in_types.html)
Top: Top (top.html)
### 2.1.7.1. Modules
The only special operation on a module is attribute access:
`m . name`, where m is a module and name accesses
a name defined in m's symbol table.  Module attributes can be
assigned to.  (Note that the `import` statement is not, strictly
spoken, an operation on a module object; `import foo` does not
require a module object named foo to exist, rather it requires
an (external) definition for a module named foo
somewhere.)
A special member of every module is `__dict__`.
This is the dictionary containing the module's symbol table.
Modifying this dictionary will actually change the module's symbol
table, but direct assignment to the `__dict__` attribute is not
possible (i.e., you can write `m .__dict__['a'] = 1`, which
defines `m .a` to be `1`, but you can't write `m .__dict__ = {}`.
Modules are written like this: `<module 'sys'>`.


More String Operations -- Python library reference
Prev: Sequence Types (sequence_types.html)
Top: Top (top.html)
### 2.1.5.1. More String Operations
String objects have one unique built-in operation: the `%`
operator (modulo) with a string left argument interprets this string
as a C sprintf format string to be applied to the right argument, and
returns the string resulting from this formatting operation.
The right argument should be a tuple with one item for each argument
required by the format string; if the string requires a single
argument, the right argument may also be a single non-tuple object.(1) (#footnotetext1)
The following format characters are understood:
%, c, s, i, d, u, o, x, X, e, E, f, g, G.
Width and precision may be a * to specify that an integer argument
specifies the actual width or precision. The flag characters -, +,
blank, # and 0 are understood. The size specifiers h, l or L may be
present but are ignored. The `%s` conversion takes any Python
object and converts it to a string using `str()` before
formatting it. The ANSI features `%p` and `%n`
are not supported. Since Python strings have an explicit length,
`%s` conversions don't assume that `'\0'` is the end of
the string.
For safety reasons, floating point precisions are clipped to 50;
`%f` conversions for numbers whose absolute value is over 1e25
are replaced by `%g` conversions.(2) (#footnotetext2)
All other errors raise exceptions.
If the right argument is a dictionary (or any kind of mapping), then
the formats in the string must have a parenthesized key into that
dictionary inserted immediately after the `%` character, and
each format formats the corresponding entry from the mapping. E.g.
In this case no * specifiers may occur in a format (since they a
require sequential parameter list).
Additional string operations are defined in standard module
`string` and in built-in module `regex`.
## ---------- Footnotes ----------
(1) (#footnoteref1)
A tuple object in this case should be a singleton.
(2) (#footnoteref2)
These numbers are fairly arbitrary. They are intended to
avoid printing endless strings of meaningless digits without hampering
correct use and without having to know the exact precision of floating
point values on a particular machine.


mpz -- Python library reference

mpz -- Python library reference
Prev: md5 (md5.html)
Top: Top (top.html)
# 13.2. Built-in Module `mpz`
This module implements the interface to part of the GNU MP library.
This library contains arbitrary precision integer and rational number
arithmetic routines. Only the interfaces to the integer
(`mpz_...') routines are provided. If not stated
otherwise, the description in the GNU MP documentation can be applied.
In general, mpz-numbers can be used just like other standard
Python numbers, e.g. you can use the built-in operators like `+`,
`*`, etc., as well as the standard built-in functions like
`abs`, `int`, ..., `divmod`, `pow`.
Please note: the bitwise-xor operation has been implemented as
a bunch of ands, inverts and ors, because the library
lacks an `mpz_xor` function, and I didn't need one.
You create an mpz-number by calling the function called `mpz` (see
below for an exact description). An mpz-number is printed like this:
`mpz( value )`.
A number of extra functions are defined in this module. Non
mpz-arguments are converted to mpz-values first, and the functions
return mpz-numbers.
An mpz-number has one method:


Multimedia Services -- Python library reference
Prev: Internet and WWW (internet_and_www.html)
Top: Top (top.html)
# 12. Multimedia Services
The modules described in this chapter implement various algorithms or
interfaces that are mainly useful for multimedia applications.  They
are available at the discretion of the installation.  Here's an overview:
## Menu


Mutable Sequence Types -- Python library reference
Prev: More String Operations (more_string_operations.html)
Top: Top (top.html)
### 2.1.5.2. Mutable Sequence Types
List objects support additional operations that allow in-place
modification of the object.
These operations would be supported by other mutable sequence types
(when added to the language) as well.
Strings and tuples are immutable sequence types and such objects cannot
be modified once created.
The following operations are defined on mutable sequence types (where
x is an arbitrary object):
 Notes:


NNTP Objects -- Python library reference
Prev: nntplib (nntplib.html)
Top: Top (top.html)
## 11.6.1. NNTP Objects
NNTP instances have the following methods.  The response that is
returned as the first item in the return tuple of almost all methods
is the server's response: a string beginning with a three-digit code.
If the server's response indicates an error, the method raises one of
the above exceptions.


nntplib -- Python library reference

nntplib -- Python library reference
Prev: gopherlib (gopherlib.html)
Top: Top (top.html)
# 11.6. Standard Module `nntplib`
This module defines the class `NNTP` which implements the client
side of the NNTP protocol.  It can be used to implement a news reader
or poster, or automated news processors.  For more information on NNTP
(Network News Transfer Protocol), see Internet RFC 977.
Here are two small examples of how it can be used. To list some
statistics about a newsgroup and print the subjects of the last 10
articles:
@small{
}
To post an article from a file (this assumes that the article has
valid headers):
The module itself defines the following items:
## Menu


Numeric Types -- Python library reference
Prev: Comparisons (comparisons.html)
Top: Top (top.html)
## 2.1.4. Numeric Types
There are three numeric types: plain integers, long integers, and
floating point numbers.  Plain integers (also just called integers)
are implemented using `long` in C, which gives them at least 32
bits of precision.  Long integers have unlimited precision.  Floating
point numbers are implemented using `double` in C.  All bets on
their precision are off unless you happen to know the machine you are
working with.
Numbers are created by numeric literals or as the result of built-in
functions and operators.  Unadorned integer literals (including hex
and octal numbers) yield plain integers.  Integer literals with an `L'
or `l' suffix yield long integers
(`L' is preferred because `1l` looks too much like eleven!).
Numeric literals containing a decimal point or an exponent sign yield
floating point numbers.
Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
``smaller'' type is converted to that of the other, where plain
integer is smaller than long integer is smaller than floating point.
Comparisons between numbers of mixed type use the same rule.(1) (#footnotetext1)
The functions `int()`, `long()` and `float()` can be used
to coerce numbers to a specific type.
All numeric types support the following operations, sorted by
ascending priority (operations in the same box have the same
priority; all numeric operations have a higher priority than
comparison operations):
Notes:
## Menu
## ---------- Footnotes ----------
(1) (#footnoteref1)
As a consequence, the list `[1, 2]` is considered equal
to `[1.0, 2.0]`, and similar for tuples.


OldProfile Class -- Python library reference
Prev: Profiler Extensions (profiler_extensions.html)
Top: Top (top.html)
## 10.8.1. OldProfile Class
The following derived profiler simulates the old style profiler,
providing errant results on recursive functions. The reason for the
usefulness of this profiler is that it runs faster (i.e., less
overhead) than the old profiler.  It still creates all the caller
stats, and is quite useful when there is no recursion in the
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.


Optional Operating System Services -- Python library reference
Prev: Generic Operating System Services (generic_operating_system_services.html)
Top: Top (top.html)
# 7. Optional Operating System Services
The modules described in this chapter provide interfaces to operating
system features that are available on selected operating systems only.
The interfaces are generally modelled after the UNIX or C
interfaces but they are available on some other systems as well
(e.g. Windows or NT).  Here's an overview:
## Menu


os -- Python library reference

os -- Python library reference
Prev: Generic Operating System Services (generic_operating_system_services.html)
Top: Top (top.html)
# 6.1. Standard Module `os`
This module provides a more portable way of using operating system
(OS) dependent functionality than importing an OS dependent built-in
module like `posix`.
When the optional built-in module `posix` is available, this
module exports the same functions and data as `posix`; otherwise,
it searches for an OS dependent built-in module like `mac` and
exports the same functions and data as found there. The design of all
Python's built-in OS dependent modules is such that as long as the same
functionality is available, it uses the same interface; e.g., the
function `os.stat( file )` returns stat info about a file in a
format compatible with the POSIX interface.
Extensions peculiar to a particular OS are also available through the
`os` module, but using them is of course a threat to portability!
Note that after the first time `os` is imported, there is no
performance penalty in using functions from `os` instead of
directly from the OS dependent built-in module, so there should be
no reason not to use `os`!
In addition to whatever the correct OS dependent module exports, the
following variables and functions are always exported by `os`:
(The functions `os.execv()` and `execve()` are not
documented here, since they are implemented by the OS dependent
module. If the OS dependent module doesn't define either of these,
the functions that rely on it will raise an exception. They are
documented in the section on module `posix`, together with all
other functions that `os` imports from the OS dependent module.)


Other Built-in Types -- Python library reference
Prev: Mapping Types (mapping_types.html)
Top: Top (top.html)
## 2.1.7. Other Built-in Types
The interpreter supports several other kinds of objects.
Most of these support only one or two operations.
## Menu


pickle -- Python library reference

pickle -- Python library reference
Prev: traceback (traceback.html)
Top: Top (top.html)
# 3.4. Standard Module `pickle`
The `pickle` module implements a basic but powerful algorithm for
``pickling'' (a.k.a. serializing, marshalling or flattening) nearly
arbitrary Python objects.  This is the act of converting objects to a
stream of bytes (and back: ``unpickling'').
This is a more primitive notion than
persistency --- although `pickle` reads and writes file objects,
it does not handle the issue of naming persistent objects, nor the
(even more complicated) area of concurrent access to persistent
objects.  The `pickle` module can transform a complex object into
a byte stream and it can transform the byte stream into an object with
the same internal structure.  The most obvious thing to do with these
byte streams is to write them onto a file, but it is also conceivable
to send them across a network or store them in a database.  The module
`shelve` provides a simple interface to pickle and unpickle
objects on ``dbm''-style database files.
Unlike the built-in module `marshal`, `pickle` handles the
following correctly:
- • recursive objects (objects containing references to themselves)
  • object sharing (references to the same object in different places)
  • user-defined classes and their instances
The data format used by `pickle` is Python-specific.  This has
the advantage that there are no restrictions imposed by external
standards such as CORBA (which probably can't represent pointer
sharing or recursive objects); however it means that non-Python
programs may not be able to reconstruct pickled Python objects.
The `pickle` data format uses a printable ASCII representation.
This is slightly more voluminous than a binary representation.
However, small integers actually take less space when
represented as minimal-size decimal strings than when represented as
32-bit binary numbers, and strings are only much longer if they
contain many control characters or 8-bit characters. The big
advantage of using printable ASCII (and of some other characteristics
of `pickle`'s representation) is that for debugging or recovery
purposes it is possible for a human to read the pickled file with a
standard text editor. (I could have gone a step further and used a
notation like S-expressions, but the parser
(currently written in Python) would have been
considerably more complicated and slower, and the files would probably
have become much larger.)
The `pickle` module doesn't handle code objects, which the
`marshal` module does. I suppose `pickle` could, and maybe
it should, but there's probably no great need for it right now (as
long as `marshal` continues to be used for reading and writing
code objects), and at least this avoids the possibility of smuggling
Trojan horses into a program.
For the benefit of persistency modules written using `pickle`, it
supports the notion of a reference to an object outside the pickled
data stream. Such objects are referenced by a name, which is an
arbitrary string of printable ASCII characters. The resolution of
such names is not defined by the `pickle` module --- the
persistent object module will have to implement a method
`persistent_load`. To write references to persistent objects,
the persistent module must define a method `persistent_id` which
returns either `None` or the persistent ID of the object.
There are some restrictions on the pickling of class instances.
First of all, the class must be defined at the top level in a module.
Next, it must normally be possible to create class instances by
calling the class without arguments. If this is undesirable, the
class can define a method `__getinitargs__()`, which should
return a tuple containing the arguments to be passed to the
class constructor (`__init__()`).
Classes can further influence how their instances are pickled --- if the class
defines the method `__getstate__()`, it is called and the return
state is pickled as the contents for the instance, and if the class
defines the method `__setstate__()`, it is called with the
unpickled state. (Note that these methods can also be used to
implement copying class instances.) If there is no
`__getstate__()` method, the instance's `__dict__` is
pickled. If there is no `__setstate__()` method, the pickled
object must be a dictionary and its items are assigned to the new
instance's dictionary. (If a class defines both `__getstate__()`
and `__setstate__()`, the state object needn't be a dictionary
--- these methods can do what they want.) This protocol is also used
by the shallow and deep copying operations defined in the `copy`
module.
Note that when class instances are pickled, their class's code and
data are not pickled along with them. Only the instance data are
pickled. This is done on purpose, so you can fix bugs in a class or
add methods and still load objects that were created with an earlier
version of the class. If you plan to have long-lived objects that
will see many versions of a class, it may be worthwhile to put a version
number in the objects so that suitable conversions can be made by the
class's `__setstate__()` method.
When a class itself is pickled, only its name is pickled --- the class
definition is not pickled, but re-imported by the unpickling process.
Therefore, the restriction that the class must be defined at the top
level in a module applies to pickled classes as well.
The interface can be summarized as follows.
To pickle an object `x` onto a file `f`, open for writing:
A shorthand for this is:
To unpickle an object `x` from a file `f`, open for reading:
A shorthand is:
The `Pickler` class only calls the method `f.write` with a
string argument. The `Unpickler` calls the methods `f.read`
(with an integer argument) and `f.readline` (without argument),
both returning a string. It is explicitly allowed to pass non-file
objects here, as long as they have the right methods.
The following types can be pickled:
- • `None`
• integers, long integers, floating point numbers
• strings
• tuples, lists and dictionaries containing only picklable objects
• classes that are defined at the top level in a module
• instances of such classes whose `__dict__` or
`__setstate__()` is picklable
Attempts to pickle unpicklable objects will raise the
`PicklingError` exception; when this happens, an unspecified
number of bytes may have been written to the file.
It is possible to make multiple calls to the `dump()` method of
the same `Pickler` instance. These must then be matched to the
same number of calls to the `load()` instance of the
corresponding `Unpickler` instance. If the same object is
pickled by multiple `dump()` calls, the `load()` will all
yield references to the same object. Warning: this is intended
for pickling multiple objects without intervening modifications to the
objects or their parts. If you modify an object and then pickle it
again using the same `Pickler` instance, the object is not
pickled again --- a reference to it is pickled and the
`Unpickler` will return the old value, not the modified one.
(There are two problems here: (a) detecting changes, and (b)
marshalling a minimal set of changes. I have no answers. Garbage
Collection may also become a problem here.)
Apart from the `Pickler` and `Unpickler` classes, the
module defines the following functions, and an exception:


Port Objects -- Python library reference
Prev: Configuration Objects (configuration_objects.html)
Top: Top (top.html)
## 16.1.2. Port Objects
Port objects (returned by `al.openport()` have the following
methods:


posix -- Python library reference

posix -- Python library reference
Prev: UNIX Specific Services (unix_specific_services.html)
Top: Top (top.html)
# 8.1. Built-in Module `posix`
This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly disguised
UNIX interface).
Do not import this module directly. Instead, import the
module `os`, which provides a portable version of this
interface. On UNIX, the `os` module provides a superset of
the `posix` interface. On non-UNIX operating systems the
`posix` module is not available, but a subset is always available
through the `os` interface. Once `os` is imported, there is
no performance penalty in using it instead of
`posix`.
The descriptions below are very terse; refer to the
corresponding UNIX manual entry for more information. Arguments
called path refer to a pathname given as a string.
Errors are reported as exceptions; the usual exceptions are given
for type errors, while errors reported by the system calls raise
`posix.error`, described below.
Module `posix` defines the following data items:
It defines the following functions and constants:
## ---------- Footnotes ----------
(1) (#footnoteref1)
The problem with automatically passing on `environ` is
that there is no portable way of changing the environment.


posixfile -- Python library reference

posixfile -- Python library reference
Prev: fcntl (fcntl.html)
Top: Top (top.html)
# 8.10. Standard Module `posixfile`
This module implements some additional functionality over the built-in
file objects.  In particular, it implements file locking, control over
the file flags, and an easy interface to duplicate the file object.
The module defines a new file object, the posixfile object.  It
has all the standard file object methods and adds the methods
described below.  This module only works for certain flavors of
UNIX, since it uses `fcntl()` for file locking.
To instantiate a posixfile object, use the `open()` function in
the posixfile module. The resulting object looks and feels roughly
the same as a standard file object.
The posixfile module defines the following constants:
The posixfile module defines the following functions:
The posixfile object defines the following additional methods:
All methods return `IOError` when the request fails.
Format characters for the `lock()` method have the following meaning:
In addition the following modifiers can be added to the format:
Note:
(1) The lock returned is in the format `(mode, len, start,
whence, pid)` where mode is a character representing the type of lock
('r' or 'w'). This modifier prevents a request from being granted; it
is for query purposes only.
Format character for the `flags()` method have the following meaning:
In addition the following modifiers can be added to the format:
Note:
(1) The `!` and `=` modifiers are mutually exclusive.
(2) This string represents the flags after they may have been altered
by the same call.
Examples:


posixpath -- Python library reference

posixpath -- Python library reference
Prev: posix (posix.html)
Top: Top (top.html)
# 8.2. Standard Module `posixpath`
This module implements some useful functions on POSIX pathnames.
Do not import this module directly. Instead, import the
module `os` and use `os.path`.


Profiler Changes -- Python library reference
Prev: Profiler Introduction (profiler_introduction.html)
Top: Top (top.html)
# 10.2. How Is This Profiler Different From The Old Profiler?
The big changes from old profiling module are that you get more
information, and you pay less CPU time.  It's not a trade-off, it's a
trade-up.
To be specific:


Profiler Extensions -- Python library reference
Prev: Calibration (calibration.html)
Top: Top (top.html)
# 10.8. Extensions --- Deriving Better Profilers
The `Profile` class of module `profile` was written so that
derived classes could be developed to extend the profiler.  Rather
than describing all the details of such an effort, I'll just present
the following two examples of derived classes that can be used to do
profiling.  If the reader is an avid Python programmer, then it should
be possible to use these as a model and create similar (and perchance
better) profile classes.
If all you want to do is change how the timer is called, or which
timer function is used, then the basic class has an option for that in
the constructor for the class. Consider passing the name of a
function to call into the constructor:
The resulting profiler will call `your_time_func()` instead of
`os.times()`. The function should return either a single number
or a list of numbers (like what `os.times()` returns). If the
function returns a single time number, or the list of returned numbers
has length 2, then you will get an especially fast version of the
dispatch routine.
Be warned that you should calibrate the profiler class for the
timer function that you choose. For most machines, a timer that
returns a lone integer value will provide the best results in terms of
low overhead during profiling. (os.times is pretty bad, 'cause
it returns a tuple of floating point values, so all arithmetic is
floating point in the profiler!). If you want to substitute a
better timer in the cleanest fashion, you should derive a class, and
simply put in the replacement dispatch method that better handles your
timer call, along with the appropriate calibration constant :-).
## Menu


Profiler Introduction -- Python library reference
Prev: The Python Profiler (the_python_profiler.html)
Top: Top (top.html)
# 10.1. Introduction to the profiler
A profiler is a program that describes the run time performance
of a program, providing a variety of statistics.  This documentation
describes the profiler functionality provided in the modules
`profile` and `pstats.`  This profiler provides
deterministic profiling of any Python programs.  It also
provides a series of report generation tools to allow users to rapidly
examine the results of a profile operation.


pwd -- Python library reference

pwd -- Python library reference
Prev: posixpath (posixpath.html)
Top: Top (top.html)
# 8.3. Built-in Module `pwd`
This module provides access to the UNIX password database.
It is available on all UNIX versions.
Password database entries are reported as 7-tuples containing the
following items from the password database (see <pwd.h>), in order:
`pw_name`,
`pw_passwd`,
`pw_uid`,
`pw_gid`,
`pw_gecos`,
`pw_dir`,
`pw_shell`.
The uid and gid items are integers, all others are strings.
An exception is raised if the entry asked for cannot be found.
It defines the following items:


Python Services -- Python library reference
Prev: Built-in Objects (built-in_objects.html)
Top: Top (top.html)
# 3. Python Services
The modules described in this chapter provide a wide range of services
related to the Python interpreter and its interaction with its
environment.  Here's an overview:
## Menu


rand -- Python library reference

rand -- Python library reference
Prev: math (math.html)
Top: Top (top.html)
# 5.2. Standard Module `rand`
 This module implements a pseudo-random number
generator with an interface similar to `rand()` in C.
the following functions:


rect -- Python library reference

rect -- Python library reference
Prev: stdwinevents (stdwinevents.html)
Top: Top (top.html)
# 15.3. Standard Module `rect`
This module contains useful operations on rectangles.
A rectangle is defined as in module
`stdwin`:
a pair of points, where a point is a pair of integers.
For example, the rectangle
is a rectangle whose left, top, right and bottom edges are 10, 20, 90
and 80, respectively.
Note that the positive vertical axis points down (as in
`stdwin`).
The module defines the following objects:


Reference Manual -- Python library reference
Prev: Deterministic Profiling (deterministic_profiling.html)
Top: Top (top.html)
# 10.5. Reference Manual
The primary entry point for the profiler is the global function
`profile.run()`.  It is typically used to create any profile
information.  The reports are formatted and printed using methods of
the class `pstats.Stats`.  The following is a description of all
of these standard entry points and functions.  For a more in-depth
view of some of the code, consider reading the later section on
Profiler Extensions, which includes discussion of how to derive
``better'' profilers from the classes presented, or reading the source
code for these modules.
## Menu


regex -- Python library reference

regex -- Python library reference
Prev: string (string.html)
Top: Top (top.html)
# 4.2. Built-in Module `regex`
This module provides regular expression matching operations similar to
those found in Emacs.  It is always available.
By default the patterns are Emacs-style regular expressions; there is
a way to change the syntax to match that of several well-known
UNIX utilities.
This module is 8-bit clean: both patterns and strings may contain null
bytes and characters whose high bit is set.
Please note: There is a little-known fact about Python string
literals which means that you don't usually have to worry about
doubling backslashes, even though they are used to escape special
characters in string literals as well as in regular expressions. This
is because Python doesn't remove backslashes from string literals if
they are followed by an unrecognized escape character.
However, if you want to include a literal backslash in a
regular expression represented as a string literal, you have to
quadruple it. E.g. to extract LaTeX `\section{...}' headers from a document, you can use this pattern:
`'\\\\section{\(.*\)}'`.
The module defines these functions, and an exception:
Compiled regular expression objects support these methods:
Compiled regular expressions support these data attributes:


regsub -- Python library reference

regsub -- Python library reference
Prev: regex (regex.html)
Top: Top (top.html)
# 4.3. Standard Module `regsub`
This module defines a number of functions useful for working with
regular expressions (see built-in module `regex`).


rfc822 -- Python library reference

rfc822 -- Python library reference
Prev: sgmllib (sgmllib.html)
Top: Top (top.html)
# 11.10. Standard Module `rfc822`
This module defines a class, `Message`, which represents a
collection of ``email headers'' as defined by the Internet standard
RFC 822.  It is used in various contexts, usually to read such headers
from a file.
A `Message` instance is instantiated with an open file object as
parameter. Instantiation reads headers from the file up to a blank
line and stores them in the instance; after instantiation, the file is
positioned directly after the blank line that terminates the headers.
Input lines as read from the file may either be terminated by CR-LF or
by a single linefeed; a terminating CR-LF is replaced by a single
linefeed before the line is stored.
All header matching is done independent of upper or lower case;
e.g. `m['From']`, `m['from']` and `m['FROM']` all yield
the same result.
## Menu


rgbimg -- Python library reference

rgbimg -- Python library reference
Prev: jpeg (jpeg.html)
Top: Top (top.html)
# 12.5. Built-in Module `rgbimg`
The rgbimg module allows python programs to access SGI imglib image
files (also known as .rgb files).  The module is far from
complete, but is provided anyway since the functionality that there is
is enough in some cases.  Currently, colormap files are not supported.
The module defines the following variables and functions:


rotor -- Python library reference

rotor -- Python library reference
Prev: mpz (mpz.html)
Top: Top (top.html)
# 13.3. Built-in Module `rotor`
This module implements a rotor-based encryption algorithm, contributed by
Lance Ellinghouse.  The design is derived from the Enigma device, a machine
used during World War II to encipher messages.  A rotor is simply a
permutation.  For example, if the character `A' is the origin of the rotor,
then a given rotor might map `A' to `L', `B' to `Z', `C' to `G', and so on.
To encrypt, we choose several different rotors, and set the origins of the
rotors to known positions; their initial position is the ciphering key.  To
encipher a character, we permute the original character by the first rotor,
and then apply the second rotor's permutation to the result. We continue
until we've applied all the rotors; the resulting character is our
ciphertext.  We then change the origin of the final rotor by one position,
from `A' to `B'; if the final rotor has made a complete revolution, then we
rotate the next-to-last rotor by one position, and apply the same procedure
recursively.  In other words, after enciphering one character, we advance
the rotors in the same fashion as a car's odometer. Decoding works in the
same way, except we reverse the permutations and apply them in the opposite
order.
The available functions in this module are:
Rotor objects have the following methods:
An example usage:
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
most important difference is that in the original Enigma, there were only 5
or 6 different rotors in existence, and they were applied twice to each
character; the cipher key was the order in which they were placed in the
machine. The Python rotor module uses the supplied key to initialize a
random number generator; the rotor permutations and their initial positions
are then randomly generated. The original device only enciphered the
letters of the alphabet, while this module can handle any 8-bit binary data;
it also produces binary output. This module can also operate with an
arbitrary number of rotors.
The original Enigma cipher was broken in 1944.
The version implemented here is probably a good deal more difficult to crack
(especially if you use many rotors), but it won't be impossible for
a truly skilful and determined attacker to break the cipher. So if you want
to keep the NSA out of your files, this rotor cipher may well be unsafe, but
for discouraging casual snooping through your files, it will probably be
just fine, and may be somewhat safer than using the Unix crypt
command.


select -- Python library reference

select -- Python library reference
Prev: socket (socket.html)
Top: Top (top.html)
# 7.3. Built-in Module `select`
This module provides access to the function `select` available in
most UNIX versions.  It defines the following:


Sequence Types -- Python library reference
Prev: Numeric Types (numeric_types.html)
Top: Top (top.html)
## 2.1.5. Sequence Types
There are three sequence types: strings, lists and tuples.
Strings literals are written in single or double quotes:
`'xyzzy'`, `"frobozz"`. See Chapter 2 of the Python
Reference Manual for more about string literals. Lists are
constructed with square brackets, separating items with commas:
`[a, b, c]`. Tuples are constructed by the comma operator (not
within square brackets), with or without enclosing parentheses, but an
empty tuple must have the enclosing parentheses, e.g.,
`a, b, c` or `()`. A single item tuple must have a trailing
comma, e.g., `(d,)`.
Sequence types support the following operations. The `in' and
`not,in' operations have the same priorities as the comparison
operations. The `+' and `*' operations have the same
priority as the corresponding numeric operations.(1) (#footnotetext1)
This table lists the sequence operations sorted in ascending priority
(operations in the same box have the same priority). In the table,
s and t are sequences of the same type; n, i
and j are integers:
Notes:
## Menu
## ---------- Footnotes ----------
(1) (#footnoteref1)
They must
have since the parser can't tell the type of the operands.


SGI IRIX Specific Services -- Python library reference
Prev: Standard Windowing Interface (standard_windowing_interface.html)
Top: Top (top.html)
# 16. SGI IRIX Specific Services
The modules described in this chapter provide interfaces to features
that are unique to SGI's IRIX operating system (versions 4 and 5).
## Menu


sgmllib -- Python library reference

sgmllib -- Python library reference
Prev: htmllib (htmllib.html)
Top: Top (top.html)
# 11.9. Standard Module `sgmllib`
This module defines a class `SGMLParser` which serves as the
basis for parsing text files formatted in SGML (Standard Generalized
Mark-up Language).  In fact, it does not provide a full SGML parser
--- it only parses SGML insofar as it is used by HTML, and the module only
exists as a basis for the `htmllib` module.
In particular, the parser is hardcoded to recognize the following
elements:
- • Opening and closing tags of the form
```< tag attr =" value " ...>`'' and
```</ tag >`'', respectively.
• Character references of the form ```&# name ;`''.
• Entity references of the form ```& name ;`''.
• SGML comments of the form ```<!-- text >`''.
The `SGMLParser` class must be instantiated without arguments.
It has the following interface methods:
Apart from overriding or extending the methods listed above, derived
classes may also define methods of the following form to define
processing of specific tags. Tag names in the input stream are case
independent; the tag occurring in method names must be in lower
case:
Note that the parser maintains a stack of opening tags for which no
matching closing tag has been found yet. Only tags processed by
`start_ tag ()` are pushed on this stack. Definition of a
`end_ tag ()` method is optional for these tags. For tags
processed by `do_ tag ()` or by `unknown_tag()`, no
`end_ tag ()` method must be defined.


shelve -- Python library reference

shelve -- Python library reference
Prev: pickle (pickle.html)
Top: Top (top.html)
# 3.5. Standard Module `shelve`
A ``shelf'' is a persistent, dictionary-like object.  The difference
with ``dbm'' databases is that the values (not the keys!) in a shelf
can be essentially arbitrary Python objects --- anything that the
`pickle` module can handle.  This includes most class instances,
recursive data types, and objects containing lots of shared
sub-objects.  The keys are ordinary strings.
To summarize the interface (`key` is a string, `data` is an
arbitrary object):
Restrictions:
- • The choice of which database package will be used (e.g. dbm or gdbm)
depends on which interface is available. Therefore it isn't safe to
open the database directly using dbm. The database is also
(unfortunately) subject to the limitations of dbm, if it is used ---
this means that (the pickled representation of) the objects stored in
the database should be fairly small, and in rare cases key collisions
may cause the database to refuse updates.
• Dependent on the implementation, closing a persistent dictionary may
or may not be necessary to flush changes to disk.
• The `shelve` module does not support concurrent read/write
access to shelved objects. (Multiple simultaneous read accesses are
safe.) When a program has a shelf open for writing, no other program
should have it open for reading or writing. UNIX file locking can
be used to solve this, but this differs across UNIX versions and
requires knowledge about the database implementation used.


signal -- Python library reference

signal -- Python library reference
Prev: Optional Operating System Services (optional_operating_system_services.html)
Top: Top (top.html)
# 7.1. Built-in Module `signal`
This module provides mechanisms to use signal handlers in Python.
Some general rules for working with signals handlers:
- • A handler for a particular signal, once set, remains installed until
it is explicitly reset (i.e. Python uses the BSD style interface).
• There is no way to ``block'' signals temporarily from critical
sections (since this is not supported by all UNIX flavors).
• Although Python signal handlers are called asynchronously as far as
the Python user is concerned, they can only occur between the
``atomic'' instructions of the Python interpreter. This means that
signals arriving during long calculations implemented purely in C
(e.g. regular expression matches on large bodies of text) may be
delayed for an arbitrary amount of time.
• When a signal arrives during an I/O operation, it is possible that the
I/O operation raises an exception after the signal handler returns.
This is dependent on the underlying UNIX system's semantics regarding
interrupted system calls.
• Because the C signal handler always returns, it makes little sense to
catch synchronous errors like `SIGFPE` or `SIGSEGV`.
• Python installs a small number of signal handlers by default:
`SIGPIPE` is ignored (so write errors on pipes and sockets can be
reported as ordinary Python exceptions), `SIGINT` is translated
into a `KeyboardInterrupt` exception, and `SIGTERM` is
caught so that necessary cleanup (especially `sys.exitfunc`) can
be performed before actually terminating. All of these can be
overridden.
• Some care must be taken if both signals and threads are used in the
same program. The fundamental thing to remember in using signals and
threads simultaneously is: always perform `signal()` operations
in the main thread of execution. Any thread can perform an
`alarm()`, `getsignal()`, or `pause()`; only the main
thread can set a new signal handler, and the main thread will be the
only one to receive signals (this is enforced by the Python signal
module, even if the underlying thread implementation supports sending
signals to individual threads). This means that signals can't be used
as a means of interthread communication. Use locks instead.
The variables defined in the signal module are:
The signal module defines the following functions:


socket -- Python library reference

socket -- Python library reference
Prev: signal (signal.html)
Top: Top (top.html)
# 7.2. Built-in Module `socket`
This module provides access to the BSD socket interface.
It is available on UNIX systems that support this interface.
For an introduction to socket programming (in C), see the following
papers: An Introductory 4.3BSD Interprocess Communication
Tutorial, by Stuart Sechrest and An Advanced 4.3BSD Interprocess
Communication Tutorial, by Samuel J. Leffler et al, both in the
UNIX Programmer's Manual, Supplementary Documents 1 (sections PS1:7
and PS1:8). The UNIX manual pages for the various socket-related
system calls are also a valuable source of information on the details of
socket semantics.
The Python interface is a straightforward transliteration of the
UNIX system call and library interface for sockets to Python's
object-oriented style: the `socket()` function returns a
socket object whose methods implement the various socket system
calls. Parameter types are somewhat higer-level than in the C
interface: as with `read()` and `write()` operations on Python
files, buffer allocation on receive operations is automatic, and
buffer length is implicit on send operations.
Socket addresses are represented as a single string for the
`AF_UNIX` address family and as a pair
`( host , port )` for the `AF_INET` address family,
where host is a string representing
either a hostname in Internet domain notation like
`'daring.cwi.nl'` or an IP address like `'100.50.200.5'`,
and port is an integral port number. Other address families are
currently not supported. The address format required by a particular
socket object is automatically selected based on the address family
specified when the socket object was created.
All errors raise exceptions. The normal exceptions for invalid
argument types and out-of-memory conditions can be raised; errors
related to socket or address semantics raise the error `socket.error`.
Non-blocking mode is supported through the `setblocking()`
method.
The module `socket` exports the following constants and functions:
## Menu


Socket Example -- Python library reference
Prev: Socket Objects (socket_objects.html)
Top: Top (top.html)
## 7.2.2. Example
Here are two minimal example programs using the TCP/IP protocol: a
server that echoes all data that it receives back (servicing only one
client), and a client using it.  Note that a server must perform the
sequence `socket`, `bind`, `listen`, `accept`
(possibly repeating the `accept` to service more than one client),
while a client only needs the sequence `socket`, `connect`.
Also note that the server does not `send`/`receive` on the
socket it is listening on but on the new socket returned by
`accept`.


Socket Objects -- Python library reference
Prev: socket (socket.html)
Top: Top (top.html)
## 7.2.1. Socket Objects
 Socket objects have the following methods.  Except for
`makefile()` these correspond to UNIX system calls applicable to
sockets.
Note that there are no methods `read()` or `write()`; use
`recv()` and `send()` without flags argument instead.


Special Attributes -- Python library reference
Prev: Other Built-in Types (other_built-in_types.html)
Top: Top (top.html)
## 2.1.8. Special Attributes
The implementation adds a few special read-only attributes to several
object types, where they are relevant:
- • `x .__dict__` is a dictionary of some sort used to store an
object's (writable) attributes;
• `x .__methods__` lists the methods of many built-in object types,
e.g., `[].__methods__` yields
`['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort']`;
• `x .__members__` lists data attributes;
• `x .__class__` is the class to which a class instance belongs;
• `x .__bases__` is the tuple of base classes of a class object.


speech channel objects -- Python library reference
Prev: voice objects (voice_objects.html)
Top: Top (top.html)
## 14.8.2. speech channel objects
A speech channel object allows you to speak strings with slightly more
control than `SpeakString()`, and allows you to use multiple
speakers at the same time. Please note that channel pitch and rate are
interrelated in some way, so that to make your Macintosh sing you will
have to adjust both.


Standard Windowing Interface -- Python library reference
Prev: Macintosh Specific Services (macintosh_specific_services.html)
Top: Top (top.html)
# 15. Standard Windowing Interface
The modules in this chapter are available only on those systems where
the STDWIN library is available.  STDWIN runs on UNIX under X11 and
on the Macintosh.  See CWI report CS-R8817.
Warning: Using STDWIN is not recommended for new
applications. It has never been ported to Microsoft Windows or
Windows NT, and for X11 or the Macintosh it lacks important
functionality --- in particular, it has no tools for the construction
of dialogs. For most platforms, alternative, native solutions exist
(though none are currently documented in this manual): Tkinter for
UNIX under X11, native Xt with Motif or Athena widgets for UNIX
under X11, Win32 for Windows and Windows NT, and a collection of
native toolkit interfaces for the Macintosh.
## Menu


stdwin -- Python library reference

stdwin -- Python library reference
Prev: Standard Windowing Interface (standard_windowing_interface.html)
Top: Top (top.html)
# 15.1. Built-in Module `stdwin`
This module defines several new object types and functions that
provide access to the functionality of STDWIN.
On Unix running X11, it can only be used if the `DISPLAY`
environment variable is set or an explicit `-display
displayname' argument is passed to the Python interpreter.
Functions have names that usually resemble their C STDWIN counterparts
with the initial `w' dropped.
Points are represented by pairs of integers; rectangles
by pairs of points.
For a complete description of STDWIN please refer to the documentation
of STDWIN for C programmers (aforementioned CWI report).
## Menu


STDWIN Example -- Python library reference
Prev: Text-edit Objects (text-edit_objects.html)
Top: Top (top.html)
## 15.1.7. Example
Here is a minimal example of using STDWIN in Python.
It creates a window and draws the string ``Hello world'' in the top
left corner of the window.
The window will be correctly redrawn when covered and re-exposed.
The program quits when the close icon or menu item is requested.


STDWIN Functions -- Python library reference
Prev: stdwin (stdwin.html)
Top: Top (top.html)
## 15.1.1. Functions Defined in Module `stdwin`
The following functions are defined in the `stdwin` module:
## ---------- Footnotes ----------
(1) (#footnoteref1)
The Python version of STDWIN does not support draw procedures; all
drawing requests are reported as draw events.


stdwinevents -- Python library reference
Prev: stdwin (stdwin.html)
Top: Top (top.html)
# 15.2. Standard Module `stdwinevents`
This module defines constants used by STDWIN for event types
(`WE_ACTIVATE` etc.), command codes (`WC_LEFT` etc.)
and selection types (`WS_PRIMARY` etc.).
Read the file for details.
Suggested usage is


string -- Python library reference

string -- Python library reference
Prev: String Services (string_services.html)
Top: Top (top.html)
# 4.1. Standard Module `string`
This module defines some constants useful for checking character
classes and some useful string functions.  See the modules
`regex` and `regsub` for string functions based on regular
expressions.
The constants defined in this module are are:
The functions defined in this module are:
This module is implemented in Python. Much of its functionality has
been reimplemented in the built-in module `strop`. However, you
should never import the latter module directly. When
`string` discovers that `strop` exists, it transparently
replaces parts of itself with the implementation from `strop`.
After initialization, there is no overhead in using
`string` instead of `strop`.


String Services -- Python library reference
Prev: Python Services (python_services.html)
Top: Top (top.html)
# 4. String Services
The modules described in this chapter provide a wide range of string
manipulation operations.  Here's an overview:
## Menu


struct -- Python library reference

struct -- Python library reference
Prev: regsub (regsub.html)
Top: Top (top.html)
# 4.4. Built-in Module `struct`
This module performs conversions between Python values and C
structs represented as Python strings.  It uses format strings
(explained below) as compact descriptions of the lay-out of the C
structs and the intended conversion to/from Python values.
See also built-in module `array`.
The module defines the following exception and functions:
Format characters have the following meaning; the conversion between C
and Python values should be obvious given their types:
A format character may be preceded by an integral repeat count; e.g.
the format string `'4h'` means exactly the same as `'hhhh'`.
C numbers are represented in the machine's native format and byte
order, and properly aligned by skipping pad bytes if necessary
(according to the rules used by the C compiler).
Examples (all on a big-endian machine):
Hint: to align the end of a structure to the alignment requirement of
a particular type, end the format with the code for that type with a
repeat count of zero, e.g. the format `'llh0l'` specifies two
pad bytes at the end, assuming longs are aligned on 4-byte boundaries.
(More format characters are planned, e.g. `'s'` for character
arrays, upper case for unsigned variants, and a way to specify the
byte order, which is useful for [de]constructing network packets and
reading/writing portable binary file formats like TIFF and AIFF.)


sunaudiodev -- Python library reference

sunaudiodev -- Python library reference
Prev: SunOS Specific Services (sunos_specific_services.html)
Top: Top (top.html)
# 17.1. Built-in Module `sunaudiodev`
This module allows you to access the sun audio interface. The sun
audio hardware is capable of recording and playing back audio data
in U-LAW format with a sample rate of 8K per second. A full
description can be gotten with `man audio'.
The module defines the following variables and functions:
## Menu


SunOS Specific Services -- Python library reference
Prev: SGI IRIX Specific Services (sgi_irix_specific_services.html)
Top: Top (top.html)
# 17. SunOS Specific Services
The modules described in this chapter provide interfaces to features
that are unique to the SunOS operating system (versions 4 and 5; the
latter is also known as Solaris version 2).
## Menu


sys -- Python library reference

sys -- Python library reference
Prev: Python Services (python_services.html)
Top: Top (top.html)
# 3.1. Built-in Module `sys`
This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
It is always available.


TCP Status Objects -- Python library reference
Prev: TCP Stream Objects (tcp_stream_objects.html)
Top: Top (top.html)
## 14.7.2. TCP Status Objects
This object has no methods, only some members holding information on
the connection. A complete description of all fields in this objects
can be found in the Apple documentation. The most interesting ones are:


TCP Stream Objects -- Python library reference
Prev: mactcp (mactcp.html)
Top: Top (top.html)
## 14.7.1. TCP Stream Objects


tempfile -- Python library reference

tempfile -- Python library reference
Prev: getopt (getopt.html)
Top: Top (top.html)
# 6.4. Standard Module `tempfile`
This module generates temporary file names.  It is not UNIX specific,
but it may require some help on non-UNIX systems.
Note: the modules does not create temporary files, nor does it
automatically remove them when the current process exits or dies.
The module defines a single user-callable function:
The module uses two global variables that tell it how to construct a
temporary name. The caller may assign values to them; by default they
are initialized at the first call to `mktemp()`.
Warning: if a UNIX process uses `mktemp()`, then calls
`fork()` and both parent and child continue to use
`mktemp()`, the processes will generate conflicting temporary
names. To resolve this, the child process should assign `None`
to `template`, to force recomputing the default on the next call
to `mktemp()`.


TERMIOS -- Python library reference

TERMIOS -- Python library reference
Prev: termios (termios.html)
Top: Top (top.html)
# 8.8. Standard Module `TERMIOS`
This module defines the symbolic constants required to use the
`termios` module (see the previous section).  See the Posix or
UNIX manual pages (or the source) for a list of those constants.
Note: this module resides in a system-dependent subdirectory of the
Python library directory. You may have to generate it for your
particular system using the script Tools/scripts/h2py.py.


termios Example -- Python library reference
Prev: termios (termios.html)
Top: Top (top.html)
## 8.7.1. Example
Here's a function that prompts for a password with echoing turned off.
Note the technique using a separate `termios.tcgetattr()` call
and a `try ... finally` statement to ensure that the old tty
attributes are restored exactly no matter what happens:


Text-edit Objects -- Python library reference
Prev: Bitmap Objects (bitmap_objects.html)
Top: Top (top.html)
## 15.1.6. Text-edit Objects
A text-edit object represents a text-edit block.
For semantics, see the STDWIN documentation for C programmers.
The following methods exist:


The Null Object -- Python library reference
Prev: Type Objects (type_objects.html)
Top: Top (top.html)
### 2.1.7.7. The Null Object
This object is returned by functions that don't explicitly return a
value.  It supports no special operations.  There is exactly one null
object, named `None` (a built-in name).
It is written as `None`.


The Python Debugger -- Python library reference
Prev: UNIX Specific Services (unix_specific_services.html)
Top: Top (top.html)
# 9. The Python Debugger
The module `pdb` defines an interactive source code debugger for
Python programs.  It supports setting breakpoints and single stepping
at the source line level, inspection of stack frames, source code
listing, and evaluation of arbitrary Python code in the context of any
stack frame.  It also supports post-mortem debugging and can be called
under program control.
The debugger is extensible --- it is actually defined as a class
`Pdb`. This is currently undocumented but easily understood by
reading the source. The extension interface uses the (also
undocumented) modules `bdb` and `cmd`.
A primitive windowing version of the debugger also exists --- this is
module `wdb`, which requires STDWIN (see the chapter on STDWIN
specific modules).
The debugger's prompt is ```(Pdb)`''.
Typical usage to run a program under control of the debugger is:
Typical usage to inspect a crashed program is:
The module defines the following functions; each enters the debugger
in a slightly different way:
## Menu


The Python Profiler -- Python library reference
Prev: The Python Debugger (the_python_debugger.html)
Top: Top (top.html)
# 10. The Python Profiler
Copyright @copyright 1994, by InfoSeek Corporation, all rights reserved.
Written by James Roskind(1) (#footnotetext1)
Permission to use, copy, modify, and distribute this Python software
and its associated documentation for any purpose (subject to the
restriction in the following sentence) without fee is hereby granted,
provided that the above copyright notice appears in all copies, and
that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of InfoSeek not be used in
advertising or publicity pertaining to distribution of the software
without specific, written prior permission. This permission is
explicitly restricted to the copying and modification of the software
to remain in Python, compiled Python, or other languages (such as C)
wherein the modified or derived code is exclusively imported into a
Python module.
INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
The profiler was written after only programming in Python for 3 weeks.
As a result, it is probably clumsy code, but I don't know for sure yet
'cause I'm a beginner :-). I did work hard to make the code run fast,
so that profiling would be a reasonable thing to do. I tried not to
repeat code fragments, but I'm sure I did some stuff in really awkward
ways at times. Please send suggestions for improvements to:
`jar@infoseek.com`. I won't promise any support. ...but
I'd appreciate the feedback.
## Menu
## ---------- Footnotes ----------
(1) (#footnoteref1)
Updated and converted to LaTeX by Guido van Rossum. The references to
the old profiler are left in the text, although it no longer exists.


The Stats Class -- Python library reference
Prev: Reference Manual (reference_manual.html)
Top: Top (top.html)
## 10.5.1. The `Stats` Class
## ---------- Footnotes ----------
(1) (#footnoteref1)
This was once necessary, when Python would print any unused expression
result that was not `None`.  The method is still defined for
backward compatibility.


thread -- Python library reference

thread -- Python library reference
Prev: select (select.html)
Top: Top (top.html)
# 7.4. Built-in Module `thread`
This module provides low-level primitives for working with multiple
threads (a.k.a. light-weight processes or tasks) --- multiple
threads of control sharing their global data space.  For
synchronization, simple locks (a.k.a. mutexes or binary
semaphores) are provided.
The module is optional and supported on SGI IRIX 4.x and 5.x and Sun
Solaris 2.x systems, as well as on systems that have a PTHREAD
implementation (e.g. KSR).
It defines the following constant and functions:
Lock objects have the following methods:
Caveats:
- • Threads interact strangely with interrupts: the
`KeyboardInterrupt` exception will be received by an arbitrary
thread. (When the `signal` module is available, interrupts
always go to the main thread.)
• Calling `sys.exit()` or raising the `SystemExit` is
equivalent to calling `thread.exit_thread()`.
• Not all built-in functions that may block waiting for I/O allow other
threads to run. (The most popular ones (`sleep`, `read`,
`select`) work as expected.)


time -- Python library reference

time -- Python library reference
Prev: os (os.html)
Top: Top (top.html)
# 6.2. Built-in Module `time`
This module provides various time-related functions.
It is always available.
An explanation of some terminology and conventions is in order.
- • The ``epoch'' is the point where the time starts. On January 1st of that
year, at 0 hours, the ``time since the epoch'' is zero. For UNIX, the
epoch is 1970. To find out what the epoch is, look at `gmtime(0)`.
• UTC is Coordinated Universal Time (formerly known as Greenwich Mean
Time). The acronym UTC is not a mistake but a compromise between
English and French.
• DST is Daylight Saving Time, an adjustment of the timezone by
(usually) one hour during part of the year. DST rules are magic
(determined by local law) and can change from year to year. The C
library has a table containing the local rules (often it is read from
a system file for flexibility) and is the only source of True Wisdom
in this respect.
• The precision of the various real-time functions may be less than
suggested by the units in which their value or argument is expressed.
E.g. on most UNIX systems, the clock ``ticks'' only 50 or 100 times a
second, and on the Mac, times are only accurate to whole seconds.
The module defines the following functions and data items:


Top -- Python library reference

Top -- Python library reference
Prev: (dir) (../dir.html)
# The Python library
This file describes the built-in types, exceptions and functions and the
standard modules that come with the Python system.  It assumes basic
knowledge about the Python language.  For an informal introduction to
the language, see the Python Tutorial.  The Python
Reference Manual gives a more formal definition of the language.
(These manuals are not yet available in INFO or Texinfo format.)
This version corresponds to Python version 1.2 (4 April 1995).
## Menu


traceback -- Python library reference

traceback -- Python library reference
Prev: types (types.html)
Top: Top (top.html)
# 3.3. Standard Module `traceback`
This module provides a standard interface to format and print stack
traces of Python programs.  It exactly mimics the behavior of the
Python interpreter when it prints a stack trace.  This is useful when
you want to print stack traces under program control, e.g. in a
``wrapper'' around the interpreter.
The module uses traceback objects --- this is the object type
that is stored in the variables `sys.exc_traceback` and
`sys.last_traceback`.
The module defines the following functions:


Truth Value Testing -- Python library reference
Prev: Types (types.html)
Top: Top (top.html)
## 2.1.1. Truth Value Testing
Any object can be tested for truth value, for use in an `if` or
`while` condition or as operand of the Boolean operations below.
The following values are considered false:
- • `None`
  • zero of any numeric type, e.g., `0`, `0L`, `0.0`.
  • any empty sequence, e.g., `''`, `()`, `[]`.
  • any empty mapping, e.g., `{}`.
  • instances of user-defined classes, if the class defines a
  `__nonzero__()` or `__len__()` method, when that
  method returns zero.
All other values are considered true --- so objects of many types are
always true.
Operations and built-in functions that have a Boolean result always
return `0` for false and `1` for true, unless otherwise
stated.  (Important exception: the Boolean operations `or' and
`and' always return one of their operands.)


Type Objects -- Python library reference
Prev: Code Objects (code_objects.html)
Top: Top (top.html)
### 2.1.7.6. Type Objects
Type objects represent the various object types.  An object's type is
accessed by the built-in function `type()`.  There are no special
operations on types.  The standard module `types` defines names
for all standard built-in types.
Types are written like this: `<type 'int'>`.


types -- Python library reference

types -- Python library reference
Prev: sys (sys.html)
Top: Top (top.html)
# 3.2. Standard 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
extension modules).  It is safe to use ```from types import *`'' ---
the module does not export any other names besides the ones listed
here.  New names exported by future versions of this module will
all end in `Type`.
Typical use is for functions that do different things depending on
their argument types, like the following:
The module defines the following names:


UDP Stream Objects -- Python library reference
Prev: TCP Status Objects (tcp_status_objects.html)
Top: Top (top.html)
## 14.7.3. UDP Stream Objects
Note that, unlike the name suggests, there is nothing stream-like
about UDP.


UNIX Specific Services -- Python library reference
Prev: Optional Operating System Services (optional_operating_system_services.html)
Top: Top (top.html)
# 8. UNIX Specific Services
The modules described in this chapter provide interfaces to features
that are unique to the UNIX operating system, or in some cases to
some or many variants of it.  Here's an overview:
## Menu