3.15 cPickle -- A faster pickle

pickle-example.html | python.html | module-copyreg.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.14.7 Example (pickle-example.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.16 copy_reg (module-copyreg.html)
---
# 3.15 cPickle -- A faster pickle
The cPickle module supports serialization and
de-serialization of Python objects, providing an interface and
functionality nearly identical to the
pickle (module-pickle.html)module. There are several
differences, the most important being performance and subclassability.
First, cPickle can be up to 1000 times faster than
pickle because the former is implemented in C. Second, in
the cPickle module the callables Pickler() and
Unpickler() are functions, not classes. This means that
you cannot use them to derive custom pickling and unpickling
subclasses. Most applications have no need for this functionality and
should benefit from the greatly improved performance of the
cPickle module.
The pickle data stream produced by pickle and
cPickle are identical, so it is possible to use
pickle and cPickle interchangeably with existing
pickles3.11 (#foot8163).
There are additional minor differences in API between cPickle
and pickle, however for most applications, they are
interchangable. More documentation is provided in the
pickle module documentation, which
includes a list of the documented differences.


module-grp.html | unix.html | module-dl.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.3 grp (module-grp.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.5 dl (module-dl.html)
---
# 8.4 crypt --
Function to check Unix passwords
Availability: Unix.
This module implements an interface to the
crypt(3)routine, which is a one-way hash
function based upon a modified DES algorithm; see
the Unix man page for further details. Possible uses include
allowing Python scripts to accept typed passwords from the user, or
attempting to crack Unix passwords with a dictionary.
A simple example illustrating typical use:


module-StringIO.html | strings.html | module-textwrap.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.6 StringIO (module-StringIO.html)
Up:
4. String Services (strings.html)
Next:
4.8 textwrap (module-textwrap.html)
---
# 4.7 cStringIO --
Faster version of StringIO
The module cStringIO provides an interface similar to that of
the StringIO (module-StringIO.html) module. Heavy use of StringIO.StringIO
objects can be made more efficient by using the function
StringIO() from this module instead.
Since this module provides a factory function which returns objects of
built-in types, there's no way to build your own version using
subclassing. Use the original StringIO (module-StringIO.html) module in that case.
Unlike the memory files implemented by the StringIO (module-StringIO.html)
module, those provided by this module are not able to accept Unicode
strings that cannot be encoded as plain ASCII strings.
Another difference from the StringIO (module-StringIO.html) module is that calling
StringIO() with a string parameter creates a read-only object.
Unlike an object created without a string parameter, it does not have
write methods.
The following data objects are provided as well:


module-robotparser.html | netdata.html | node545.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.19 robotparser (module-robotparser.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.20.1 Module Contents (node545.html)
---
# 12.20 csv -- CSV File Reading and Writing
New in version 2.3.
The so-called CSV (Comma Separated Values) format is the most common import
and export format for spreadsheets and databases. There is no ``CSV
standard'', so the format is operationally defined by the many applications
which read and write it. The lack of a standard means that subtle
differences often exist in the data produced and consumed by different
applications. These differences can make it annoying to process CSV files
from multiple sources. Still, while the delimiters and quoting characters
vary, the overall format is similar enough that it is possible to write a
single module which can efficiently manipulate such data, hiding the details
of reading and writing the data from the programmer.
The csv module implements classes to read and write tabular data in
CSV format. It allows programmers to say, ``write this data in the format
preferred by Excel,'' or ``read data from this file which was generated by
Excel,'' without knowing the precise details of the CSV format used by
Excel. Programmers can also describe the CSV formats understood by other
applications or define their own special-purpose CSV formats.
The csv module's reader and writer objects read and
write sequences. Programmers can also read and write data in dictionary
form using the DictReader and DictWriter classes.
Note:
This version of the csv module doesn't support Unicode
input. Also, there are currently some issues regarding ASCII NUL
characters. Accordingly, all input should generally be printable
ASCII to be safe. These restrictions will be removed in the future.
See Also:


module-curses.wrapper.html | allos.html | module-curses.panel.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.16 curses.wrapper (module-curses.wrapper.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.18 curses.panel (module-curses.panel.html)
---
# 6.17 curses.ascii --
Utilities for ASCII characters
New in version 1.6.
The curses.ascii module supplies name constants for
ASCII characters and functions to test membership in various
ASCII character classes. The constants supplied are names for
control characters as follows:
Note that many of these have little practical significance in modern
usage. The mnemonics derive from teleprinter conventions that predate
digital computers.
The module supplies the following functions, patterned on those in the
standard C library:
These functions accept either integers or strings; when the argument
is a string, it is first converted using the built-in function
ord().
Note that all these functions check ordinal bit values derived from the
first character of the string you pass in; they do not actually know
anything about the host machine's character encoding. For functions
that know about the character encoding (and handle
internationalization properly) see the string (module-string.html) module.
The following two functions take either a single-character string or
integer byte value; they return a value of the same type.
The following function takes either a single-character string or
integer value; it returns a string.


module-getpass.html | allos.html | curses-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.13 getpass (module-getpass.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.14.1 Functions (curses-functions.html)
---
# 6.14 curses --
Terminal handling for character-cell displays
Changed in version 1.6:
Added support for the `ncurses` library and
converted to a package.
The curses module provides an interface to the curses
library, the de-facto standard for portable advanced terminal
handling.
While curses is most widely used in the Unix environment, versions
are available for DOS, OS/2, and possibly other systems as well. This
extension module is designed to match the API of ncurses, an
open-source curses library hosted on Linux and the BSD variants of
Unix.
See Also:
The Demo/curses/ directory in the Python source
distribution contains some example programs using the
curses bindings provided by this module.


module-curses.ascii.html | allos.html | cursespanel-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.17 curses.ascii (module-curses.ascii.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.18.1 Functions (cursespanel-functions.html)
---
# 6.18 curses.panel --
A panel stack extension for curses.
Panels are windows with the added feature of depth, so they can be
stacked on top of each other, and only the visible portions of
each window will be displayed. Panels can be added, moved up
or down in the stack, and removed.


node218.html | allos.html | curses-textpad-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.14.3 Constants (node218.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.15.1 Textbox objects (curses-textpad-objects.html)
---
# 6.15 curses.textpad --
Text input widget for curses programs
New in version 1.6.
The curses.textpad module provides a Textbox class
that handles elementary text editing in a curses window, supporting a
set of keybindings resembling those of Emacs (thus, also of Netscape
Navigator, BBedit 6.x, FrameMaker, and many other programs). The
module also provides a rectangle-drawing function useful for framing
text boxes or for other purposes.
The module curses.textpad defines the following function:


curses-textpad-objects.html | allos.html | module-curses.ascii.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.15.1 Textbox objects (curses-textpad-objects.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.17 curses.ascii (module-curses.ascii.html)
---
# 6.16 curses.wrapper --
Terminal handler for curses programs
New in version 1.6.
This module supplies one function, wrapper(), which runs
another function which should be the rest of your curses-using
application. If the application raises an exception,
wrapper() will restore the terminal to a sane state before
passing it further up the stack and generating a traceback.


popen2-flow-control.html | allos.html | node202.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.8.2 Flow Control Issues (popen2-flow-control.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.9.1 Available Types (node202.html)
---
# 6.9 datetime --
Basic date and time types
New in version 2.3.
The datetime module supplies classes for manipulating dates
and times in both simple and complex ways. While date and time
arithmetic is supported, the focus of the implementation is on
efficient member extraction for output formatting and manipulation.
There are two kinds of date and time objects: ``naive'' and ``aware''.
This distinction refers to whether the object has any notion of time
zone, daylight saving time, or other kind of algorithmic or political
time adjustment. Whether a naive datetime object represents
Coordinated Universal Time (UTC), local time, or time in some other
timezone is purely up to the program, just like it's up to the program
whether a particular number represents meters, miles, or mass. Naive
datetime objects are easy to understand and to work with, at
the cost of ignoring some aspects of reality.
For applications requiring more, datetime and time
objects have an optional time zone information member,
tzinfo, that can contain an instance of a subclass of
the abstract tzinfo class. These tzinfo objects
capture information about the offset from UTC time, the time zone
name, and whether Daylight Saving Time is in effect. Note that no
concrete tzinfo classes are supplied by the datetime
module. Supporting timezones at whatever level of detail is required
is up to the application. The rules for time adjustment across the
world are more political than rational, and there is no standard
suitable for every application.
The datetime module exports the following constants:
See Also:


module-anydbm.html | someos.html | dbhash-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.10 anydbm (module-anydbm.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.11.1 Database Objects (dbhash-objects.html)
---
# 7.11 dbhash --
DBM-style interface to the BSD database library
Availability: Unix, Windows.
The dbhash module provides a function to open databases using
the BSD `db` library. This module mirrors the interface of the
other Python database modules that provide access to DBM-style
databases. The bsddb (module-bsddb.html)module is required
to use dbhash.
This module provides an exception and a function:
See Also:


dl-objects.html | unix.html | module-gdbm.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.5.1 Dl Objects (dl-objects.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.7 gdbm (module-gdbm.html)
---
# 8.6 dbm --
Simple ``database'' interface
Availability: Unix.
The dbm module provides an interface to the Unix
(`n`)`dbm` library. Dbm objects behave like mappings
(dictionaries), except that keys and values are always strings.
Printing a dbm object doesn't print the keys and values, and the
items() and values() methods are not supported.
This module can be used with the ``classic'' ndbm interface, the BSD
DB compatibility interface, or the GNU GDBM compatibility interface.
On Unix, the configure script will attempt to locate the
appropriate header file to simplify building this module.
The module defines the following:


module-gl.html | sgi.html | module-gl-constants.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.8 gl (module-gl.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.10 GL (module-gl-constants.html)
---
# 20.9 DEVICE --
Constants used with the gl module
Availability: IRIX.
This modules defines the constants used by the Silicon Graphics
Graphics Library that C programmers find in the header file
`<gl/device.h>`.
Read the module source file for details.


module-struct.html | strings.html | sequence-matcher.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.3 struct (module-struct.html)
Up:
4. String Services (strings.html)
Next:
4.4.1 SequenceMatcher Objects (sequence-matcher.html)
---
# 4.4 difflib --
Helpers for computing deltas
New in version 2.1.
See Also:


module-os.path.html | allos.html | module-stat.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.2 os.path (module-os.path.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.4 stat (module-stat.html)
---
# 6.3 dircache --
Cached directory listings
The dircache module defines a function for reading directory listing
using a cache, and cache invalidation using the mtime of the directory.
Additionally, it defines a function to annotate directories by appending
a slash.
The dircache module defines the following functions:


module-compileall.html | language.html | bytecodes.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
18.9 compileall (module-compileall.html)
Up:
18. Python Language Services (language.html)
Next:
18.10.1 Python Byte Code (bytecodes.html)
---
# 18.10 dis --
Disassembler for Python byte code
The dis module supports the analysis of Python byte code by
disassembling it. Since there is no Python assembler, this module
defines the Python assembly language. The Python byte code which
this module takes as an input is defined in the file
Include/opcode.h and used by the compiler and the interpreter.
Example: Given the function myfunc:
```text

def myfunc(alist):
return len(alist)
```
the following command can be used to get the disassembly of
myfunc():
```text

>>> dis.dis(myfunc)
2 0 LOAD_GLOBAL 0 (len)
3 LOAD_FAST 0 (alist)
6 CALL_FUNCTION 1
9 RETURN_VALUE
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
```
(The ``2'' is a line number).
The dis module defines the following functions and constants:


bytecodes.html | language.html | compiler.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
18.10.1 Python Byte Code (bytecodes.html)
Up:
18. Python Language Services (language.html)
Next:
19. Python compiler package (compiler.html)
---
# 18.11 distutils --
Building and installing Python modules
The distutils package provides support for building and
installing additional modules into a Python installation. The new
modules may be either 100%-pure Python, or may be extension modules
written in C, or may be collections of Python packages which include
modules coded in both Python and C.
This package is discussed in two separate documents which are included
in the Python documentation package. To learn about distributing new
modules using the distutils facilities, read
Distributing Python Modules (../dist/dist.html). To learn
about installing Python modules, whether or not the author made use of
the distutils package, read
Installing Python Modules (../inst/inst.html).
See Also:


module-crypt.html | unix.html | dl-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.4 crypt (module-crypt.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.5.1 Dl Objects (dl-objects.html)
---
# 8.5 dl --
Call C functions in shared objects
Availability: Unix.
The dl module defines an interface to the
dlopen() function, which is the most common interface on
Unix platforms for handling dynamically linked libraries. It allows
the program to call arbitrary functions in such a library.
Note:
This module will not work unless
`sizeof(int) == sizeof(long) == sizeof(char *)`
If this is not the case, SystemError will be raised on
import.
The dl module defines the following function:
The dl module defines the following constants:
The dl module defines the following exception:
Example:
```text

>>> import dl, time
>>> a=dl.open('/lib/libc.so.6')
>>> a.call('time'), time.time()
(929723914, 929723914.498)
```
This example was tried on a Debian GNU/Linux system, and is a good
example of the fact that using this module is usually a bad alternative.


module-pydoc.html | misc.html | node133.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.1 pydoc (module-pydoc.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.2.1 Normal Usage (node133.html)
---
# 5.2 doctest --
Test docstrings represent reality
The doctest module searches a module's docstrings for text that looks
like an interactive Python session, then executes all such sessions to verify
they still work exactly as shown. Here's a complete but small example:
```text

"""
This is module example.

Example supplies one function, factorial. For example,

>>> factorial(5)
120
"""

def factorial(n):
"""Return the factorial of n, an exact integer >= 0.

If the result is small enough to fit in an int, return an int.
Else return a long.

>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000L
>>> factorial(30L)
265252859812191058636308480000000L
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0

Factorials of floats are OK, but the float must be an exact integer:
>>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000L

It must also not be ridiculously large:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
```
```text

import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
try:
result *= factor
except OverflowError:
result *= long(factor)
factor += 1
return result

def _test():
import doctest, example
return doctest.testmod(example)

if __name__ == "__main__":
_test()
```
If you run example.py directly from the command line,
doctest works its magic:
```text

$ python example.py
$
```
There's no output! That's normal, and it means all the examples
worked. Pass -v to the script, and doctest
prints a detailed log of what it's trying, and prints a summary at the
end:
```text

$ python example.py -v
Running example.__doc__
Trying: factorial(5)
Expecting: 120
ok
0 of 1 examples failed in example.__doc__
Running example.factorial.__doc__
Trying: [factorial(n) for n in range(6)]
Expecting: [1, 1, 2, 6, 24, 120]
ok
Trying: [factorial(long(n)) for n in range(6)]
Expecting: [1, 1, 2, 6, 24, 120]
ok
Trying: factorial(30)
Expecting: 265252859812191058636308480000000L
ok
```
And so on, eventually ending with:
```text

Trying: factorial(1e100)
Expecting:
Traceback (most recent call last):
...
OverflowError: n too large
ok
0 of 8 examples failed in example.factorial.__doc__
2 items passed all tests:
1 tests in example
8 tests in example.factorial
9 tests in 2 items.
9 passed and 0 failed.
Test passed.
$
```
That's all you need to know to start making productive use of
doctest! Jump in. The docstrings in doctest.py contain
detailed information about all aspects of doctest, and we'll
just cover the more important points here.


node478.html | internet.html | doc-xmlrpc-servers.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.21.2 CGIXMLRPCRequestHandler (node478.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.22.1 DocXMLRPCServer Objects (doc-xmlrpc-servers.html)
---
# 11.22 DocXMLRPCServer --
Self-documenting XML-RPC server
New in version 2.3.
The DocXMLRPCServer module extends the classes found in
SimpleXMLRPCServer to serve HTML documentation in response to
HTTP GET requests. Servers can either be free standing, using
DocXMLRPCServer, or embedded in a CGI environment, using
DocCGIXMLRPCRequestHandler.


bsddb-objects.html | someos.html | dumbdbm-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.13.1 Hash, BTree and (bsddb-objects.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.14.1 Dumbdbm Objects (dumbdbm-objects.html)
---
# 7.14 dumbdbm --
Portable DBM implementation
Note:
The dumbdbm module is intended as a last resort fallback for
the anydbm (module-anydbm.html) module when no more robust module is available.
The dumbdbm module is not written for speed and is not nearly as
heavily used as the other database modules.
The dumbdbm module provides a persistent dictionary-like interface
which is written entirely in Python. Unlike other modules such as
gdbm (module-gdbm.html) and bsddb (module-bsddb.html), no external library is required. As
with other persistent mappings, the keys and values must always be strings.
The module defines the following:
See Also:


timer-objects.html | someos.html | module-dummythreading.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.5.7 Timer Objects (timer-objects.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.7 dummy_threading (module-dummythreading.html)
---
# 7.6 dummy_thread --
Drop-in replacement for the thread module
This module provides a duplicate interface to the thread (module-thread.html)
module. It is meant to be imported when the thread (module-thread.html) module
is not provided on a platform.
Suggested usage is:
```text

try:
import thread as _thread
except ImportError:
import dummy_thread as _thread
```


module-dummythread.html | someos.html | module-Queue.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.6 dummy_thread (module-dummythread.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.8 Queue (module-Queue.html)
---
# 7.7 dummy_threading --
Drop-in replacement for the threading module
This module provides a duplicate interface to the
threading (module-threading.html) module. It is meant to be imported when the
thread (module-thread.html) module is not provided on a platform.
Suggested usage is:
```text

try:
import threading as _threading
except ImportError:
import dummy_threading as _threading
```


12.2.6 Representing character sets

module-email.Header.html | module-email.html | module-email.Encoders.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.2.5 Internationalized headers (module-email.Header.html)
Up:
12.2 email (module-email.html)
Next:
12.2.7 Encoders (module-email.Encoders.html)
---
## 12.2.6 Representing character sets
This module provides a class Charset for representing
character sets and character set conversions in email messages, as
well as a character set registry and several convenience methods for
manipulating this registry. Instances of Charset are used in
several other modules within the email package.
New in version 2.2.2.
Charset instances have the following data attributes:
Charset instances also have the following methods:
The Charset class also provides a number of methods to support
standard operations and built-in functions.
The email.Charset module also provides the following
functions for adding new entries to the global character set, alias,
and codec registries:


12.2.7 Encoders

module-email.Charset.html | module-email.html | module-email.Errors.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.2.6 Representing character sets (module-email.Charset.html)
Up:
12.2 email (module-email.html)
Next:
12.2.8 Exception classes (module-email.Errors.html)
---
## 12.2.7 Encoders
When creating Message objects from scratch, you often need to
encode the payloads for transport through compliant mail servers.
This is especially true for image/* and text/*
type messages containing binary data.
The email package provides some convenient encodings in its
Encoders module. These encoders are actually used by the
MIMEImage and MIMEText class constructors to provide default
encodings. All encoder functions take exactly one argument, the
message object to encode. They usually extract the payload, encode
it, and reset the payload to this newly encoded value. They should also
set the Content-Transfer-Encoding: header as appropriate.
Here are the encoding functions provided:


12.2.8 Exception classes

module-email.Encoders.html | module-email.html | module-email.Utils.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.2.7 Encoders (module-email.Encoders.html)
Up:
12.2 email (module-email.html)
Next:
12.2.9 Miscellaneous utilities (module-email.Utils.html)
---
## 12.2.8 Exception classes
The following exception classes are defined in the
email.Errors module:


12.2.3 Generating MIME documents

node498.html | module-email.html | node500.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.2.2.2 Additional notes (node498.html)
Up:
12.2 email (module-email.html)
Next:
12.2.3.1 Deprecated methods (node500.html)
---
## 12.2.3 Generating MIME documents
One of the most common tasks is to generate the flat text of the email
message represented by a message object structure. You will need to do
this if you want to send your message via the smtplib (module-smtplib.html)
module or the nntplib (module-nntplib.html) module, or print the message on the
console. Taking a message object structure and producing a flat text
document is the job of the Generator class.
Again, as with the email.Parser (module-email.Parser.html) module, you aren't limited
to the functionality of the bundled generator; you could write one
from scratch yourself. However the bundled generator knows how to
generate most email in a standards-compliant way, should handle MIME
and non-MIME email messages just fine, and is designed so that the
transformation from flat text, to a message structure via the
Parser class, and back to flat text, is idempotent (the input
is identical to the output).
Here are the public methods of the Generator class:
The other public Generator methods are:
As a convenience, see the methods Message.as_string() and
`str(aMessage)`, a.k.a. Message.__str__(), which
simplify the generation of a formatted string representation of a
message object. For more detail, see email.Message (module-email.Message.html).
The email.Generator module also provides a derived class,
called DecodedGenerator which is like the Generator
base class, except that non-text parts are substituted with
a format string representing the part.


12.2.5 Internationalized headers

node501.html | module-email.html | module-email.Charset.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.2.4 Creating email and (node501.html)
Up:
12.2 email (module-email.html)
Next:
12.2.6 Representing character sets (module-email.Charset.html)
---
## 12.2.5 Internationalized headers
RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) is the base standard that describes the format of email
messages. It derives from the older RFC 822 (http://www.faqs.org/rfcs/rfc822.html) standard which came
into widespread use at a time when most email was composed of ASCII
characters only. RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) is a specification written assuming email
contains only 7-bit ASCII characters.
Of course, as email has been deployed worldwide, it has become
internationalized, such that language specific character sets can now
be used in email messages. The base standard still requires email
messages to be transfered using only 7-bit ASCII characters, so a
slew of RFCs have been written describing how to encode email
containing non-ASCII characters into RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html)-compliant format.
These RFCs include RFC 2045 (http://www.faqs.org/rfcs/rfc2045.html), RFC 2046 (http://www.faqs.org/rfcs/rfc2046.html), RFC 2047 (http://www.faqs.org/rfcs/rfc2047.html), and RFC 2231 (http://www.faqs.org/rfcs/rfc2231.html).
The email package supports these standards in its
email.Header and email.Charset modules.
If you want to include non-ASCII characters in your email headers,
say in the Subject: or To: fields, you should
use the Header class and assign the field in the
Message object to an instance of Header instead of
using a string for the header value. For example:
```text

>>> from email.Message import Message
>>> from email.Header import Header
>>> msg = Message()
>>> h = Header('p\xf6stal', 'iso-8859-1')
>>> msg['Subject'] = h
>>> print msg.as_string()
Subject: =?iso-8859-1?q?p=F6stal?=
```
Notice here how we wanted the Subject: field to contain a
non-ASCII character? We did this by creating a Header
instance and passing in the character set that the byte string was
encoded in. When the subsequent Message instance was
flattened, the Subject: field was properly RFC 2047 (http://www.faqs.org/rfcs/rfc2047.html)
encoded. MIME-aware mail readers would show this header using the
embedded ISO-8859-1 character.
New in version 2.2.2.
Here is the Header class description:
Optional errors is passed straight through to the
append() method.
The Header class also provides a number of methods to support
standard operators and built-in functions.
The email.Header module also provides the following
convenient functions.


writer-impls.html | netdata.html | module-email.Message.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.1.4 Writer Implementations (writer-impls.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.2.1 Representing an email (module-email.Message.html)
---
# 12.2 email --
An email and MIME handling package
New in version 2.2.
The email package is a library for managing email messages,
including MIME and other RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html)-based message documents. It
subsumes most of the functionality in several older standard modules
such as rfc822 (module-rfc822.html), mimetools (module-mimetools.html),
multifile (module-multifile.html), and other non-standard packages such as
mimecntl. It is specifically not designed to do any
sending of email messages to SMTP (RFC 2821 (http://www.faqs.org/rfcs/rfc2821.html)) servers; that is the
function of the smtplib (module-smtplib.html) module. The email
package attempts to be as RFC-compliant as possible, supporting in
addition to RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html), such MIME-related RFCs as
RFC 2045 (http://www.faqs.org/rfcs/rfc2045.html)-RFC 2047 (http://www.faqs.org/rfcs/rfc2047.html), and RFC 2231 (http://www.faqs.org/rfcs/rfc2231.html).
The primary distinguishing feature of the email package is
that it splits the parsing and generating of email messages from the
internal object model representation of email. Applications
using the email package deal primarily with objects; you can
add sub-objects to messages, remove sub-objects from messages,
completely re-arrange the contents, etc. There is a separate parser
and a separate generator which handles the transformation from flat
text to the object model, and then back to flat text again. There
are also handy subclasses for some common MIME object types, and a few
miscellaneous utilities that help with such common tasks as extracting
and parsing message field values, creating RFC-compliant dates, etc.
The following sections describe the functionality of the
email package. The ordering follows a progression that
should be common in applications: an email message is read as flat
text from a file or other source, the text is parsed to produce the
object structure of the email message, this structure is manipulated,
and finally rendered back into flat text.
It is perfectly feasible to create the object structure out of whole
cloth -- i.e. completely from scratch. From there, a similar
progression can be taken as above.
Also included are detailed specifications of all the classes and
modules that the email package provides, the exception
classes you might encounter while using the email package,
some auxiliary utilities, and a few examples. For users of the older
mimelib package, or previous versions of the email
package, a section on differences and porting is provided.
See Also:


12.2.10 Iterators

module-email.Utils.html | module-email.html | node508.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.2.9 Miscellaneous utilities (module-email.Utils.html)
Up:
12.2 email (module-email.html)
Next:
12.2.11 Differences from email (node508.html)
---
## 12.2.10 Iterators
Iterating over a message object tree is fairly easy with the
Message.walk() method. The email.Iterators module
provides some useful higher level iterations over message object
trees.
The following function has been added as a useful debugging tool. It
should not be considered part of the supported public interface
for the package.


12.2.1 Representing an email message

module-email.html | module-email.html | node495.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.2 email (module-email.html)
Up:
12.2 email (module-email.html)
Next:
12.2.1.1 Deprecated methods (node495.html)
---
## 12.2.1 Representing an email message
The central class in the email package is the
Message class; it is the base class for the email
object model. Message provides the core functionality for
setting and querying header fields, and for accessing message bodies.
Conceptually, a Message object consists of headers and
payloads. Headers are RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) style field names and
values where the field name and value are separated by a colon. The
colon is not part of either the field name or the field value.
Headers are stored and returned in case-preserving form but are
matched case-insensitively. There may also be a single envelope
header, also known as the Unix-From header or the
`From_` header. The payload is either a string in the case of
simple message objects or a list of Message objects for
MIME container documents (e.g. multipart/* and
message/rfc822).
Message objects provide a mapping style interface for
accessing the message headers, and an explicit interface for accessing
both the headers and the payload. It provides convenience methods for
generating a flat text representation of the message object tree, for
accessing commonly used header parameters, and for recursively walking
over the object tree.
Here are the methods of the Message class:
The following methods implement a mapping-like interface for accessing
the message's RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) headers. Note that there are some
semantic differences between these methods and a normal mapping
(i.e. dictionary) interface. For example, in a dictionary there are
no duplicate keys, but here there may be duplicate message headers. Also,
in dictionaries there is no guaranteed order to the keys returned by
keys(), but in a Message object, headers are always
returned in the order they appeared in the original message, or were
added to the message later. Any header deleted and then re-added are
always appended to the end of the header list.
These semantic differences are intentional and are biased toward
maximal convenience.
Note that in all cases, any envelope header present in the message is
not included in the mapping interface.
Here are some additional useful methods:
Message objects can also optionally contain two instance
attributes, which can be used when generating the plain text of a MIME
message.


12.2.2 Parsing email messages

node495.html | module-email.html | node497.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.2.1.1 Deprecated methods (node495.html)
Up:
12.2 email (module-email.html)
Next:
12.2.2.1 Parser class API (node497.html)
---
## 12.2.2 Parsing email messages
Message object structures can be created in one of two ways: they can be
created from whole cloth by instantiating Message objects and
stringing them together via attach() and
set_payload() calls, or they can be created by parsing a flat text
representation of the email message.
The email package provides a standard parser that understands
most email document structures, including MIME documents. You can
pass the parser a string or a file object, and the parser will return
to you the root Message instance of the object structure. For
simple, non-MIME messages the payload of this root object will likely
be a string containing the text of the message. For MIME
messages, the root object will return `True` from its
is_multipart() method, and the subparts can be accessed via
the get_payload() and walk() methods.
Note that the parser can be extended in limited ways, and of course
you can implement your own parser completely from scratch. There is
no magical connection between the email package's bundled
parser and the Message class, so your custom parser can create
message object trees any way it finds necessary.
The primary parser class is Parser which parses both the
headers and the payload of the message. In the case of
multipart messages, it will recursively parse the body of
the container message. Two modes of parsing are supported,
strict parsing, which will usually reject any non-RFC compliant
message, and lax parsing, which attempts to adjust for common
MIME formatting problems.
The email.Parser module also provides a second class, called
HeaderParser which can be used if you're only interested in
the headers of the message. HeaderParser can be much faster in
these situations, since it does not attempt to parse the message body,
instead setting the payload to the raw body as a string.
HeaderParser has the same API as the Parser class.


12.2.9 Miscellaneous utilities

module-email.Errors.html | module-email.html | module-email.Iterators.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12.2.8 Exception classes (module-email.Errors.html)
Up:
12.2 email (module-email.html)
Next:
12.2.10 Iterators (module-email.Iterators.html)
---
## 12.2.9 Miscellaneous utilities
There are several useful utilities provided with the email
package.
The following functions have been deprecated:


node126.html | module-codecs.html | module-unicodedata.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.9.2 Standard Encodings (node126.html)
Up:
4.9 codecs (module-codecs.html)
Next:
4.10 unicodedata (module-unicodedata.html)
---
## 4.9.3 encodings.idna --
Internationalized Domain Names in Applications
New in version 2.3.
This module implements RFC 3490 (http://www.faqs.org/rfcs/rfc3490.html) (Internationalized Domain Names in
Applications) and RFC 3492 (http://www.faqs.org/rfcs/rfc3492.html) (Nameprep: A Stringprep Profile for
Internationalized Domain Names (IDN)). It builds upon the
`punycode` encoding and stringprep (module-stringprep.html).
These RFCs together define a protocol to support non-ASCII characters
in domain names. A domain name containing non-ASCII characters (such
as ``www.Alliancefrançaise.nu'') is converted into an
ASCII-compatible encoding (ACE, such as
``www.xn-alliancefranaise-npb.nu''). The ACE form of the domain name
is then used in all places where arbitrary characters are not allowed
by the protocol, such as DNS queries, HTTP Host: fields, and so
on. This conversion is carried out in the application; if possible
invisible to the user: The application should transparently convert
Unicode domain labels to IDNA on the wire, and convert back ACE labels
to Unicode before presenting them to the user.
Python supports this conversion in several ways: The `idna` codec
allows to convert between Unicode and the ACE. Furthermore, the
socket (module-socket.html) module transparently converts Unicode host names to
ACE, so that applications need not be concerned about converting host
names themselves when they pass them to the socket module. On top of
that, modules that have host names as function parameters, such as
httplib (module-httplib.html) and ftplib (module-ftplib.html), accept Unicode host names
(httplib (module-httplib.html) then also transparently sends an IDNA hostname in
the Host: field if it sends that field at all).
When receiving host names from the wire (such as in reverse name
lookup), no automatic conversion to Unicode is performed: Applications
wishing to present such host names to the user should decode them to
Unicode.
The module encodings.idna also implements the nameprep
procedure, which performs certain normalizations on host names, to
achieve case-insensitivity of international domain names, and to unify
similar characters. The nameprep functions can be used directly if
desired.


module-tempfile.html | allos.html | module-glob.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.21 tempfile (module-tempfile.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.23 glob (module-glob.html)
---
# 6.22 errno --
Standard errno system symbols
This module makes available standard `errno` system symbols.
The value of each symbol is the corresponding integer value.
The names and descriptions are borrowed from linux/include/errno.h,
which should be pretty all-inclusive.
To translate a numeric error code to an error message, use
os.strerror().
Of the following list, symbols that are not used on the current
platform are not defined by the module. The specific list of defined
symbols is available as `errno.errorcode.keys()`. Symbols
available can include:


2.3 Built-in Exceptions

specialattrs.html | builtin.html | node33.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
2.2.10 Special Attributes (specialattrs.html)
Up:
2. Built-In Objects (builtin.html)
Next:
2.4 Built-in Constants (node33.html)
---
# 2.3 Built-in Exceptions
Exceptions should be class objects.
The exceptions are defined in the module exceptions. This
module never needs to be imported explicitly: the exceptions are
provided in the built-in namespace as well as the exceptions
module.
Note:
In past versions of Python string exceptions were supported. In
Python 1.5 and newer versions, all standard exceptions have been
converted to class objects and users are encouraged to do the same.
String exceptions will raise a `PendingDeprecationWarning`.
In future versions, support for string exceptions will be removed.
Two distinct string objects with the same value are considered different
exceptions. This is done to force programmers to use exception names
rather than their string value when specifying exception handlers.
The string value of all built-in exceptions is their name, but this is
not a requirement for user-defined exceptions or exceptions defined by
library modules.
For class exceptions, in a try statement with
an except clause that mentions a particular
class, that clause also handles any exception classes derived from
that class (but not exception classes from which it is
derived). Two exception classes that are not related via subclassing
are never equivalent, even if they have the same name.
The built-in exceptions listed below can be generated by the
interpreter or built-in functions. Except where mentioned, they have
an ``associated value'' indicating the detailed cause of the error.
This may be a string or a tuple containing several items of
information (e.g., an error code and a string explaining the code).
The associated value is the second argument to the
raise statement. For string exceptions, the
associated value itself will be stored in the variable named as the
second argument of the except clause (if any). For class
exceptions, that variable receives the exception instance. If the
exception class is derived from the standard root class
Exception, the associated value is present as the
exception instance's args attribute, and possibly on other
attributes as well.
User code can raise built-in exceptions. This can be used to test an
exception handler or to report an error condition ``just like'' the
situation in which the interpreter raises the same exception; but
beware that there is nothing to prevent user code from raising an
inappropriate error.
The built-in exception classes can be sub-classed to define new
exceptions; programmers are encouraged to at least derive new
exceptions from the Exception base class. More
information on defining exceptions is available in the
Python Tutorial (../tut/tut.html) under the heading
``User-defined Exceptions.''
The following exceptions are only used as base classes for other
exceptions.
The following exceptions are the exceptions that are actually raised.
The following exceptions are used as warning categories; see the
warnings (module-warnings.html) module for more information.
The class hierarchy for built-in exceptions is:


module-pty.html | unix.html | module-pipes.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.11 pty (module-pty.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.13 pipes (module-pipes.html)
---
# 8.12 fcntl --
The fcntl() and ioctl() system calls
Availability: Unix.
This module performs file control and I/O control on file descriptors.
It is an interface to the fcntl() and ioctl()
Unix routines.
All functions in this module take a file descriptor fd as their
first argument. This can be an integer file descriptor, such as
returned by `sys.stdin.fileno()`, or a file object, such as
`sys.stdin` itself, which provides a fileno() which
returns a genuine file descriptor.
The module defines the following functions:
Examples (all on a SVR4 compliant system):
```text

import struct, fcntl

file = open(...)
rv = fcntl(file, fcntl.F_SETFL, os.O_NDELAY)

lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
rv = fcntl.fcntl(file, fcntl.F_SETLKW, lockdata)
```
Note that in the first example the return value variable rv will
hold an integer value; in the second example it will hold a string
value. The structure lay-out for the lockdata variable is
system dependent -- therefore using the flock() call may be
better.


module-statvfs.html | allos.html | dircmp-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.6 statvfs (module-statvfs.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.7.1 The dircmp class (dircmp-objects.html)
---
# 6.7 filecmp --
File and Directory Comparisons
The filecmp module defines functions to compare files and
directories, with various optional time/correctness trade-offs.
The filecmp module defines the following functions:
Example:
```text

>>> import filecmp
>>> filecmp.cmp('libundoc.tex', 'libundoc.tex')
True
>>> filecmp.cmp('libundoc.tex', 'lib.tex')
False
```


ConfigParser-objects.html | misc.html | module-xreadlines.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.14.2 ConfigParser Objects (ConfigParser-objects.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.16 xreadlines (module-xreadlines.html)
---
# 5.15 fileinput --
Iterate over lines from multiple input streams
This module implements a helper class and functions to quickly write a
loop over standard input or a list of files.
The typical use is:
```text

import fileinput
for line in fileinput.input():
process(line)
```
This iterates over the lines of all files listed in
`sys.argv[1:]`, defaulting to `sys.stdin` if the list is
empty. If a filename is `'-'`, it is also replaced by
`sys.stdin`. To specify an alternative list of filenames, pass
it as the first argument to input(). A single file name is
also allowed.
All files are opened in text mode. If an I/O error occurs during
opening or reading a file, IOError is raised.
If `sys.stdin` is used more than once, the second and further use
will return no lines, except perhaps for interactive use, or if it has
been explicitly reset (e.g. using `sys.stdin.seek(0)`).
Empty files are opened and immediately closed; the only time their
presence in the list of filenames is noticeable at all is when the
last file opened is empty.
It is possible that the last line of a file does not end in a newline
character; lines are returned including the trailing newline when it
is present.
The following function is the primary interface of this module:
The following functions use the global state created by
input(); if there is no active state,
RuntimeError is raised.
The class which implements the sequence behavior provided by the
module is available for subclassing as well:
Optional in-place filtering: if the keyword argument
`inplace =1` is passed to input() or to the
FileInput constructor, the file is moved to a backup file and
standard output is directed to the input file (if a file of the same
name as the backup file already exists, it will be replaced silently).
This makes it possible to write a filter that rewrites its input file
in place. If the keyword argument `backup ='.<some
extension>'` is also given, it specifies the extension for the backup
file, and the backup file remains around; by default, the extension is
`'.bak'` and it is deleted when the output file is closed. In-place
filtering is disabled when standard input is read.


forms-objects.html | sgi.html | module-flp.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.4.3 FORMS Objects (forms-objects.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.6 flp (module-flp.html)
---
# 20.5 FL --
Constants used with the fl module
Availability: IRIX.
This module defines symbolic constants needed to use the built-in
module fl (module-fl.html) (see above); they are equivalent to those defined in
the C header file `<forms.h>` except that the name prefix
"FL_" is omitted. Read the module source for a complete list of
the defined names. Suggested use:
```text

import fl
from FL import *
```


cd-parser-objects.html | sgi.html | node720.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.3.2 Parser Objects (cd-parser-objects.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.4.1 Functions Defined in (node720.html)
---
# 20.4 fl --
FORMS library for graphical user interfaces
Availability: IRIX.
This module provides an interface to the FORMS Libraryby Mark Overmars. The source for the
library can be retrieved by anonymous ftp from host
"ftp.cs.ruu.nl", directory SGI/FORMS. It was last tested
with version 2.0b.
Most functions are literal translations of their C equivalents,
dropping the initial "fl_" from their name. Constants used by
the library are defined in module FL (module-fl-constants.html)
described below.
The creation of objects is a little different in Python than in C:
instead of the `current form' maintained by the library to which new
FORMS objects are added, all functions that add a FORMS object to a
form are methods of the Python object representing the form.
Consequently, there are no Python equivalents for the C functions
fl_addto_form() and fl_end_form(), and the
equivalent of fl_bgn_form() is called
fl.make_form().
Watch out for the somewhat confusing terminology: FORMS uses the word
object for the buttons, sliders etc. that you can place in a form.
In Python, `object' means any value. The Python interface to FORMS
introduces two new Python object types: form objects (representing an
entire form) and FORMS objects (representing one button, slider etc.).
Hopefully this isn't too confusing.
There are no `free objects' in the Python interface to FORMS, nor is
there an easy way to add object classes written in Python. The FORMS
interface to GL event handling is available, though, so you can mix
FORMS with pure GL windows.
Please note: importing fl implies a call to the GL
function foreground() and to the FORMS routine
fl_init().


module-fl-constants.html | sgi.html | module-fm.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.5 FL (module-fl-constants.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.7 fm (module-fm.html)
---
# 20.6 flp --
Functions for loading stored FORMS designs
Availability: IRIX.
This module defines functions that can read form definitions created
by the `form designer' (fdesign) program that comes with the
FORMS library (see module fl (module-fl.html) above).
For now, see the file flp.doc in the Python library source
directory for a description.


20.7 fm -- Font Manager interface

module-flp.html | sgi.html | module-gl.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.6 flp (module-flp.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.8 gl (module-gl.html)
---
# 20.7 fm --
Font Manager interface
Availability: IRIX.
This module provides access to the IRIS Font Manager library.
It is available only on Silicon Graphics machines.
See also: 4Sight User's Guide, section 1, chapter 5: ``Using
the IRIS Font Manager.''
This is not yet a full interface to the IRIS Font Manager.
Among the unsupported features are: matrix operations; cache
operations; character operations (use string operations instead); some
details of font info; individual glyph metrics; and printer matching.
It supports the following operations:
Font handle objects support the following operations:


module-glob.html | allos.html | module-shutil.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.23 glob (module-glob.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.25 shutil (module-shutil.html)
---
# 6.24 fnmatch --
Unix filename pattern matching
This module provides support for Unix shell-style wildcards, which
are not the same as regular expressions (which are documented
in the re (module-re.html)module). The special
characters used in shell-style wildcards are:
Note that the filename separator (`'/'` on Unix) is not
special to this module. See module
glob (module-glob.html)for pathname expansion
(glob (module-glob.html) uses fnmatch() to match pathname
segments). Similarly, filenames starting with a period are
not special for this module, and are matched by the `*` and
`?` patterns.


netdata.html | netdata.html | formatter-interface.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
12. Internet Data Handling (netdata.html)
Up:
12. Internet Data Handling (netdata.html)
Next:
12.1.1 The Formatter Interface (formatter-interface.html)
---
# 12.1 formatter --
Generic output formatting
This module supports two interface definitions, each with multiple
implementations. The formatter interface is used by the
HTMLParser class of the htmllib (module-htmllib.html) module, and the
writer interface is required by the formatter interface.
Formatter objects transform an abstract flow of formatting events into
specific output events on writer objects. Formatters manage several
stack structures to allow various properties of a writer object to be
changed and restored; writers need not be able to handle relative
changes nor any sort of ``change back'' operation. Specific writer
properties which may be controlled via formatter objects are
horizontal alignment, font, and left margin indentations. A mechanism
is provided which supports providing arbitrary, non-exclusive style
settings to a writer as well. Additional interfaces facilitate
formatting events which are not reversible, such as paragraph
separation.
Writer objects encapsulate device interfaces. Abstract devices, such
as file formats, are supported as well as physical devices. The
provided implementations all work with abstract devices. The
interface makes available mechanisms for setting the properties which
formatter objects manage and inserting data into the output.


weakref-extension.html | python.html | fpectl-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.3.3 Weak References in (weakref-extension.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.4.1 Example (fpectl-example.html)
---
# 3.4 fpectl --
Floating point exception control
Availability: Unix.
Most computers carry out floating point operationsin conformance with the so-called IEEE-754 standard.
On any real computer,
some floating point operations produce results that cannot
be expressed as a normal floating point value.
For example, try
```text

>>> import math
>>> math.exp(1000)
inf
>>> math.exp(1000) / math.exp(1000)
nan
```
(The example above will work on many platforms.
DEC Alpha may be one exception.)
"Inf" is a special, non-numeric value in IEEE-754 that
stands for "infinity", and "nan" means "not a number."
Note that,
other than the non-numeric results,
nothing special happened when you asked Python
to carry out those calculations.
That is in fact the default behaviour prescribed in the IEEE-754 standard,
and if it works for you,
stop reading now.
In some circumstances,
it would be better to raise an exception and stop processing
at the point where the faulty operation was attempted.
The fpectl module
is for use in that situation.
It provides control over floating point
units from several hardware manufacturers,
allowing the user to turn on the generation
of SIGFPE whenever any of the
IEEE-754 exceptions Division by Zero, Overflow, or
Invalid Operation occurs.
In tandem with a pair of wrapper macros that are inserted
into the C code comprising your python system,
SIGFPE is trapped and converted into the Python
FloatingPointError exception.
The fpectl module defines the following functions and
may raise the given exception:


differ-examples.html | strings.html | module-StringIO.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
4.4.4 Differ Example (differ-examples.html)
Up:
4. String Services (strings.html)
Next:
4.6 StringIO (module-StringIO.html)
---
# 4.5 fpformat --
Floating point conversions
The fpformat module defines functions for dealing with
floating point numbers representations in 100% pure
Python. Note:
This module is unneeded: everything here could
be done via the `%` string interpolation operator.
The fpformat module defines the following functions and an
exception:
Example:


11.7 ftplib -- FTP protocol client

httplib-examples.html | internet.html | ftp-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.6.3 Examples (httplib-examples.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.7.1 FTP Objects (ftp-objects.html)
---
# 11.7 ftplib --
FTP protocol client
This module defines the class FTP and a few related items.
The FTP class implements the client side of the FTP
protocol. You can use this to write Python
programs that perform a variety of automated FTP jobs, such as
mirroring other ftp servers. It is also used by the module
urllib (module-urllib.html) to handle URLs that use FTP. For more information
on FTP (File Transfer Protocol), see Internet RFC 959 (http://www.faqs.org/rfcs/rfc959.html).
Here's a sample session using the ftplib module:
```text

>>> from ftplib import FTP
>>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
>>> ftp.login() # user anonymous, passwd anonymous@
>>> ftp.retrlines('LIST') # list directory contents
total 24418
drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .
dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 ..
-rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX
.
.
.
>>> ftp.retrbinary('RETR README', open('README', 'wb').write)
'226 Transfer complete.'
>>> ftp.quit()
```
The module defines the following items:
See Also:
The file Tools/scripts/ftpmirror.py in the Python source distribution is a script that can mirror
FTP sites, or portions thereof, using the ftplib module.
It can be used as an extended example that applies this module.


module-main.html | python.html | strings.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.31 __main__ (module-main.html)
Up:
3. Python Runtime Services (python.html)
Next:
4. String Services (strings.html)
---
# 3.32 __future__ --
Future statement definitions
__future__ is a real module, and serves three purposes:
- To avoid confusing existing tools that analyze import statements
and expect to find the modules they're importing.
- To ensure that future_statements run under releases prior to 2.1
at least yield runtime exceptions (the import of
__future__ will fail, because there was no module of
that name prior to 2.1).
- To document when incompatible changes were introduced, and when they
will be -- or were -- made mandatory. This is a form of executable
documentation, and can be inspected programatically via importing
__future__ and examining its contents.
Each statment in __future__.py is of the form:
```text

FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease ","
CompilerFlag ")"
```
where, normally, OptionalRelease is less then MandatoryRelease, and
both are 5-tuples of the same form as `sys.version_info`:
```text

(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
PY_MINOR_VERSION, # the 1; an int
PY_MICRO_VERSION, # the 0; an int
PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
PY_RELEASE_SERIAL # the 3; an int
)
```
OptionalRelease records the first release in which the feature was
accepted.
In the case of MandatoryReleases that have not yet occurred,
MandatoryRelease predicts the release in which the feature will become
part of the language.
Else MandatoryRelease records when the feature became part of the
language; in releases at or after that, modules no longer need a
future statement to use the feature in question, but may continue to
use such imports.
MandatoryRelease may also be `None`, meaning that a planned
feature got dropped.
Instances of class _Feature have two corresponding methods,
getOptionalRelease() and getMandatoryRelease().
CompilerFlag is the (bitfield) flag that should be passed in the
fourth argument to the builtin function compile() to enable
the feature in dynamically compiled code. This flag is stored in the
compiler_flag attribute on _Future instances.
No feature description will ever be deleted from __future__.


3.2 gc -- Garbage Collector interface

module-sys.html | python.html | module-weakref.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.1 sys (module-sys.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.3 weakref (module-weakref.html)
---
# 3.2 gc --
Garbage Collector interface
The gc module is only available if the interpreter was built
with the optional cyclic garbage detector (enabled by default). If
this was not enabled, an ImportError is raised by attempts
to import this module.
This module provides an interface to the optional garbage collector. It
provides the ability to disable the collector, tune the collection
frequency, and set debugging options. It also provides access to
unreachable objects that the collector found but cannot free. Since the
collector supplements the reference counting already used in Python, you
can disable the collector if you are sure your program does not create
reference cycles. Automatic collection can be disabled by calling
`gc.disable()`. To debug a leaking program call
`gc.set_debug(gc.DEBUG_LEAK)`.
The gc module provides the following functions:
The following variable is provided for read-only access (you can
mutate its value but should not rebind it):
The following constants are provided for use with
set_debug():


module-dbm.html | unix.html | module-termios.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.6 dbm (module-dbm.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.8 termios (module-termios.html)
---
# 8.7 gdbm --
GNU's reinterpretation of dbm
Availability: Unix.
This module is quite similar to the dbm (module-dbm.html)module, but uses `gdbm` instead to provide some additional
functionality. Please note that the file formats created by
`gdbm` and `dbm` are incompatible.
The gdbm module provides an interface to the GNU DBM
library. `gdbm` objects behave like mappings
(dictionaries), except that keys and values are always strings.
Printing a `gdbm` object doesn't print the keys and values, and
the items() and values() methods are not supported.
The module defines the following constant and functions:
In addition to the dictionary-like methods, `gdbm` objects have the
following methods:


curses-panel-objects.html | allos.html | module-optparse.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.18.2 Panel Objects (curses-panel-objects.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.20 optparse (module-optparse.html)
---
# 6.19 getopt --
Parser for command line options
This module helps scripts to parse the command line arguments in
`sys.argv`.
It supports the same conventions as the Unix getopt()
function (including the special meanings of arguments of the form
``-`' and ``-``-`').
Long options similar to those supported by
GNU software may be used as well via an optional third argument.
This module provides a single function and an exception:
An example using only Unix style options:
```text

>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
```
Using long option names is equally easy:
```text

>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
... 'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x',
'')]
>>> args
['a1', 'a2']
```
In a script, typical usage is something like this:


6.13 getpass -- Portable password input

mutex-objects.html | allos.html | module-curses.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.12.1 Mutex Objects (mutex-objects.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.14 curses (module-curses.html)
---
# 6.13 getpass
-- Portable password input
The getpass module provides two functions:


locale-gettext.html | allos.html | node268.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.26.3 Access to message (locale-gettext.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.27.1 GNU gettext API (node268.html)
---
# 6.27 gettext --
Multilingual internationalization services
The gettext module provides internationalization (I18N) and
localization (L10N) services for your Python modules and applications.
It supports both the GNU `gettext` message catalog API and a
higher level, class-based API that may be more appropriate for Python
files. The interface described below allows you to write your
module and application messages in one natural language, and provide a
catalog of translated messages for running under different natural
languages.
Some hints on localizing your Python modules and applications are also
given.


module-DEVICE.html | sgi.html | module-imgfile.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.9 DEVICE (module-DEVICE.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.11 imgfile (module-imgfile.html)
---
# 20.10 GL --
Constants used with the gl module
Availability: IRIX.


20.8 gl -- Graphics Library interface

module-fm.html | sgi.html | module-DEVICE.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.7 fm (module-fm.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.9 DEVICE (module-DEVICE.html)
---
# 20.8 gl --
Graphics Library interface
Availability: IRIX.
This module provides access to the Silicon Graphics
Graphics Library.
It is available only on Silicon Graphics machines.
Warning:
Some illegal calls to the GL library cause the Python
interpreter to dump core.
In particular, the use of most GL calls is unsafe before the first
window is opened.
The module is too large to document here in its entirety, but the
following should help you to get started.
The parameter conventions for the C functions are translated to Python as
follows:
- All (short, long, unsigned) int values are represented by Python
integers.
- All float and double values are represented by Python floating point
numbers.
In most cases, Python integers are also allowed.
- All arrays are represented by one-dimensional Python lists.
In most cases, tuples are also allowed.
- All string and character arguments are represented by Python strings,
for instance,
`winopen('Hi There!')`
and
`rotate(900, 'z')`.
- All (short, long, unsigned) integer arguments or return values that are
only used to specify the length of an array argument are omitted.
For example, the C call
```text

lmdef(deftype, index, np, props)
```
is translated to Python as
```text

lmdef(deftype, index, props)
```
- Output arguments are omitted from the argument list; they are
transmitted as function return values instead.
If more than one value must be returned, the return value is a tuple.
If the C function has both a regular return value (that is not omitted
because of the previous rule) and an output argument, the return value
comes first in the tuple.
Examples: the C call
```text

getmcolor(i, &red, &green, &blue)
```
is translated to Python as
```text

red, green, blue = getmcolor(i)
```
The following functions are non-standard or have special argument
conventions:
Here is a tiny but complete example GL program in Python:
```text

import gl, GL, time

def main():
gl.foreground()
gl.prefposition(500, 900, 500, 900)
w = gl.winopen('CrissCross')
gl.ortho2(0.0, 400.0, 0.0, 400.0)
gl.color(GL.WHITE)
gl.clear()
gl.color(GL.RED)
gl.bgnline()
gl.v2f(0.0, 0.0)
gl.v2f(400.0, 400.0)
gl.endline()
gl.bgnline()
gl.v2f(400.0, 0.0)
gl.v2f(0.0, 400.0)
gl.endline()
time.sleep(5)

main()
```
See Also:


module-errno.html | allos.html | module-fnmatch.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.22 errno (module-errno.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.24 fnmatch (module-fnmatch.html)
---
# 6.23 glob --
Unix style pathname pattern expansion
The glob module finds all the pathnames matching a specified
pattern according to the rules used by the Unix shell. No tilde
expansion is done, but `*`, `?`, and character ranges
expressed with `[]` will be correctly matched. This is done by
using the os.listdir() and fnmatch.fnmatch()
functions in concert, and not by actually invoking a subshell. (For
tilde and shell variable expansion, use os.path.expanduser()
and os.path.expandvars().)
For example, consider a directory containing only the following files:
1.gif, 2.txt, and card.gif. glob()
will produce the following results. Notice how any leading components
of the path are preserved.
```text

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
```


ftp-objects.html | internet.html | module-poplib.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.7.1 FTP Objects (ftp-objects.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.9 poplib (module-poplib.html)
---
# 11.8 gopherlib --
Gopher protocol client
This module provides a minimal implementation of client side of the
the Gopher protocol. It is used by the module urllib (module-urllib.html) to
handle URLs that use the Gopher protocol.
The module defines the following functions:


8.3 grp -- The group database

module-pwd.html | unix.html | module-crypt.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
8.2 pwd (module-pwd.html)
Up:
8. Unix Specific Services (unix.html)
Next:
8.4 crypt (module-crypt.html)
---
# 8.3 grp --
The group database
Availability: Unix.
This module provides access to the Unix group database.
It is available on all Unix versions.
Group database entries are reported as a tuple-like object, whose
attributes correspond to the members of the `group` structure
(Attribute field below, see `<pwd.h>`):
The gid is an integer, name and password are strings, and the member
list is a list of strings.
(Note that most users are not explicitly listed as members of the
group they are in according to the password database. Check both
databases to get complete membership information.)
It defines the following items:


7.16 gzip -- Support for gzip files

module-zlib.html | someos.html | module-bz2.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
7.15 zlib (module-zlib.html)
Up:
7. Optional Operating System (someos.html)
Next:
7.17 bz2 (module-bz2.html)
---
# 7.16 gzip --
Support for gzip files
The data compression provided by the `zlib` module is compatible
with that used by the GNU compression program gzip.
Accordingly, the gzip module provides the GzipFile
class to read and write gzip-format files, automatically
compressing or decompressing the data so it looks like an ordinary
file object. Note that additional file formats which can be
decompressed by the gzip and gunzip programs, such
as those produced by compress and pack, are not
supported by this module.
The module defines the following items:


5.10 heapq -- Heap queue algorithm

bisect-example.html | misc.html | node162.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.9.1 Examples (bisect-example.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.10.1 Theory (node162.html)
---
# 5.10 heapq --
Heap queue algorithm
New in version 2.3.
This module provides an implementation of the heap queue algorithm,
also known as the priority queue algorithm.
Heaps are arrays for which
`heap [ k ] <= heap [2* k +1]` and
`heap [ k ] <= heap [2* k +2]`
for all k, counting elements from zero. For the sake of
comparison, non-existing elements are considered to be infinite. The
interesting property of a heap is that `heap [0]` is always
its smallest element.
The API below differs from textbook heap algorithms in two aspects:
(a) We use zero-based indexing. This makes the relationship between the
index for a node and the indexes for its children slightly less
obvious, but is more suitable since Python uses zero-based indexing.
(b) Our pop method returns the smallest item, not the largest (called a
"min heap" in textbooks; a "max heap" is more common in texts because
of its suitability for in-place sorting).
These two make it possible to view the heap as a regular Python list
without surprises: `heap [0]` is the smallest item, and
`heap .sort()` maintains the heap invariant!
To create a heap, use a list initialized to `[]`, or you can
transform a populated list into a heap via function heapify().
The following functions are provided:
Example of use:
```text

>>> from heapq import heappush, heappop
>>> heap = []
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> for item in data:
... heappush(heap, item)
...
>>> sorted = []
>>> while heap:
... sorted.append(heappop(heap))
...
>>> print sorted
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> data.sort()
>>> print data == sorted
True
>>>
```


crypto.html | crypto.html | module-md5.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
15. Cryptographic Services (crypto.html)
Up:
15. Cryptographic Services (crypto.html)
Next:
15.2 md5 (module-md5.html)
---
# 15.1 hmac --
Keyed-Hashing for Message Authentication
New in version 2.2.
This module implements the HMAC algorithm as described by RFC 2104 (http://www.faqs.org/rfcs/rfc2104.html).
An HMAC object has the following methods:


node390.html | profile.html | hotshot-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
10.8 Extensions (node390.html)
Up:
10. The Python Profiler (profile.html)
Next:
10.9.1 Profile Objects (hotshot-objects.html)
---
# 10.9 hotshot --
High performance logging profiler
New in version 2.2.
This module provides a nicer interface to the _hotshot C module.
Hotshot is a replacement for the existing profile (module-profile.html) module. As it's
written mostly in C, it should result in a much smaller performance impact
than the existing profile (module-profile.html) module.


10.9.2 Using hotshot data

hotshot-objects.html | module-hotshot.html | hotshot-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
10.9.1 Profile Objects (hotshot-objects.html)
Up:
10.9 hotshot (module-hotshot.html)
Next:
10.9.3 Example Usage (hotshot-example.html)
---
## 10.9.2 Using hotshot data
New in version 2.2.
This module loads hotshot profiling data into the standard pstats
Stats objects.
See Also:


html-parser-objects.html | markup.html | module-xml.parsers.expat.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.3.1 HTMLParser Objects (html-parser-objects.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.5 xml.parsers.expat (module-xml.parsers.expat.html)
---
# 13.4 htmlentitydefs --
Definitions of HTML general entities
This module defines three dictionaries, `name2codepoint`,
`codepoint2name`, and `entitydefs`. `entitydefs` is
used by the htmllib (module-htmllib.html) module to provide the
entitydefs member of the HTMLParser class. The
definition provided here contains all the entities defined by XHTML 1.0
that can be handled using simple textual substitution in the Latin-1
character set (ISO-8859-1).


module-sgmllib.html | markup.html | html-parser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13.2 sgmllib (module-sgmllib.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.3.1 HTMLParser Objects (html-parser-objects.html)
---
# 13.3 htmllib --
A parser for HTML documents
This module defines a class which can serve as a base for parsing text
files formatted in the HyperText Mark-up Language (HTML). The class
is not directly concerned with I/O -- it must be provided with input
in string form via a method, and makes calls to methods of a
``formatter'' object in order to produce output. The
HTMLParser class is designed to be used as a base class for
other classes in order to add functionality, and allows most of its
methods to be extended or overridden. In turn, this class is derived
from and extends the SGMLParser class defined in module
sgmllib (module-sgmllib.html). The HTMLParser
implementation supports the HTML 2.0 language as described in
RFC 1866 (http://www.faqs.org/rfcs/rfc1866.html). Two implementations of formatter objects are provided in
the formatter (module-formatter.html)module; refer to the
documentation for that module for information on the formatter
interface.
The following is a summary of the interface defined by
sgmllib.SGMLParser:
- The interface to feed data to an instance is through the feed()
method, which takes a string argument. This can be called with as
little or as much text at a time as desired; "p.feed(a);
p.feed(b)" has the same effect as "p.feed(a+b)". When the data
contains complete HTML tags, these are processed immediately;
incomplete elements are saved in a buffer. To force processing of all
unprocessed data, call the close() method.
For example, to parse the entire contents of a file, use:
```text

parser.feed(open('myfile.html').read())
parser.close()
```
- The interface to define semantics for HTML tags is very simple: derive
a class and define methods called start_tag(),
end_tag(), or do_tag(). The parser will
call these at appropriate moments: start_tag or
do_tag() is called when an opening tag of the form
`< tag ...>` is encountered; end_tag() is called
when a closing tag of the form `< tag >` is encountered. If
an opening tag requires a corresponding closing tag, like `<H1>`
... `</H1>`, the class should define the start_tag()
method; if a tag requires no closing tag, like `<P>`, the class
should define the do_tag() method.
The module defines a single class:
See Also:


markup.html | markup.html | htmlparser-example.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
13. Structured Markup Processing (markup.html)
Up:
13. Structured Markup Processing (markup.html)
Next:
13.1.1 Example HTML Parser (htmlparser-example.html)
---
# 13.1 HTMLParser --
Simple HTML and XHTML parser
This module defines a class HTMLParser which serves as the
basis for parsing text files formatted in HTML(HyperText
Mark-up Language) and XHTML. Unlike the parser in
htmllib (module-htmllib.html), this parser is not based on the SGML parser in
sgmllib (module-sgmllib.html).
HTMLParser instances have the following methods:


11.6 httplib -- HTTP protocol client

urllib2-examples.html | internet.html | httpconnection-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.5.20 Examples (urllib2-examples.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.6.1 HTTPConnection Objects (httpconnection-objects.html)
---
# 11.6 httplib --
HTTP protocol client
This module defines classes which implement the client side of the
HTTP and HTTPS protocols. It is normally not used directly -- the
module urllib (module-urllib.html)uses it to handle URLs
that use HTTP and HTTPS.
Note:
HTTPS support is only available if the socket (module-socket.html) module was
compiled with SSL support.
Note:
The public interface for this module changed substantially in Python
2.0. The HTTP class is retained only for backward
compatibility with 1.5.2. It should not be used in new code. Refer
to the online docstrings for usage.
The constants defined in this module are:
The module provides the following classes:
The following exceptions are raised as appropriate:


module-audioop.html | mmedia.html | module-aifc.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
14.1 audioop (module-audioop.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.3 aifc (module-aifc.html)
---
# 14.2 imageop --
Manipulate raw image data
The imageop module contains some useful operations on images.
It operates on images consisting of 8 or 32 bit pixels stored in
Python strings. This is the same format as used by
gl.lrectwrite() and the imgfile (module-imgfile.html) module.
The module defines the following variables and functions:


11.10 imaplib -- IMAP4 protocol client

pop3-example.html | internet.html | imap4-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
11.9.2 POP3 Example (pop3-example.html)
Up:
11. Internet Protocols and (internet.html)
Next:
11.10.1 IMAP4 Objects (imap4-objects.html)
---
# 11.10 imaplib --
IMAP4 protocol client
This module defines three classes, IMAP4, IMAP4_SSL and IMAP4_stream, which encapsulate a
connection to an IMAP4 server and implement a large subset of the
IMAP4rev1 client protocol as defined in RFC 2060 (http://www.faqs.org/rfcs/rfc2060.html). It is backward
compatible with IMAP4 (RFC 1730 (http://www.faqs.org/rfcs/rfc1730.html)) servers, but note that the
"STATUS" command is not supported in IMAP4.
Three classes are provided by the imaplib module, IMAP4 is the base class:
Three exceptions are defined as attributes of the IMAP4 class:
There's also a subclass for secure connections:
The second subclass allows for connections created by a child process:
The following utility functions are defined:
Note that IMAP4 message numbers change as the mailbox changes; in
particular, after an "EXPUNGE" command performs deletions the
remaining messages are renumbered. So it is highly advisable to use
UIDs instead, with the UID command.
At the end of the module, there is a test section that contains a more
extensive example of usage.
See Also:
Documents describing the protocol, and sources and binaries
for servers implementing it, can all be found at the
University of Washington's IMAP Information Center
(http://www.cac.washington.edu/imap/).


module-gl-constants.html | sgi.html | module-jpeg.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.10 GL (module-gl-constants.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
20.12 jpeg (module-jpeg.html)
---
# 20.11 imgfile --
Support for SGI imglib files
Availability: IRIX.
The imgfile module allows Python programs to access SGI imglib image
files (also known as .rgb files). The module is far from
complete, but is provided anyway since the functionality that there is
is enough in some cases. Currently, colormap files are not supported.
The module defines the following variables and functions:


module-rgbimg.html | mmedia.html | module-sndhdr.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
14.8 rgbimg (module-rgbimg.html)
Up:
14. Multimedia Services (mmedia.html)
Next:
14.10 sndhdr (module-sndhdr.html)
---
# 14.9 imghdr --
Determine the type of an image
The imghdr module determines the type of image contained in a
file or byte stream.
The imghdr module defines the following function:
The following image types are recognized, as listed below with the
return value from what():
You can extend the list of file types imghdr can recognize by
appending to this variable:
Example:


3.21 imp -- Access the import internals

warning-functions.html | python.html | examples-imp.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.20.3 Available Functions (warning-functions.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.21.1 Examples (examples-imp.html)
---
# 3.21 imp --
Access the import internals
This module provides an interface to the mechanisms
used to implement the import statement. It defines the
following constants and functions:
The following constants with integer values, defined in this module,
are used to indicate the search result of find_module().
The following constant and functions are obsolete; their functionality
is available through find_module() or load_module().
They are kept around for backward compatibility:


3.11 inspect -- Inspect live objects

operator-map.html | python.html | inspect-types.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.10.1 Mapping Operators to (operator-map.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.11.1 Types and members (inspect-types.html)
---
# 3.11 inspect --
Inspect live objects
New in version 2.1.
The inspect module provides several useful functions
to help get information about live objects such as modules,
classes, methods, functions, tracebacks, frame objects, and
code objects. For example, it can help you examine the
contents of a class, retrieve the source code of a method,
extract and format the argument list for a function, or
get all the information you need to display a detailed traceback.
There are four main kinds of services provided by this module:
type checking, getting source code, inspecting classes
and functions, and examining the interpreter stack.


immutable-transforms.html | misc.html | itertools-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
5.12.3 Protocol for automatic (immutable-transforms.html)
Up:
5. Miscellaneous Services (misc.html)
Next:
5.13.1 Itertool functions (itertools-functions.html)
---
# 5.13 itertools --
Functions creating iterators for efficient looping
New in version 2.3.
This module implements a number of iterator building blocks inspired
by constructs from the Haskell and SML programming languages. Each
has been recast in a form suitable for Python.
The module standardizes a core set of fast, memory efficient tools
that are useful by themselves or in combination. Standardization helps
avoid the readability and reliability problems which arise when many
different individuals create their own slightly varying implementations,
each with their own quirks and naming conventions.
The tools are designed to combine readily with one another. This makes
it easy to construct more specialized tools succinctly and efficiently
in pure Python.
For instance, SML provides a tabulation tool: `tabulate(f)`
which produces a sequence `f(0), f(1), ...`. This toolbox
provides imap() and count() which can be combined
to form `imap(f, count())` and produce an equivalent result.
Likewise, the functional tools are designed to work well with the
high-speed functions provided by the operator (module-operator.html) module.
The module author welcomes suggestions for other basic building blocks
to be added to future versions of the module.
Whether cast in pure python form or C code, tools that use iterators
are more memory efficient (and faster) than their list based counterparts.
Adopting the principles of just-in-time manufacturing, they create
data when and where needed instead of consuming memory with the
computer equivalent of ``inventory''.
The performance advantage of iterators becomes more acute as the number
of elements increases - at some point, lists grow large enough to
to severely impact memory cache performance and start running slowly.
See Also:
The Standard ML Basis Library,
The Standard ML Basis Library (http://www.standardml.org/Basis/).
Haskell, A Purely Functional Language,
Definition of Haskell and the Standard Libraries (http://www.haskell.org/definition/).


20.12 jpeg -- Read and write JPEG files

module-imgfile.html | sgi.html | sunos.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
20.11 imgfile (module-imgfile.html)
Up:
20. SGI IRIX Specific (sgi.html)
Next:
21. SunOS Specific Services (sunos.html)
---
# 20.12 jpeg --
Read and write JPEG files
Availability: IRIX.
The module jpeg provides access to the jpeg compressor and
decompressor written by the Independent JPEG Group
(IJG). JPEG is a standard for
compressing pictures; it is defined in ISO 10918. For details on JPEG
or the Independent JPEG Group software refer to the JPEG standard or
the documentation provided with the software.
A portable interface to JPEG image files is available with the Python
Imaging Library (PIL) by Fredrik Lundh. Information on PIL is
available at http://www.pythonware.com/products/pil/.
The jpeg module defines an exception and some functions.
See Also:


module-token.html | language.html | module-tokenize.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
18.3 token (module-token.html)
Up:
18. Python Language Services (language.html)
Next:
18.5 tokenize (module-tokenize.html)
---
# 18.4 keyword --
Testing for Python keywords
This module allows a Python program to determine if a string is a
keyword.


traceback-example.html | python.html | module-pickle.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
3.12.1 Traceback Example (traceback-example.html)
Up:
3. Python Runtime Services (python.html)
Next:
3.14 pickle (module-pickle.html)
---
# 3.13 linecache --
Random access to text lines
The linecache module allows one to get any line from any file,
while attempting to optimize internally, using a cache, the common case
where many lines are read from a single file. This is used by the
traceback (module-traceback.html) module to retrieve source lines for inclusion in
the formatted traceback.
The linecache module defines the following functions:
Example:


shutil-example.html | allos.html | node264.html | Python Library Reference | contents.html | modindex.html | genindex.html
Previous:
6.25.1 Example (shutil-example.html)
Up:
6. Generic Operating System (allos.html)
Next:
6.26.1 Background, details, hints, (node264.html)
---
# 6.26 locale --
Internationalization services
The locale module opens access to the POSIX locale
database and functionality. The POSIX locale mechanism allows
programmers to deal with certain cultural issues in an application,
without requiring the programmer to know all the specifics of each
country where the software is executed.
The locale module is implemented on top of the
_localemodule, which in turn uses an
ANSI C locale implementation if available.
The locale module defines the following exception and
functions:
The nl_langinfo function accepts one of the following keys.
Most descriptions are taken from the corresponding description in the
GNU C library.
Example:
```text

>>> import locale
>>> loc = locale.setlocale(locale.LC_ALL) # get current locale
>>> locale.setlocale(locale.LC_ALL, 'de') # use German locale
>>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
>>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
>>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
>>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale
```