node279.html | allos.html | node281.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.27.4 Acknowledgements (node279.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.28.1 Logger Objects (node281.html)
---
# 6.28 logging --
Logging facility for Python
New in version 2.3.
This module defines functions and classes which implement a flexible
error logging system for applications.
Logging is performed by calling methods on instances of the
Logger class (hereafter called loggers). Each instance has a
name, and they are conceptually arranged in a name space hierarchy
using dots (periods) as separators. For example, a logger named
"scan" is the parent of loggers "scan.text", "scan.html" and "scan.pdf".
Logger names can be anything you want, and indicate the area of an
application in which a logged message originates.
Logged messages also have levels of importance associated with them.
The default levels provided are DEBUG, INFO,
WARNING, ERROR and CRITICAL. As a
convenience, you indicate the importance of a logged message by calling
an appropriate method of Logger. The methods are
debug(), info(), warning(), error() and
critical(), which mirror the default levels. You are not
constrained to use these levels: you can specify your own and use a
more general Logger method, log(), which takes an
explicit level argument.
Levels can also be associated with loggers, being set either by the
developer or through loading a saved logging configuration. When a
logging method is called on a logger, the logger compares its own
level with the level associated with the method call. If the logger's
level is higher than the method call's, no logging message is actually
generated. This is the basic mechanism controlling the verbosity of
logging output.
Logging messages are encoded as instances of the LogRecord class.
When a logger decides to actually log an event, an LogRecord
instance is created from the logging message.
Logging messages are subjected to a dispatch mechanism through the
use of handlers, which are instances of subclasses of the
Handler class. Handlers are responsible for ensuring that a logged
message (in the form of a LogRecord) ends up in a particular
location (or set of locations) which is useful for the target audience for
that message (such as end users, support desk staff, system administrators,
developers). Handlers are passed LogRecord instances intended for
particular destinations. Each logger can have zero, one or more handlers
associated with it (via the addHandler method of Logger).
In addition to any handlers directly associated with a logger,
all handlers associated with all ancestors of the logger are
called to dispatch the message.
Just as for loggers, handlers can have levels associated with them.
A handler's level acts as a filter in the same way as a logger's level does.
If a handler decides to actually dispatch an event, the emit() method
is used to send the message to its destination. Most user-defined subclasses
of Handler will need to override this emit().
In addition to the base Handler class, many useful subclasses
are provided:
1. StreamHandler instances send error messages to
streams (file-like objects).
2. FileHandler instances send error messages to disk
files.
3. RotatingFileHandler instances send error messages to disk
files, with support for maximum log file sizes and log file rotation.
4. SocketHandler instances send error messages to
TCP/IP sockets.
5. DatagramHandler instances send error messages to UDP
sockets.
6. SMTPHandler instances send error messages to a
designated email address.
7. SysLogHandler instances send error messages to a
Unix syslog daemon, possibly on a remote machine.
8. NTEventLogHandler instances send error messages to a
Windows NT/2000/XP event log.
9. MemoryHandler instances send error messages to a
buffer in memory, which is flushed whenever specific criteria are
met.
10. HTTPHandler instances send error messages to an
HTTP server using either "GET" or "POST" semantics.
The StreamHandler and FileHandler classes are defined
in the core logging package. The other handlers are defined in a sub-
module, logging.handlers. (There is also another sub-module,
logging.config, for configuration functionality.)
Logged messages are formatted for presentation through instances of the
Formatter class. They are initialized with a format string
suitable for use with the % operator and a dictionary.
For formatting multiple messages in a batch, instances of
BufferingFormatter can be used. In addition to the format string
(which is applied to each message in the batch), there is provision for
header and trailer format strings.
When filtering based on logger level and/or handler level is not enough,
instances of Filter can be added to both Logger and
Handler instances (through their addFilter() method).
Before deciding to process a message further, both loggers and handlers
consult all their filters for permission. If any filter returns a false
value, the message is not processed further.
The basic Filter functionality allows filtering by specific logger
name. If this feature is used, messages sent to the named logger and its
children are allowed through the filter, and all others dropped.
In addition to the classes described above, there are a number of module-
level functions.
See Also:


module-mailcap.html | netdata.html | mailbox-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.3 mailcap (module-mailcap.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.4.1 Mailbox Objects (mailbox-objects.html)
---
# 12.4 mailbox --
Read various mailbox formats
This module defines a number of classes that allow easy and uniform
access to mail messages in a (Unix) mailbox.
Note that because the rfc822 (module-rfc822.html) module is deprecated, it is
recommended that you use the email (module-email.html) package to create
message objects from a mailbox. (The default can't be changed for
backwards compatibility reasons.) The safest way to do this is with
bit of code:
```text

import email
import email.Errors
import mailbox

def msgfactory(fp):
try:
return email.message_from_file(fp)
except email.Errors.MessageParseError:
# Don't return None since that will
# stop the mailbox iterator
return ''

mbox = mailbox.UnixMailbox(fp, msgfactory)
```
The above wrapper is defensive against ill-formed MIME messages in the
mailbox, but you have to be prepared to receive the empty string from
the mailbox's next() method. On the other hand, if you
know your mailbox contains only well-formed MIME messages, you can
simplify this to:
```text

import email
import mailbox

mbox = mailbox.UnixMailbox(fp, email.message_from_file)
```
See Also:


12.3 mailcap -- Mailcap file handling.

node510.html | netdata.html | module-mailbox.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.2.13 Examples (node510.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.4 mailbox (module-mailbox.html)
---
# 12.3 mailcap --
Mailcap file handling.
Mailcap files are used to configure how MIME-aware applications such
as mail readers and Web browsers react to files with different MIME
types. (The name ``mailcap'' is derived from the phrase ``mail
capability''.) For example, a mailcap file might contain a line like
"video/mpeg; xmpeg %s". Then, if the user encounters an email
message or Web document with the MIME type video/mpeg,
"%s" will be replaced by a filename (usually one belonging to a
temporary file) and the xmpeg program can be automatically
started to view the file.
The mailcap format is documented in RFC 1524 (http://www.faqs.org/rfcs/rfc1524.html), ``A User Agent
Configuration Mechanism For Multimedia Mail Format Information,'' but
is not an Internet standard. However, mailcap files are supported on
most Unix systems.


module-builtin.html | python.html | module-future.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.30 __builtin__ (module-builtin.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.32 __future__ (module-future.html)
---
# 3.31 __main__ --
Top-level script environment
This module represents the (otherwise anonymous) scope in which the
interpreter's main program executes -- commands read either from
standard input, from a script file, or from an interactive prompt. It
is this environment in which the idiomatic ``conditional script''
stanza causes a script to run:


module-copy.html | python.html | module-warnings.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.18 copy (module-copy.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.20 warnings (module-warnings.html)
---
# 3.19 marshal --
Internal Python object serialization
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).3.12 (#foot8879)
This is not a general ``persistence'' module. For general persistence
and transfer of Python objects through RPC calls, see the modules
pickle (module-pickle.html) and shelve (module-shelve.html). The marshal module exists
mainly to support reading and writing the ``pseudo-compiled'' code for
Python modules of .pyc files. Therefore, the Python
maintainers reserve the right to modify the marshal format in backward
incompatible ways should the need arise. If you're serializing and
de-serializing Python objects, use the pickle module instead.
Warning:
The marshal module is not intended to be secure against
erroneous or maliciously constructed data. Never unmarshal data
received from an untrusted or unauthenticated source.
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, Unicode objects, 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), it is possible to create plain Python
integers that are longer than 32 bits.
If such an integer is marshaled and read back in on a machine where
C's `long int` type has only 32 bits, a Python long integer object
is returned instead. While of a different type, the numeric value is
the same. (This behavior is new in Python 2.2. In earlier versions,
all but the least-significant 32 bits of the value were lost, and a
warning message was printed.)
There are functions that read/write files as well as functions
operating on strings.
The module defines these functions:


5.5 math -- Mathematical functions

regrtest.html | misc.html | module-cmath.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.4.3 Running tests Using (regrtest.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.6 cmath (module-cmath.html)
---
# 5.5 math --
Mathematical functions
This module is always available. It provides access to the
mathematical functions defined by the C standard.
These functions cannot be used with complex numbers; use the functions
of the same name from the cmath (module-cmath.html) module if you require
support for complex numbers. The distinction between functions which
support complex numbers and those which don't is made since most users
do not want to learn quite as much mathematics as required to
understand complex numbers. Receiving an exception instead of a
complex result allows earlier detection of the unexpected complex
number used as a parameter, so that the programmer can determine how
and why it was generated in the first place.
The following functions are provided by this module. Except
when explicitly noted otherwise, all return values are floats:
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 module also defines two mathematical constants:
Note:
The math module consists mostly of thin wrappers around
the platform C math library functions. Behavior in exceptional cases is
loosely specified by the C standards, and Python inherits much of its
math-function error-reporting behavior from the platform C
implementation. As a result,
the specific exceptions raised in error cases (and even whether some
arguments are considered to be exceptional at all) are not defined in any
useful cross-platform or cross-release way. For example, whether
`math.log(0)` returns `-Inf` or raises ValueError or
OverflowError isn't defined, and in
cases where `math.log(0)` raises OverflowError,
`math.log(0L)` may raise ValueError instead.


module-hmac.html | crypto.html | module-sha.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
15.1 hmac (module-hmac.html)
Up:
15. Cryptographic Services (crypto.html)
Next:
15.3 sha (module-sha.html)
---
# 15.2 md5 --
MD5 message digest algorithm
This module implements the interface to RSA's MD5 message digest
algorithm (see also Internet RFC 1321 (http://www.faqs.org/rfcs/rfc1321.html)). Its use is quite
straightforward: use 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 concatenation 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'`:
```text

>>> import md5
>>> m = md5.new()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
```
More condensed:
```text

>>> md5.new("Nobody inspects the spammish repetition").digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
```
The following values are provided as constants in the module and as
attributes of the md5 objects returned by new():
md5 objects support the following methods:
An md5 object has the following methods:


12.5 mhlib -- Access to MH mailboxes

mailbox-objects.html | netdata.html | mh-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.4.1 Mailbox Objects (mailbox-objects.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.5.1 MH Objects (mh-objects.html)
---
# 12.5 mhlib --
Access to MH mailboxes
The mhlib module provides a Python interface to MH folders and
their contents.
The module contains three basic classes, MH, which represents a
particular collection of folders, Folder, which represents a single
folder, and Message, which represents a single message.


mh-message-objects.html | netdata.html | mimetools-message-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.5.3 Message Objects (mh-message-objects.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.6.1 Additional Methods of (mimetools-message-objects.html)
---
# 12.6 mimetools --
Tools for parsing MIME messages
Deprecated since release 2.3.
The email (module-email.html) package should be used in
preference to the mimetools module. This
module is present only to maintain backward
compatibility.
This module defines a subclass of the
rfc822 (module-rfc822.html)module's
Message class and a number of utility functions that are
useful for the manipulation for MIME multipart or encoded message.
It defines the following items:
See Also:


mimetools-message-objects.html | netdata.html | mimetypes-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.6.1 Additional Methods of (mimetools-message-objects.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.7.1 MimeTypes Objects (mimetypes-objects.html)
---
# 12.7 mimetypes --
Map filenames to MIME types
The mimetypes module converts between a filename or URL and
the MIME type associated with the filename extension. Conversions are
provided from filename to MIME type and from MIME type to filename
extension; encodings are not supported for the latter conversion.
The module provides one class and a number of convenience functions.
The functions are the normal interface to this module, but some
applications may be interested in the class as well.
The functions described below provide the primary interface for this
module. If the module has not been initialized, they will call
init() if they rely on the information init()
sets up.
Some additional functions and data items are available for controlling
the behavior of the module.
The MimeTypes class may be useful for applications which may
want more than one MIME-type database:


mimetypes-objects.html | netdata.html | MimeWriter-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.7.1 MimeTypes Objects (mimetypes-objects.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.8.1 MimeWriter Objects (MimeWriter-objects.html)
---
# 12.8 MimeWriter --
Generic MIME file writer
Deprecated since release 2.3.
The email (module-email.html) package should be used in
preference to the MimeWriter module. This
module is present only to maintain backward
compatibility.
This module defines the class MimeWriter. The
MimeWriter class implements a basic formatter for creating
MIME multi-part files. It doesn't seek around the output file nor
does it use large amounts of buffer space. You must write the parts
out in the order that they should occur in the final
file. MimeWriter does buffer the headers you add, allowing you
to rearrange their order.


MimeWriter-objects.html | netdata.html | module-multifile.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.8.1 MimeWriter Objects (MimeWriter-objects.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.10 multifile (module-multifile.html)
---
# 12.9 mimify --
MIME processing of mail messages
Deprecated since release 2.3.
The email (module-email.html) package should be used in
preference to the mimify module. This
module is present only to maintain backward
compatibility.
The mimify module defines two functions to convert mail messages to
and from MIME format. The mail message can be either a simple message
or a so-called multipart message. Each part is treated separately.
Mimifying (a part of) a message entails encoding the message as
quoted-printable if it contains any characters that cannot be
represented using 7-bit ASCII. Unmimifying (a part of) a message
entails undoing the quoted-printable encoding. Mimify and unmimify
are especially useful when a message has to be edited before being
sent. Typical use would be:
```text

unmimify message
edit message
mimify message
send message
```
The modules defines the following user-callable functions and
user-settable variables:
This module can also be used from the command line. Usage is as
follows:
```text

mimify.py -e [-l length] [infile [outfile]]
mimify.py -d [-b] [infile [outfile]]
```
to encode (mimify) and decode (unmimify) respectively. infile
defaults to standard input, outfile defaults to standard output.
The same file can be specified for input and output.
If the -l option is given when encoding, if there are any lines
longer than the specified length, the containing part will be
encoded.
If the -b option is given when decoding, any base64 parts will
be decoded as well.


7.9 mmap --
Memory-mapped file support

QueueObjects.html | someos.html | module-anydbm.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.8.1 Queue Objects (QueueObjects.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.10 anydbm (module-anydbm.html)
---
# 7.9 mmap --
Memory-mapped file support
Memory-mapped file objects behave like both strings and like
file objects. Unlike normal string objects, however, these are
mutable. You can use mmap objects in most places where strings
are expected; for example, you can use the re module to
search through a memory-mapped file. Since they're mutable, you can
change a single character by doing `obj[ index ] = 'a'`, or
change a substring by assigning to a slice:
`obj[ i1 : i2 ] = '...'`. You can also read and write
data starting at the current file position, and seek()
through the file to different positions.
A memory-mapped file is created by the mmap() function,
which is different on Unix and on Windows. In either case you must
provide a file descriptor for a file opened for update.
If you wish to map an existing Python file object, use its
fileno() method to obtain the correct value for the
fileno parameter. Otherwise, you can open the file using the
os.open() function, which returns a file descriptor
directly (the file still needs to be closed when done).
For both the Unix and Windows versions of the function,
access may be specified as an optional keyword parameter.
access accepts one of three values: ACCESS_READ,
ACCESS_WRITE, or ACCESS_COPY to specify
readonly, write-through or copy-on-write memory respectively.
access can be used on both Unix and Windows. If
access is not specified, Windows mmap returns a write-through
mapping. The initial memory values for all three access types are
taken from the specified file. Assignment to an
ACCESS_READ memory map raises a TypeError
exception. Assignment to an ACCESS_WRITE memory map
affects both memory and the underlying file. Assigment to an
ACCESS_COPY memory map affects memory but does not update
the underlying file.
Memory-mapped file objects support the following methods:


module-sha.html | crypto.html | module-rotor.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
15.3 sha (module-sha.html)
Up:
15. Cryptographic Services (crypto.html)
Next:
15.5 rotor (module-rotor.html)
---
# 15.4 mpz --
GNU arbitrary magnitude integers
Deprecated since release 2.2.
See the references at the end of this section for
information about packages which provide similar
functionality. This module will be removed in Python
2.3.
This is an optional module. It is only available when Python is
configured to include it, which requires that the GNU MP software is
installed.
This module implements the interface to part of the GNU MP library,
which defines 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.
Support for rational numberscan be
implemented in Python. For an example, see the
Rat module, provided as
Demos/classes/Rat.py in the Python source distribution.
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 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:


node735.html | node735.html | msvcrt-files.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
22. MS Windows Specific (node735.html)
Up:
22. MS Windows Specific (node735.html)
Next:
22.1.1 File Operations (msvcrt-files.html)
---
# 22.1 msvcrt -
Useful routines from the MS VC++ runtime
Availability: Windows.
These functions provide access to some useful capabilities on Windows
platforms. Some higher-level modules use these functions to build the
Windows implementations of their services. For example, the
getpass (module-getpass.html) module uses this in the implementation of the
getpass() function.
Further documentation on these functions can be found in the Platform
API documentation.


module-mimify.html | netdata.html | MultiFile-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.9 mimify (module-mimify.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.10.1 MultiFile Objects (MultiFile-objects.html)
---
# 12.10 multifile --
Support for files containing distinct parts
The MultiFile object enables you to treat sections of a text
file as file-like input objects, with `''` being returned by
readline() when a given delimiter pattern is encountered. The
defaults of this class are designed to make it useful for parsing
MIME multipart messages, but by subclassing it and overriding methods
it can be easily adapted for more general use.
It will be useful to know that in MultiFile's view of the world, text
is composed of three kinds of lines: data, section-dividers, and
end-markers. MultiFile is designed to support parsing of
messages that may have multiple nested message parts, each with its
own pattern for section-divider and end-marker lines.
See Also:


6.12 mutex -- Mutual exclusion support

scheduler-objects.html | allos.html | mutex-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.11.1 Scheduler Objects (scheduler-objects.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.12.1 Mutex Objects (mutex-objects.html)
---
# 6.12 mutex --
Mutual exclusion support
The mutex module defines a class that allows mutual-exclusion
via acquiring and releasing locks. It does not require (or imply)
threading or multi-tasking, though it could be useful for
those purposes.
The mutex module defines the following class:


12.18 netrc -- netrc file processing

xdr-exceptions.html | netdata.html | netrc-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.17.3 Exceptions (xdr-exceptions.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.18.1 netrc Objects (netrc-objects.html)
---
# 12.18 netrc --
netrc file processing
New in version 1.5.2.
The netrc class parses and encapsulates the netrc file format
used by the Unix ftp program and other FTP clients.


subclassing-reprs.html | python.html | module-site.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.26.2 Subclassing Repr Objects (subclassing-reprs.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.28 site (module-site.html)
---
# 3.27 new --
Creation of runtime internal objects
The new module allows an interface to the interpreter object
creation functions. This is for use primarily in marshal-type functions,
when a new object needs to be created ``magically'' and not by using the
regular creation functions. This module provides a low-level interface
to the interpreter, so care must be exercised when using this module.
The new module defines the following functions:


node374.html | unix.html | module-syslog.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.15.2 Resource Usage (node374.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.17 syslog (module-syslog.html)
---
# 8.16 nis --
Interface to Sun's NIS (Yellow Pages)
Availability: UNIX.
The nis module gives a thin wrapper around the NIS library, useful
for central administration of several hosts.
Because NIS exists only on Unix systems, this module is
only available for Unix.
The nis module defines the following functions:
The nis module defines the following exception:


11.11 nntplib -- NNTP protocol client

imap4-example.html | internet.html | nntp-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.10.2 IMAP4 Example (imap4-example.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.11.1 NNTP Objects (nntp-objects.html)
---
# 11.11 nntplib --
NNTP protocol client
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 (http://www.faqs.org/rfcs/rfc977.html).
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:
```text

>>> s = NNTP('news.cwi.nl')
>>> resp, count, first, last, name = s.group('comp.lang.python')
>>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
Group comp.lang.python has 59 articles, range 3742 to 3803
>>> resp, subs = s.xhdr('subject', first + '-' + last)
>>> for id, sub in subs[-10:]: print id, sub
...
3792 Re: Removing elements from a list while iterating...
3793 Re: Who likes Info files?
3794 Emacs and doc strings
3795 a few questions about the Mac implementation
3796 Re: executable python scripts
3797 Re: executable python scripts
3798 Re: a few questions about the Mac implementation
3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules
3802 Re: executable python scripts
3803 Re: \POSIX{} wait and SIGCHLD
>>> s.quit()
'205 news.cwi.nl closing connection. Goodbye.'
```
To post an article from a file (this assumes that the article has
valid headers):
```text

>>> s = NNTP('news.cwi.nl')
>>> f = open('/tmp/article')
>>> s.post(f)
'240 Article posted successfully.'
>>> s.quit()
'205 news.cwi.nl closing connection. Goodbye.'
```
The module itself defines the following items:


module-UserString.html | python.html | operator-map.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.9 UserString (module-UserString.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.10.1 Mapping Operators to (operator-map.html)
---
# 3.10 operator --
Standard operators as functions.
The operator module exports a set of functions implemented in C
corresponding to the intrinsic operators of Python. For example,
`operator.add(x, y)` is equivalent to the expression `x+y`. The
function names are those used for special class methods; variants without
leading and trailing "__" are also provided for convenience.
The functions fall into categories that perform object comparisons,
logical operations, mathematical operations, sequence operations, and
abstract type tests.
The object comparison functions are useful for all objects, and are
named after the rich comparison operators they support:
The logical operations are also generally applicable to all objects,
and support truth tests, identity tests, and boolean operations:
The mathematical and bitwise operations are the most numerous:
Operations which work with sequences include:
The operator module also defines a few predicates to test the
type of objects. Note:
Be careful not to misinterpret the
results of these functions; only isCallable() has any
measure of reliability with instance objects. For example:
```text

>>> class C:
... pass
...
>>> import operator
>>> o = C()
>>> operator.isMappingType(o)
1
```
Example: Build a dictionary that maps the ordinals from `0` to
`256` to their character equivalents.
```text

>>> import operator
>>> d = {}
>>> keys = range(256)
>>> vals = map(chr, keys)
>>> map(operator.setitem, [d]*len(keys), keys, vals)
```


module-getopt.html | allos.html | optparse-philosophy.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.19 getopt (module-getopt.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.20.1 Philosophy (optparse-philosophy.html)
---
# 6.20 optparse --
Powerful parser for command line options.
New in version 2.3.
The optparse module is a powerful, flexible, extensible,
easy-to-use command-line parsing library for Python. Using
optparse, you can add intelligent, sophisticated handling of
command-line options to your scripts with very little overhead.
Here's an example of using optparse to add some command-line
options to a simple script:
```text

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")

(options, args) = parser.parse_args()
```
With these few lines of code, users of your script can now do the
``usual thing'' on the command-line:
```text

$ <yourscript> -f outfile --quiet
$ <yourscript> -qfoutfile
$ <yourscript> --file=outfile -q
$ <yourscript> --quiet --file outfile
```
(All of these result in `options.filename == "outfile"` and
`options.verbose == False`, just as you might expect.)
Even niftier, users can run one of
```text

$ <yourscript> -h
$ <yourscript> --help
```
and optparse will print out a brief summary of your script's
options:
```text

usage: <yourscript> [options]

options:
-h, --help show this help message and exit
-fFILE, --file=FILE write report to FILE
-q, --quiet don't print status messages to stdout
```
That's just a taste of the flexibility optparse gives you in
parsing your command-line.


allos.html | allos.html | os-procinfo.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6. Generic Operating System (allos.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.1.1 Process Parameters (os-procinfo.html)
---
# 6.1 os --
Miscellaneous operating system interfaces
This module provides a more portable way of using operating system
dependent functionality than importing a operating system dependent
built-in module like posix (module-posix.html) or nt.
This module searches for an operating system dependent built-in module like
mac or posix (module-posix.html) and exports the same functions and data
as found there. The design of all Python's built-in operating system dependent
modules is such that as long as the same functionality is available,
it uses the same interface; for example, the function
`os.stat( path )` returns stat information about path in
the same format (which happens to have originated with the
POSIX interface).
Extensions peculiar to a particular operating system 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 operating system dependent built-in module,
so there should be no reason not to use os!
The os module contains many functions and data values.
The items below and in the following sub-sections are all available
directly from the os module.


os-path.html | allos.html | module-dircache.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.1.6 Miscellaneous System Information (os-path.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.3 dircache (module-dircache.html)
---
# 6.2 os.path --
Common pathname manipulations
This module implements some useful functions on pathnames.
Warning:
On Windows, many of these functions do not properly
support UNC pathnames. splitunc() and ismount()
do handle them correctly.


module-sndhdr.html | mmedia.html | ossaudio-device-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
14.10 sndhdr (module-sndhdr.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.11.1 Audio Device Objects (ossaudio-device-objects.html)
---
# 14.11 ossaudiodev --
Access to OSS-compatible audio devices
Availability: Linux, FreeBSD, possibly other Unix-like systems.
This module allows you to access the OSS (Open Sound System) audio
interface. OSS is available for a wide range of open-source and
commercial Unices, and is the standard audio interface for Linux and
recent versions of FreeBSD.
See Also:
The module defines a large number of constants supplied by
the OSS device driver; see `<sys/soundcard.h>` on either
Linux or FreeBSD for a listing .
ossaudiodev defines the following variables and functions:


language.html | language.html | node682.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
18. Python Language Services (language.html)
Up:
18. Python Language Services (language.html)
Next:
18.1.1 Creating AST Objects (node682.html)
---
# 18.1 parser --
Access Python parse trees
The parser module provides an interface to Python's internal
parser and byte-code compiler. The primary purpose for this interface
is to allow Python code to edit the parse tree of a Python expression
and create executable code from this. This is better than trying
to parse and modify an arbitrary Python code fragment as a string
because parsing is performed in a manner identical to the code
forming the application. It is also faster.
There are a few things to note about this module which are important
to making use of the data structures created. This is not a tutorial
on editing the parse trees for Python code, but some examples of using
the parser module are presented.
Most importantly, a good understanding of the Python grammar processed
by the internal parser is required. For full information on the
language syntax, refer to the Python
Language Reference (../ref/ref.html). The parser itself is created from a grammar
specification defined in the file Grammar/Grammar in the
standard Python distribution. The parse trees stored in the AST
objects created by this module are the actual output from the internal
parser when created by the expr() or suite()
functions, described below. The AST objects created by
sequence2ast() faithfully simulate those structures. Be
aware that the values of the sequences which are considered
``correct'' will vary from one version of Python to another as the
formal grammar for the language is revised. However, transporting
code from one Python version to another as source text will always
allow correct parse trees to be created in the target version, with
the only restriction being that migrating to an older version of the
interpreter will not support more recent language constructs. The
parse trees are not typically compatible from one version to another,
whereas source code has always been forward-compatible.
Each element of the sequences returned by ast2list() or
ast2tuple() has a simple form. Sequences representing
non-terminal elements in the grammar always have a length greater than
one. The first element is an integer which identifies a production in
the grammar. These integers are given symbolic names in the C header
file Include/graminit.h and the Python module
symbol (module-symbol.html). Each additional element of the sequence represents
a component of the production as recognized in the input string: these
are always sequences which have the same form as the parent. An
important aspect of this structure which should be noted is that
keywords used to identify the parent node type, such as the keyword
if in an if_stmt, are included in the node tree without
any special treatment. For example, the if keyword is
represented by the tuple `(1, 'if')`, where `1` is the
numeric value associated with all NAME tokens, including
variable and function names defined by the user. In an alternate form
returned when line number information is requested, the same token
might be represented as `(1, 'if', 12)`, where the `12`
represents the line number at which the terminal symbol was found.
Terminal elements are represented in much the same way, but without
any child elements and the addition of the source text which was
identified. The example of the if keyword above is
representative. The various types of terminal symbols are defined in
the C header file Include/token.h and the Python module
token (module-token.html).
The AST objects are not required to support the functionality of this
module, but are provided for three purposes: to allow an application
to amortize the cost of processing complex parse trees, to provide a
parse tree representation which conserves memory space when compared
to the Python list or tuple representation, and to ease the creation
of additional modules in C which manipulate parse trees. A simple
``wrapper'' class may be created in Python to hide the use of AST
objects.
The parser module defines functions for a few distinct
purposes. The most important purposes are to create AST objects and
to convert AST objects to other representations such as parse trees
and compiled code objects, but there are also functions which serve to
query the type of parse tree represented by an AST object.
See Also:


9. The Python Debugger

module-commands.html | lib.html | debugger-commands.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.18 commands (module-commands.html)
Up:
Python Library Reference (lib.html)
Next:
9.1 Debugger Commands (debugger-commands.html)
---
# 9. The Python Debugger
The module pdb defines an interactive source code
debuggerfor Python programs. It supports setting
(conditional) 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 the class
Pdb.
This is currently undocumented but easily understood by reading the
source. The extension interface uses the modules
bdb(undocumented) and
cmd (module-cmd.html).
The debugger's prompt is "(Pdb) ".
Typical usage to run a program under control of the debugger is:
```text

>>> import pdb
>>> import mymodule
>>> pdb.run('mymodule.test()')
> <string>(0)?()
(Pdb) continue
> <string>(1)?()
(Pdb) continue
NameError: 'spam'
> <string>(1)?()
(Pdb)
```
pdb.py can also be invoked as
a script to debug other scripts. For example:
```text

python /usr/local/lib/python1.5/pdb.py myscript.py
```
Typical usage to inspect a crashed program is:
```text

>>> import pdb
>>> import mymodule
>>> mymodule.test()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "./mymodule.py", line 4, in test
test2()
File "./mymodule.py", line 3, in test2
print spam
NameError: spam
>>> pdb.pm()
> ./mymodule.py(3)test2()
-> print spam
(Pdb)
```
The module defines the following functions; each enters the debugger
in a slightly different way:


module-linecache.html | python.html | node61.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.13 linecache (module-linecache.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.14.1 Relationship to other (node61.html)
---
# 3.14 pickle -- Python object serialization
The pickle module implements a fundamental, but powerful
algorithm for serializing and de-serializing a Python object
structure. ``Pickling'' is the process whereby a Python object
hierarchy is converted into a byte stream, and ``unpickling'' is the
inverse operation, whereby a byte stream is converted back into an
object hierarchy. Pickling (and unpickling) is alternatively known as
``serialization'', ``marshalling,''3.2 (#foot8168) or ``flattening'',
however, to avoid confusion, the terms used here are ``pickling'' and
``unpickling''.
This documentation describes both the pickle module and the
cPickle (module-cPickle.html) module.
---
#### Footnotes
... ``marshalling,''3.2 (module-pickle.html#tex2html14): Don't confuse this with
the marshal (module-marshal.html) module


module-fcntl.html | unix.html | template-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.12 fcntl (module-fcntl.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.13.1 Template Objects (template-objects.html)
---
# 8.13 pipes --
Interface to shell pipelines
Availability: Unix.
The pipes module defines a class to abstract the concept of
a pipeline -- a sequence of convertors from one file to
another.
Because the module uses /bin/sh command lines, a POSIX or
compatible shell for os.system() and os.popen()
is required.
The pipes module defines the following class:
Example:
```text

>>> import pipes
>>> t=pipes.Template()
>>> t.append('tr a-z A-Z', '--')
>>> f=t.open('/tmp/1', 'w')
>>> f.write('hello world')
>>> f.close()
>>> open('/tmp/1').read()
'HELLO WORLD'
```


examples-imp.html | python.html | module-code.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.21.1 Examples (examples-imp.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.23 code (module-code.html)
---
# 3.22 pkgutil --
Package extension utility
New in version 2.3.
Warning:
This is an experimental module. It may be withdrawn or completely
changed up to an including the release of Python 2.3 beta 1.
This module provides a single function:


dircmp-objects.html | allos.html | popen3-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.7.1 The dircmp class (dircmp-objects.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.8.1 Popen3 and Popen4 (popen3-objects.html)
---
# 6.8 popen2 --
Subprocesses with accessible I/O streams
Availability: Unix, Windows.
This module allows you to spawn processes and connect to their
input/output/error pipes and obtain their return codes under
Unix and Windows.
Note that starting with Python 2.0, this functionality is available
using functions from the os (module-os.html) module which have the same
names as the factory functions here, but the order of the return
values is more intuitive in the os (module-os.html) module variants.
The primary interface offered by this module is a trio of factory
functions. For each of these, if bufsize is specified,
it specifies the buffer size for the I/O pipes. mode, if
provided, should be the string `'b'` or `'t'`; on Windows
this is needed to determine whether the file objects should be opened
in binary or text mode. The default value for mode is
`'t'`.
The only way to retrieve the return codes for the child processes is
by using the poll() or wait() methods on the
Popen3 and Popen4 classes; these are only available on
Unix. This information is not available when using the
popen2(), popen3(), and popen4()
functions, or the equivalent functions in the os (module-os.html) module.
On Unix, a class defining the objects returned by the factory
functions is also available. These are not used for the Windows
implementation, and are not available on that platform.


11.9 poplib -- POP3 protocol client

module-gopherlib.html | internet.html | pop3-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.8 gopherlib (module-gopherlib.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.9.1 POP3 Objects (pop3-objects.html)
---
# 11.9 poplib --
POP3 protocol client
This module defines a class, POP3, which encapsulates a
connection to an POP3 server and implements the protocol as defined in
RFC 1725 (http://www.faqs.org/rfcs/rfc1725.html). The POP3 class supports both the minimal and
optional command sets.
Note that POP3, though widely supported, is obsolescent. The
implementation quality of POP3 servers varies widely, and too many are
quite poor. If your mailserver supports IMAP, you would be better off
using the `imaplib . IMAP4` class, as IMAP
servers tend to be better implemented.
A single class is provided by the poplib module:
One exception is defined as an attribute of the poplib module:
See Also:


unix.html | unix.html | posix-large-files.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8. Unix Specific Services (unix.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.1.1 Large File Support (posix-large-files.html)
---
# 8.1 posix --
The most common POSIX system calls
Availability: Unix.
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 (module-os.html), which provides a portable version of this
interface. On Unix, the os (module-os.html) 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 (module-os.html) interface. Once os (module-os.html) is
imported, there is no performance penalty in using it instead
of posix. In addition, os (module-os.html)provides some additional functionality, such as automatically calling
putenv() when an entry in `os.environ` is changed.
The descriptions below are very terse; refer to the corresponding
Unix manual (or POSIX documentation) 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
error (a synonym for the standard exception
OSError), described below.


template-objects.html | unix.html | module-resource.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.13.1 Template Objects (template-objects.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.15 resource (module-resource.html)
---
# 8.14 posixfile --
File-like objects with locking support
Availability: Unix.
Deprecated since release 1.5.
The locking operation that this module provides is
done better and more portably by the
fcntl (module-fcntl.html).lockf() call.
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.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 raise 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 characters for the flags() method have the following
meanings:
In addition the following modifiers can be added to the format:
Notes:
(1): The "!" and "=" modifiers are mutually exclusive.
(2): This string represents the flags after they may have been altered
by the same call.
Examples:


3.25 pprint -- Data pretty printer

module-codeop.html | python.html | node90.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.24 codeop (module-codeop.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.25.1 PrettyPrinter Objects (node90.html)
---
# 3.25 pprint --
Data pretty printer
The pprint module provides a capability to ``pretty-print''
arbitrary Python data structures in a form which can be used as input
to the interpreter. If the formatted structures include objects which
are not fundamental Python types, the representation may not be
loadable. This may be the case if objects such as files, sockets,
classes, or instances are included, as well as many other builtin
objects which are not representable as Python constants.
The formatted representation keeps objects on a single line if it can,
and breaks them onto multiple lines if they don't fit within the
allowed width. Construct PrettyPrinter objects explicitly if
you need to adjust the width constraint.
The pprint module defines one class:
The PrettyPrinter class supports several derivative functions:
One more support function is also defined:
```text

>>> pprint.saferepr(stuff)
"[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca
l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python
1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']"
```


10.5 Reference Manual

node385.html | profile.html | profile-stats.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
10.4 What Is Deterministic (node385.html)
Up:
10. The Python Profiler (profile.html)
Next:
10.5.1 The Stats Class (profile-stats.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.
Analysis of the profiler data is done using this class from the
pstats module:


8.11 pty -- Pseudo-terminal utilities

module-tty.html | unix.html | module-fcntl.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.10 tty (module-tty.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.12 fcntl (module-fcntl.html)
---
# 8.11 pty --
Pseudo-terminal utilities
Availability: IRIX, Linux.
The pty module defines operations for handling the
pseudo-terminal concept: starting another process and being able to
write to and read from its controlling terminal programmatically.
Because pseudo-terminal handling is highly platform dependant, there
is code to do it only for SGI and Linux. (The Linux code is supposed
to work on other platforms, but hasn't been tested yet.)
The pty module defines the following functions:


8.2 pwd -- The password database

posix-contents.html | unix.html | module-grp.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.1.2 Module Contents (posix-contents.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.3 grp (module-grp.html)
---
# 8.2 pwd --
The password database
Availability: Unix.
This module provides access to the Unix user account and password
database. It is available on all Unix versions.
Password database entries are reported as a tuple-like object, whose
attributes correspond to the members of the `passwd` structure
(Attribute field below, see `<pwd.h>`):
The uid and gid items are integers, all others are strings.
KeyError is raised if the entry asked for cannot be found.
Note:
In traditional Unix the field `pw_passwd` usually
contains a password encrypted with a DES derived algorithm (see module
crypt (module-crypt.html)). However most modern unices
use a so-called shadow password system. On those unices the
field `pw_passwd` only contains a asterisk (`'*'`) or the
letter "x" where the encrypted password is stored in a file
/etc/shadow which is not world readable.
It defines the following items:


module-tabnanny.html | language.html | pyclbr-class-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
18.6 tabnanny (module-tabnanny.html)
Up:
18. Python Language Services (language.html)
Next:
18.7.1 Class Descriptor Objects (pyclbr-class-objects.html)
---
# 18.7 pyclbr --
Python class browser support
The pyclbr can be used to determine some limited information
about the classes and methods defined in a module. The information
provided is sufficient to implement a traditional three-pane class
browser. The information is extracted from the source code rather
than from an imported module, so this module is safe to use with
untrusted source code. This restriction makes it impossible to use
this module with modules not implemented in Python, including many
standard and optional extension modules.


pyclbr-class-objects.html | language.html | module-compileall.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
18.7.1 Class Descriptor Objects (pyclbr-class-objects.html)
Up:
18. Python Language Services (language.html)
Next:
18.9 compileall (module-compileall.html)
---
# 18.8 py_compile --
Compile Python source files
The py_compile module provides a function to generate a
byte-code file from a source file, and another function used when the
module source file is invoked as a script.
Though not often needed, this function can be useful when installing
modules for shared use, especially if some of the users may not have
permission to write the byte-code cache files in the directory
containing the source code.
When this module is run as a script, the main() is used to
compile all the files named on the command line.


misc.html | misc.html | module-doctest.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5. Miscellaneous Services (misc.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.2 doctest (module-doctest.html)
---
# 5.1 pydoc --
Documentation generator and online help system
New in version 2.1.
The pydoc module automatically generates documentation from
Python modules. The documentation can be presented as pages of text
on the console, served to a Web browser, or saved to HTML files.
The built-in function help() invokes the online help system
in the interactive interpreter, which uses pydoc to generate
its documentation as text on the console. The same text documentation
can also be viewed from outside the Python interpreter by running
pydoc as a script at the operating system's command prompt.
For example, running
```text

pydoc sys
```
at a shell prompt will display documentation on the sys (module-sys.html)
module, in a style similar to the manual pages shown by the Unix
man command. The argument to pydoc can be the name
of a function, module, or package, or a dotted reference to a class,
method, or function within a module or module in a package. If the
argument to pydoc looks like a path (that is, it contains the
path separator for your operating system, such as a slash in Unix),
and refers to an existing Python source file, then documentation is
produced for that file.
Specifying a -w flag before the argument will cause HTML
documentation to be written out to a file in the current directory,
instead of displaying text on the console.
Specifying a -k flag before the argument will search the
synopsis lines of all available modules for the keyword given as the
argument, again in a manner similar to the Unix man
command. The synopsis line of a module is the first line of its
documentation string.
You can also use pydoc to start an HTTP server on the local
machine that will serve documentation to visiting Web browsers.
pydoc -p 1234 will start a HTTP server on port
1234, allowing you to browse the documentation at
`http://localhost:1234/` in your preferred Web browser.
pydoc -g will start the server and additionally
bring up a small Tkinter (module-Tkinter.html)-based graphical interface to help
you search for documentation pages.


7.8 Queue -- A synchronized queue class

module-dummythreading.html | someos.html | QueueObjects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.7 dummy_threading (module-dummythreading.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.8.1 Queue Objects (QueueObjects.html)
---
# 7.8 Queue --
A synchronized queue class
The Queue module implements a multi-producer, multi-consumer
FIFO queue. It is especially useful in threads programming when
information must be exchanged safely between multiple threads. The
Queue class in this module implements all the required locking
semantics. It depends on the availability of thread support in
Python.
See Also:
The Queue module defines the following class and exception:


binhex-notes.html | netdata.html | module-uu.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.14.1 Notes (binhex-notes.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.16 uu (module-uu.html)
---
# 12.15 quopri --
Encode and decode MIME quoted-printable data
This module performs quoted-printable transport encoding and decoding,
as defined in RFC 1521 (http://www.faqs.org/rfcs/rfc1521.html): ``MIME (Multipurpose Internet Mail
Extensions) Part One: Mechanisms for Specifying and Describing the
Format of Internet Message Bodies''. The quoted-printable encoding is
designed for data where there are relatively few nonprintable
characters; the base64 encoding scheme available via the
base64 (module-base64.html) module is more compact if there are many such
characters, as when sending a graphics file.


module-cmath.html | misc.html | module-whrandom.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.6 cmath (module-cmath.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.8 whrandom (module-whrandom.html)
---
# 5.7 random --
Generate pseudo-random numbers
This module implements pseudo-random number generators for various
distributions.
For integers, uniform selection from a range.
For sequences, uniform selection of a random element, a function to
generate a random permutation of a list in-place, and a function for
random sampling without replacement.
On the real line, there are functions to compute uniform, normal (Gaussian),
lognormal, negative exponential, gamma, and beta distributions.
For generating distributions of angles, the von Mises distribution
is available.
Almost all module functions depend on the basic function
random(), which generates a random float uniformly in
the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as
the core generator. It produces 53-bit precision floats and has a
period of 2**19937-1. The underlying implementation in C
is both fast and threadsafe. The Mersenne Twister is one of the most
extensively tested random number generators in existence. However, being
completely deterministic, it is not suitable for all purposes, and is
completely unsuitable for cryptographic purposes.
The functions supplied by this module are actually bound methods of a
hidden instance of the random.Random class. You can
instantiate your own instances of Random to get generators
that don't share state. This is especially useful for multi-threaded
programs, creating a different instance of Random for each
thread, and using the jumpahead() method to ensure that the
generated sequences seen by each thread don't overlap.
Class Random can also be subclassed if you want to use a
different basic generator of your own devising: in that case, override
the random(), seed(), getstate(),
setstate() and jumpahead() methods.
As an example of subclassing, the random module provides
the WichmannHill class which implements an alternative generator
in pure Python. The class provides a backward compatible way to
reproduce results from earlier versions of Python which used the
Wichmann-Hill algorithm as the core generator.
Changed in version 2.3:
Substituted MersenneTwister for Wichmann-Hill.
Bookkeeping functions:
Functions for integers:
Functions for sequences:
The following functions generate specific real-valued distributions.
Function parameters are named after the corresponding variables in the
distribution's equation, as used in common mathematical practice; most of
these equations can be found in any statistics text.
Alternative Generator


4.2 re -- Regular expression operations

module-string.html | strings.html | re-syntax.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.1 string (module-string.html)
Up:
4. String Services (strings.html)
Next:
4.2.1 Regular Expression Syntax (re-syntax.html)
---
# 4.2 re --
Regular expression operations
This module provides regular expression matching operations similar to
those found in Perl. Regular expression pattern strings may not
contain null bytes, but can specify the null byte using the
`\ number` notation. Both patterns and strings to be
searched can be Unicode strings as well as 8-bit strings. The
re module is always available.
Regular expressions use the backslash character ("\") to
indicate special forms or to allow special characters to be used
without invoking their special meaning. This collides with Python's
usage of the same character for the same purpose in string literals;
for example, to match a literal backslash, one might have to write
`'\\\\'` as the pattern string, because the regular expression
must be "\\", and each backslash must be expressed as
"\\" inside a regular Python string literal.
The solution is to use Python's raw string notation for regular
expression patterns; backslashes are not handled in any special way in
a string literal prefixed with "r". So `r"\n"` is a
two-character string containing "\" and "n",
while `"\n"` is a one-character string containing a newline.
Usually patterns will be expressed in Python code using this raw
string notation.
See Also:


7.20 readline -- GNU readline interface

tar-examples.html | someos.html | readline-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.19.3 Examples (tar-examples.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.20.1 Example (readline-example.html)
---
# 7.20 readline --
GNU readline interface
Availability: Unix.
The readline module defines a number of functions used either
directly or from the rlcompleter (module-rlcompleter.html) module to facilitate
completion and history file read and write from the Python
interpreter.
The readline module defines the following functions:
See Also:


node90.html | python.html | Repr-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.25.1 PrettyPrinter Objects (node90.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.26.1 Repr Objects (Repr-objects.html)
---
# 3.26 repr --
Alternate repr() implementation
The repr module provides a means for producing object
representations with limits on the size of the resulting strings.
This is used in the Python debugger and may be useful in other
contexts as well.
This module provides a class, an instance, and a function:


module-posixfile.html | unix.html | node373.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.14 posixfile (module-posixfile.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.15.1 Resource Limits (node373.html)
---
# 8.15 resource --
Resource usage information
Availability: Unix.
This module provides basic mechanisms for measuring and controlling
system resources utilized by a program.
Symbolic constants are used to specify particular system resources and
to request usage information about either the current process or its
children.
A single exception is defined for errors:


restricted.html | restricted.html | rexec-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
17. Restricted Execution (restricted.html)
Up:
17. Restricted Execution (restricted.html)
Next:
17.1.1 RExec Objects (rexec-objects.html)
---
# 17.1 rexec --
Restricted execution framework
Changed in version 2.3:
Disabled module.
Warning:
The documentation has been left in place to help in reading old code
that uses the module.
This module contains the RExec class, which supports
r_eval(), r_execfile(), r_exec(), and
r_import() methods, which are restricted versions of the standard
Python functions eval(), execfile() and
the exec and import statements.
Code executed in this restricted environment will
only have access to modules and functions that are deemed safe; you
can subclass RExec to add or remove capabilities as desired.
Warning:
While the rexec module is designed to perform as described
below, it does have a few known vulnerabilities which could be
exploited by carefully written code. Thus it should not be relied
upon in situations requiring ``production ready'' security. In such
situations, execution via sub-processes or very careful
``cleansing'' of both code and data to be processed may be
necessary. Alternatively, help in patching known rexec
vulnerabilities would be welcomed.
Note:
The RExec class can prevent code from performing unsafe
operations like reading or writing disk files, or using TCP/IP
sockets. However, it does not protect against code using extremely
large amounts of memory or processor time.
It is important to be aware that code running in a restricted
environment can still call the sys.exit() function. To
disallow restricted code from exiting the interpreter, always protect
calls that cause restricted code to run with a
try/except statement that catches the
SystemExit exception. Removing the sys.exit()
function from the restricted environment is not sufficient -- the
restricted code could still use `raise SystemExit`. Removing
SystemExit is not a reasonable option; some library code
makes use of this and would break were it not available.
See Also:


multifile-example.html | netdata.html | message-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.10.2 MultiFile Example (multifile-example.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.11.1 Message Objects (message-objects.html)
---
# 12.11 rfc822 --
Parse RFC 2822 mail headers
Deprecated since release 2.3.
The email (module-email.html) package should be used in
preference to the rfc822 module. This
module is present only to maintain backward
compatibility.
This module defines a class, Message, which represents an
``email message'' as defined by the Internet standard
RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html).12.5 (#foot52371) Such messages
consist of a collection of message headers, and a message body. This
module also defines a helper class
AddressList for parsing RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) addresses. Please refer to
the RFC for information on the specific syntax of RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) messages.
The mailbox (module-mailbox.html)module provides classes
to read mailboxes produced by various end-user mail programs.
See Also:
---
#### Footnotes
...2822.12.5 (module-rfc822.html#tex2html127): This module originally conformed to RFC 822 (http://www.faqs.org/rfcs/rfc822.html),
hence the name. Since then, RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) has been released as an
update to RFC 822 (http://www.faqs.org/rfcs/rfc822.html). This module should be considered
RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html)-conformant, especially in cases where the
syntax or semantics have changed since RFC 822 (http://www.faqs.org/rfcs/rfc822.html).


module-colorsys.html | mmedia.html | module-imghdr.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
14.7 colorsys (module-colorsys.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.9 imghdr (module-imghdr.html)
---
# 14.8 rgbimg --
Read and write ``SGI RGB'' files
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
enough in some cases. Currently, colormap files are not supported.
Note:
This module is only built by default for 32-bit platforms; it is
not expected to work properly on other systems.
The module defines the following variables and functions:


readline-example.html | someos.html | completer-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.20.1 Example (readline-example.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.21.1 Completer Objects (completer-objects.html)
---
# 7.21 rlcompleter --
Completion function for GNU readline
Availability: Unix.
The rlcompleter module defines a completion function for
the readline (module-readline.html) module by completing valid Python identifiers
and keywords.
This module is Unix-specific due to its dependence on the
readline (module-readline.html) module.
The rlcompleter module defines the Completer class.
Example:
```text

>>> import rlcompleter
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> readline. <TAB PRESSED>
readline.__doc__ readline.get_line_buffer readline.read_init_file
readline.__file__ readline.insert_text readline.set_completer
readline.__name__ readline.parse_and_bind
>>> readline.
```
The rlcompleter module is designed for use with Python's
interactive mode. A user can add the following lines to his or her
initialization file (identified by the PYTHONSTARTUP
environment variable) to get automatic Tab completion:
```text

try:
import readline
except ImportError:
print "Module readline not available."
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
```


netrc-objects.html | netdata.html | module-csv.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.18.1 netrc Objects (netrc-objects.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.20 csv (module-csv.html)
---
# 12.19 robotparser --
Parser for robots.txt
This module provides a single class, RobotFileParser, which answers
questions about whether or not a particular user agent can fetch a URL on
the Web site that published the robots.txt file. For more details on
the structure of robots.txt files, see
http://www.robotstxt.org/wc/norobots.html.
The following example demonstrates basic use of the RobotFileParser class.


module-mpz.html | crypto.html | tkinter.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
15.4 mpz (module-mpz.html)
Up:
15. Cryptographic Services (crypto.html)
Next:
16. Graphical User Interfaces (tkinter.html)
---
# 15.5 rotor --
Enigma-like encryption and decryption
Deprecated since release 2.3.
The encryption algorithm is insecure.
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:
```text

>>> import rotor
>>> rt = rotor.newrotor('key', 12)
>>> rt.encrypt('bar')
'\xab4\xf3'
>>> rt.encryptmore('bar')
'\xef\xfd$'
>>> rt.encrypt('bar')
'\xab4\xf3'
>>> rt.decrypt('\xab4\xf3')
'bar'
>>> rt.decryptmore('\xef\xfd$')
'bar'
>>> rt.decrypt('\xef\xfd$')
'l(\xcd'
>>> del rt
```
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 skillful 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.


6.11 sched -- Event scheduler

module-time.html | allos.html | scheduler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.10 time (module-time.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.11.1 Scheduler Objects (scheduler-objects.html)
---
# 6.11 sched --
Event scheduler
The sched module defines a class which implements a general
purpose event scheduler:
Example:
```text

>>> import sched, time
>>> s=sched.scheduler(time.time, time.sleep)
>>> def print_time(): print "From print_time", time.time()
...
>>> def print_some_times():
... print time.time()
... s.enter(5, 1, print_time, ())
... s.enter(10, 1, print_time, ())
... s.run()
... print time.time()
...
>>> print_some_times()
930343690.257
From print_time 930343695.274
From print_time 930343700.273
930343700.276
```


node658.html | tkinter.html | module-turtle.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
16.2.3 Tix Commands (node658.html)
Up:
16. Graphical User Interfaces (tkinter.html)
Next:
16.4 turtle (module-turtle.html)
---
# 16.3 ScrolledText --
Scrolled Text Widget
Availability: Tk.
The ScrolledText module provides a class of the same name
which implements a basic text widget which has a vertical scroll bar
configured to do the ``right thing.'' Using the ScrolledText
class is a lot easier than setting up a text widget and scroll bar
directly. The constructor is the same as that of the
Tkinter.Text class.
The text widget and scrollbar are packed together in a Frame,
and the methods of the Grid and Pack geometry managers
are acquired from the Frame object. This allows the
ScrolledText widget to be used directly to achieve most normal
geometry management behavior.
Should more specific control be necessary, the following attributes
are available:


socket-example.html | someos.html | poll-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.2.3 Example (socket-example.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.3.1 Polling Objects (poll-objects.html)
---
# 7.3 select --
Waiting for I/O completion
This module provides access to the select()
and poll() functions
available in most operating systems. Note that on Windows, it only
works for sockets; on other operating systems, it also works for other
file types (in particular, on Unix, it works on pipes). It cannot
be used on regular files to determine whether a file has grown since
it was last read.
The module defines the following:


module-array.html | misc.html | set-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.11 array (module-array.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.12.1 Set Objects (set-objects.html)
---
# 5.12 sets --
Unordered collections of unique elements
New in version 2.3.
The sets module provides classes for constructing and manipulating
unordered collections of unique elements. Common uses include membership
testing, removing duplicates from a sequence, and computing standard math
operations on sets such as intersection, union, difference, and symmetric
difference.
Like other collections, sets support `x in set`,
`len( set )`, and `for x in set`. Being an
unordered collection, sets do not record element position or order of
insertion. Accordingly, sets do not support indexing, slicing, or
other sequence-like behavior.
Most set applications use the Set class which provides every set
method except for __hash__(). For advanced applications requiring
a hash method, the ImmutableSet class adds a __hash__()
method but omits methods which alter the contents of the set. Both
Set and ImmutableSet derive from BaseSet, an
abstract class useful for determining whether something is a set:
`isinstance( obj , BaseSet)`.
The set classes are implemented using dictionaries. As a result, sets
cannot contain mutable elements such as lists or dictionaries.
However, they can contain immutable collections such as tuples or
instances of ImmutableSet. For convenience in implementing
sets of sets, inner sets are automatically converted to immutable
form, for example, `Set([Set(['dog'])])` is transformed to
`Set([ImmutableSet(['dog'])])`.


13.2 sgmllib -- Simple SGML parser

htmlparser-example.html | markup.html | module-htmllib.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.1.1 Example HTML Parser (htmlparser-example.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.3 htmllib (module-htmllib.html)
---
# 13.2 sgmllib --
Simple SGML parser
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 base for the htmllib (module-htmllib.html) module. Another
HTML parser which supports XHTML and offers a somewhat different
interface is available in the HTMLParser (module-HTMLParser.html) module.
SGMLParser instances have 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:


module-md5.html | crypto.html | module-mpz.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
15.2 md5 (module-md5.html)
Up:
15. Cryptographic Services (crypto.html)
Next:
15.4 mpz (module-mpz.html)
---
# 15.3 sha --
SHA message digest algorithm
This module implements the interface to NIST'ssecure hash
algorithm,known as SHA. It is used in
the same way as the md5 (module-md5.html) module: use new()
to create an sha object, then feed this object with arbitrary strings
using the update() method, and at any point you can ask it
for the digest of the concatenation of the strings fed to it
so far. SHA digests are 160 bits instead of
MD5's 128 bits.
The following values are provided as constants in the module and as
attributes of the sha objects returned by new():
An sha object has the same methods as md5 objects:


module-copyreg.html | python.html | node74.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.16 copy_reg (module-copyreg.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.17.1 Restrictions (node74.html)
---
# 3.17 shelve --
Python object persistence
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-pickle.html) module can handle. This includes most class
instances, recursive data types, and objects containing lots of shared
sub-objects. The keys are ordinary strings.
Shelve objects support all methods supported by dictionaries. This eases
the transition from dictionary based scripts to those requiring persistent
storage.


5.19 shlex -- Simple lexical analysis

Cmd-objects.html | misc.html | node180.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.18.1 Cmd Objects (Cmd-objects.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.19.1 Module Contents (node180.html)
---
# 5.19 shlex --
Simple lexical analysis
New in version 1.5.2.
The shlex class makes it easy to write lexical analyzers for
simple syntaxes resembling that of the Unix shell. This will often
be useful for writing minilanguages, (e.g. in run control files for
Python applications) or for parsing quoted strings.
See Also:


module-fnmatch.html | allos.html | shutil-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.24 fnmatch (module-fnmatch.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.25.1 Example (shutil-example.html)
---
# 6.25 shutil --
High-level file operations
The shutil module offers a number of high-level operations on
files and collections of files. In particular, functions are provided
which support file copying and removal.
Caveat: On MacOS, the resource fork and other metadata are
not used. For file copies, this means that resources will be lost and
file type and creator codes will not be correct.


someos.html | someos.html | node304.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7. Optional Operating System (someos.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.1.1 Example (node304.html)
---
# 7.1 signal --
Set handlers for asynchronous events
This module provides mechanisms to use signal handlers in Python.
Some general rules for working with signals and their handlers:
- A handler for a particular signal, once set, remains installed until
it is explicitly reset (Python emulates the BSD style interface
regardless of the underlying implementation), with the exception of
the handler for SIGCHLD, which follows the underlying
implementation.
- 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
(such as 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) and SIGINT is translated
into a KeyboardInterrupt exception. 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 inter-thread
communication. Use locks instead.
The variables defined in the signal module are:
The signal module defines the following functions:


module-BaseHTTPServer.html | internet.html | module-CGIHTTPServer.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.16 BaseHTTPServer (module-BaseHTTPServer.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.18 CGIHTTPServer (module-CGIHTTPServer.html)
---
# 11.17 SimpleHTTPServer --
Simple HTTP request handler
The SimpleHTTPServer module defines a request-handler class,
interface compatible with BaseHTTPServer.BaseHTTPRequestHandler
which serves files only from a base directory.
The SimpleHTTPServer module defines the following class:
The SimpleHTTPRequestHandler defines the following member
variables:
The SimpleHTTPRequestHandler defines the following methods:


xmlrpc-client-example.html | internet.html | simple-xmlrpc-servers.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.20.8 Example of Client (xmlrpc-client-example.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.21.1 SimpleXMLRPCServer Objects (simple-xmlrpc-servers.html)
---
# 11.21 SimpleXMLRPCServer --
Basic XML-RPC server
The SimpleXMLRPCServer module provides a basic server
framework for XML-RPC servers written in Python. Servers can either
be free standing, using SimpleXMLRPCServer, or embedded in a
CGI environment, using CGIXMLRPCRequestHandler.


module-new.html | python.html | module-user.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.27 new (module-new.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.29 user (module-user.html)
---
# 3.28 site --
Site-specific configuration hook
This module is automatically imported during initialization.
In earlier versions of Python (up to and including 1.5a3), scripts or
modules that needed to use site-specific modules would place
"import site" somewhere near the top of their code. This is no
longer necessary.
This will append site-specific paths to the module search path.
It starts by constructing up to four directories from a head and a
tail part. For the head part, it uses `sys.prefix` and
`sys.exec_prefix`; empty heads are skipped. For
the tail part, it uses the empty string (on Macintosh or Windows) or
it uses first lib/python2.3/site-packages and then
lib/site-python (on Unix). For each of the distinct
head-tail combinations, it sees if it refers to an existing directory,
and if so, adds it to `sys.path` and also inspects the newly added
path for configuration files.
A path configuration file is a file whose name has the form
package.pth; its contents are additional items (one
per line) to be added to `sys.path`. Non-existing items are
never added to `sys.path`, but no check is made that the item
refers to a directory (rather than a file). No item is added to
`sys.path` more than once. Blank lines and lines beginning with
`#` are skipped. Lines starting with `import` are executed.
For example, suppose `sys.prefix` and `sys.exec_prefix` are
set to /usr/local. The Python 2.3 library is then
installed in /usr/local/lib/python2.3 (where only the
first three characters of `sys.version` are used to form the
installation path name). Suppose this has a subdirectory
/usr/local/lib/python2.3/site-packages with three
subsubdirectories, foo, bar and spam, and two
path configuration files, foo.pth and bar.pth. Assume
foo.pth contains the following:
```text

# foo package configuration

foo
bar
bletch
```
and bar.pth contains:
```text

# bar package configuration

bar
```
Then the following directories are added to `sys.path`, in this
order:
```text

/usr/local/lib/python2.3/site-packages/bar
/usr/local/lib/python2.3/site-packages/foo
```
Note that bletch is omitted because it doesn't exist; the
bar directory precedes the foo directory because
bar.pth comes alphabetically before foo.pth; and
spam is omitted because it is not mentioned in either path
configuration file.
After these path manipulations, an attempt is made to import a module
named sitecustomize, which can
perform arbitrary site-specific customizations. If this import fails
with an ImportError exception, it is silently ignored.


11.12 smtplib -- SMTP protocol client

nntp-objects.html | internet.html | SMTP-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.11.1 NNTP Objects (nntp-objects.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.12.1 SMTP Objects (SMTP-objects.html)
---
# 11.12 smtplib --
SMTP protocol client
The smtplib module defines an SMTP client session object that
can be used to send mail to any Internet machine with an SMTP or ESMTP
listener daemon. For details of SMTP and ESMTP operation, consult
RFC 821 (http://www.faqs.org/rfcs/rfc821.html) (Simple Mail Transfer Protocol) and RFC 1869 (http://www.faqs.org/rfcs/rfc1869.html)
(SMTP Service Extensions).
A nice selection of exceptions is defined as well:
See Also:


module-imghdr.html | mmedia.html | module-ossaudiodev.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
14.9 imghdr (module-imghdr.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.11 ossaudiodev (module-ossaudiodev.html)
---
# 14.10 sndhdr --
Determine type of sound file
The sndhdr provides utility functions which attempt to
determine the type of sound data which is in a file. When these
functions are able to determine what type of sound data is stored in a
file, they return a tuple `( type , sampling_rate , channels , frames , bits_per_sample )`. The value for
type indicates the data type and will be one of the strings
`'aifc'`, `'aiff'`, `'au'`, `'hcom'`,
`'sndr'`, `'sndt'`, `'voc'`, `'wav'`,
`'8svx'`, `'sb'`, `'ub'`, or `'ul'`. The
sampling_rate will be either the actual value or `0` if
unknown or difficult to decode. Similarly, channels will be
either the number of channels or `0` if it cannot be determined
or if the value is difficult to decode. The value for frames
will be either the number of frames or `-1`. The last item in
the tuple, bits_per_sample, will either be the sample size in
bits or `'A'` for A-LAWor `'U'` for
u-LAW.


node304.html | someos.html | socket-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.1.1 Example (node304.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.2.1 Socket Objects (socket-objects.html)
---
# 7.2 socket --
Low-level networking interface
This module provides access to the BSD socket interface.
It is available on all modern Unix systems, Windows, MacOS, BeOS,
OS/2, and probably additional platforms.
For an introduction to socket programming (in C), see the following
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 platform-specific reference material
for the various socket-related system calls are also a valuable source
of information on the details of socket semantics. For Unix, refer
to the manual pages; for Windows, see the WinSock (or Winsock 2)
specification.
For IPv6-ready APIs, readers may want to refer to RFC 2553 (http://www.faqs.org/rfcs/rfc2553.html) titled
Basic Socket Interface Extensions for IPv6.
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
higher-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 follows:
A single string is used for the AF_UNIX address family.
A pair `( host , port )` is used 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 IPv4 address like `'100.50.200.5'`,
and port is an integral port number.
For AF_INET6 address family, a four-tuple
`( host , port , flowinfo , scopeid )` is
used, where flowinfo and scopeid represents
`sin6_flowinfo` and `sin6_scope_id` member in
struct sockaddr_in6 in C.
For socket module methods, flowinfo and scopeid
can be omitted just for backward compatibility. Note, however,
omission of scopeid can cause problems in manipulating scoped
IPv6 addresses. 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.
For IPv4 addresses, two special forms are accepted instead of a host
address: the empty string represents INADDR_ANY, and the string
`'<broadcast>'` represents INADDR_BROADCAST.
The behavior is not available for IPv6 for backward compatibility,
therefore, you may want to avoid these if you intend to support IPv6 with
your Python programs.
If you use a hostname in the host portion of IPv4/v6 socket
address, the program may show a nondeterministic behavior, as Python
uses the first address returned from the DNS resolution. The socket
address will be resolved differently into an actual IPv4/v6 address,
depending on the results from DNS resolution and/or the host
configuration. For deterministic behavior use a numeric address in
host portion.
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
setblocking(). A generalization of this based on timeouts
is supported through settimeout().
The module socket exports the following constants and functions:
See Also: