1.1 A Simple Example

intro.html | intro.html | errors.html | Extending and Embedding the Python Interpreter | contents.html
---
# 1.1 A Simple Example
Let's create an extension module called "spam" (the favorite food
of Monty Python fans...) and let's say we want to create a Python
interface to the C library function system().1.1 (#foot883)This function takes a null-terminated character string as argument and
returns an integer. We want this function to be callable from Python
as follows:
```text

>>> import spam
>>> status = spam.system("ls -l")
```
Begin by creating a file spammodule.c. (Historically, if a
module is called "spam", the C file containing its implementation
is called spammodule.c; if the module name is very long, like
"spammify", the module name can be just spammify.c.)
The first line of our file can be:
```text

#include <Python.h>
```
which pulls in the Python API (you can add a comment describing the
purpose of the module and a copyright notice if you like).
All user-visible symbols defined by `"Python.h"` have a prefix of
"Py" or "PY", except those defined in standard header files.
For convenience, and since they are used extensively by the Python
interpreter, `"Python.h"` includes a few standard header files:
`<stdio.h>`, `<string.h>`, `<errno.h>`, and
`<stdlib.h>`. If the latter header file does not exist on your
system, it declares the functions malloc(),
free() and realloc() directly.
The next thing we add to our module file is the C function that will
be called when the Python expression "spam.system(string)"is evaluated (we'll see shortly how it ends up being called):
```text

static PyObject *
spam_system(self, args)
PyObject *self;
PyObject *args;
{
char *command;
int sts;

if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return Py_BuildValue("i", sts);
}
```
There is a straightforward translation from the argument list in
Python (e.g. the single expression `"ls -l"`) to the arguments
passed to the C function. The C function always has two arguments,
conventionally named self and args.
The self argument is only used when the C function implements a
built-in method, not a function. In the example, self will
always be a NULL pointer, since we are defining a function, not a
method. (This is done so that the interpreter doesn't have to
understand two different types of C functions.)
The args argument will be a pointer to a Python tuple object
containing the arguments. Each item of the tuple corresponds to an
argument in the call's argument list. The arguments are Python
objects -- in order to do anything with them in our C function we have
to convert them to C values. The function PyArg_ParseTuple()
in the Python API checks the argument types and converts them to C
values. It uses a template string to determine the required types of
the arguments as well as the types of the C variables into which to
store the converted values. More about this later.
PyArg_ParseTuple() returns true (nonzero) if all arguments have
the right type and its components have been stored in the variables
whose addresses are passed. It returns false (zero) if an invalid
argument list was passed. In the latter case it also raises an
appropriate exception so the calling function can return
NULL immediately (as we saw in the example).


1.10.3 Thin Ice

ownershipRules.html | refcounts.html | nullPointers.html | Extending and Embedding the Python Interpreter | contents.html
---
## 1.10.3 Thin Ice
There are a few situations where seemingly harmless use of a borrowed
reference can lead to problems. These all have to do with implicit
invocations of the interpreter, which can cause the owner of a
reference to dispose of it.
The first and most important case to know about is using
Py_DECREF() on an unrelated object while borrowing a
reference to a list item. For instance:
```text

bug(PyObject *list) {
PyObject *item = PyList_GetItem(list, 0);

PyList_SetItem(list, 1, PyInt_FromLong(0L));
PyObject_Print(item, stdout, 0); /* BUG! */
}
```
This function first borrows a reference to `list[0]`, then
replaces `list[1]` with the value `0`, and finally prints
the borrowed reference. Looks harmless, right? But it's not!
Let's follow the control flow into PyList_SetItem(). The list
owns references to all its items, so when item 1 is replaced, it has
to dispose of the original item 1. Now let's suppose the original
item 1 was an instance of a user-defined class, and let's further
suppose that the class defined a __del__() method. If this
class instance has a reference count of 1, disposing of it will call
its __del__() method.
Since it is written in Python, the __del__() method can execute
arbitrary Python code. Could it perhaps do something to invalidate
the reference to `item` in bug()? You bet! Assuming
that the list passed into bug() is accessible to the
__del__() method, it could execute a statement to the effect of
"del list[0]", and assuming this was the last reference to that
object, it would free the memory associated with it, thereby
invalidating `item`.
The solution, once you know the source of the problem, is easy:
temporarily increment the reference count. The correct version of the
function reads:
```text

no_bug(PyObject *list) {
PyObject *item = PyList_GetItem(list, 0);

Py_INCREF(item);
PyList_SetItem(list, 1, PyInt_FromLong(0L));
PyObject_Print(item, stdout, 0);
Py_DECREF(item);
}
```
This is a true story. An older version of Python contained variants
of this bug and someone spent a considerable amount of time in a C
debugger to figure out why his __del__() methods would fail...
The second case of problems with a borrowed reference is a variant
involving threads. Normally, multiple threads in the Python
interpreter can't get in each other's way, because there is a global
lock protecting Python's entire object space. However, it is possible
to temporarily release this lock using the macro
`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using
`Py_END_ALLOW_THREADS`. This is common around blocking I/O
calls, to let other threads use the CPU while waiting for the I/O to
complete. Obviously, the following function has the same problem as
the previous one:
```text

bug(PyObject *list) {
PyObject *item = PyList_GetItem(list, 0);
Py_BEGIN_ALLOW_THREADS
...some blocking I/O call...
Py_END_ALLOW_THREADS
PyObject_Print(item, stdout, 0); /* BUG! */
}
```


cplusplus.html | intro.html | building-on-unix.html | Extending and Embedding the Python Interpreter | contents.html
---
# 1.12 Providing a C API for an Extension Module
Many extension modules just provide new functions and types to be
used from Python, but sometimes the code in an extension module can
be useful for other extension modules. For example, an extension
module could implement a type ``collection'' which works like lists
without order. Just like the standard Python list type has a C API
which permits extension modules to create and manipulate lists, this
new collection type should have a set of C functions for direct
manipulation from other extension modules.
At first sight this seems easy: just write the functions (without
declaring them static, of course), provide an appropriate
header file, and document the C API. And in fact this would work if
all extension modules were always linked statically with the Python
interpreter. When modules are used as shared libraries, however, the
symbols defined in one module may not be visible to another module.
The details of visibility depend on the operating system; some systems
use one global namespace for the Python interpreter and all extension
modules (e.g. Windows), whereas others require an explicit list of
imported symbols at module link time (e.g. AIX), or offer a choice of
different strategies (most Unices). And even if symbols are globally
visible, the module whose functions one wishes to call might not have
been loaded yet!
Portability therefore requires not to make any assumptions about
symbol visibility. This means that all symbols in extension modules
should be declared static, except for the module's
initialization function, in order to avoid name clashes with other
extension modules (as discussed in section 1.4 (methodTable.html#methodTable)). And it
means that symbols that should be accessible from other
extension modules must be exported in a different way.
Python provides a special mechanism to pass C-level information (i.e.
pointers) from one extension module to another one: CObjects.
A CObject is a Python data type which stores a pointer (void
*). CObjects can only be created and accessed via their C API, but
they can be passed around like any other Python object. In particular,
they can be assigned to a name in an extension module's namespace.
Other extension modules can then import this module, retrieve the
value of this name, and then retrieve the pointer from the CObject.
There are many ways in which CObjects can be used to export the C API
of an extension module. Each name could get its own CObject, or all C
API pointers could be stored in an array whose address is published in
a CObject. And the various tasks of storing and retrieving the pointers
can be distributed in different ways between the module providing the
code and the client modules.
The following example demonstrates an approach that puts most of the
burden on the writer of the exporting module, which is appropriate
for commonly used library modules. It stores all C API pointers
(just one in the example!) in an array of void pointers which
becomes the value of a CObject. The header file corresponding to
the module provides a macro that takes care of importing the module
and retrieving its C API pointers; client modules only have to call
this macro before accessing the C API.
The exporting module is a modification of the spam module from
section 1.1 (simpleExample.html#simpleExample). The function spam.system()
does not call the C library function system() directly,
but a function PySpam_System(), which would of course do
something more complicated in reality (such as adding ``spam'' to
every command). This function PySpam_System() is also
exported to other extension modules.
The function PySpam_System() is a plain C function,
declared static like everything else:
```text

static int
PySpam_System(command)
char *command;
{
return system(command);
}
```
The function spam_system() is modified in a trivial way:
```text

static PyObject *
spam_system(self, args)
PyObject *self;
PyObject *args;
{
char *command;
int sts;

if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = PySpam_System(command);
return Py_BuildValue("i", sts);
}
```
In the beginning of the module, right after the line
```text

#include "Python.h"
```
two more lines must be added:
```text

#define SPAM_MODULE
#include "spammodule.h"
```
The `#define` is used to tell the header file that it is being
included in the exporting module, not a client module. Finally,
the module's initialization function must take care of initializing
the C API pointer array:
```text

void
initspam()
{
PyObject *m, *d;
static void *PySpam_API[PySpam_API_pointers];
PyObject *c_api_object;
m = Py_InitModule("spam", SpamMethods);

/* Initialize the C API pointer array */
PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;

/* Create a CObject containing the API pointer array's address */
c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL);

/* Create a name for this object in the module's namespace */
d = PyModule_GetDict(m);
PyDict_SetItemString(d, "_C_API", c_api_object);
}
```
Note that `PySpam_API` is declared `static`; otherwise
the pointer array would disappear when `initspam` terminates!
The bulk of the work is in the header file spammodule.h,
which looks like this:
```text

#ifndef Py_SPAMMODULE_H
#define Py_SPAMMODULE_H
#ifdef __cplusplus
extern "C" {
#endif

/* Header file for spammodule */

/* C API functions */
#define PySpam_System_NUM 0
#define PySpam_System_RETURN int
#define PySpam_System_PROTO Py_PROTO((char *command))

/* Total number of C API pointers */
#define PySpam_API_pointers 1

#ifdef SPAM_MODULE
/* This section is used when compiling spammodule.c */

static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;

#else
/* This section is used in modules that use spammodule's API */

static void **PySpam_API;

#define PySpam_System \
(*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])

#define import_spam() \
{ \
PyObject *module = PyImport_ImportModule("spam"); \
if (module != NULL) { \
PyObject *module_dict = PyModule_GetDict(module); \
PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API"); \
if (PyCObject_Check(c_api_object)) { \
PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object); \
} \
} \
}

#endif

#ifdef __cplusplus
}
#endif

#endif /* !defined(Py_SPAMMODULE_H */
```
All that a client module must do in order to have access to the
function PySpam_System() is to call the function (or
rather macro) import_spam() in its initialization
function:
```text

void
initclient()
{
PyObject *m;

Py_InitModule("client", ClientMethods);
import_spam();
}
```
The main disadvantage of this approach is that the file
spammodule.h is rather complicated. However, the
basic structure is the same for each function that is
exported, so it has to be learned only once.
Finally it should be mentioned that CObjects offer additional
functionality, which is especially useful for memory allocation and
deallocation of the pointer stored in a CObject. The details
are described in the Python/C API
Reference Manual (../api/api.html) in the section ``CObjects'' and in the
implementation of CObjects (files Include/cobject.h and
Objects/cobject.c in the Python source code distribution).


3.1 A Cookbook Approach

building-on-windows.html | building-on-windows.html | dynamic-linking.html | Extending and Embedding the Python Interpreter | contents.html
---
# 3.1 A Cookbook Approach
This section provides a recipe for building a Python extension on
Windows.
Grab the binary installer from http://www.python.org/ and
install Python. The binary installer has all of the required header
files except for config.h.
Get the source distribution and extract it into a convenient location.
Copy the config.h from the PC/ directory into the
include/ directory created by the installer.
Create a Setup file for your extension module, as described in
chapter 2 (building-on-unix.html#building-on-unix).
Get David Ascher's compile.py script from
http://starship.python.net/crew/da/compile/. Run the script to
create Microsoft Visual C++ project files.
Open the DSW file in Visual C++ and select Build.
If your module creates a new type, you may have trouble with this line:
```text

PyObject_HEAD_INIT(&PyType_Type)
```
Change it to:
```text

PyObject_HEAD_INIT(NULL)
```
and add the following to the module initialization function:
```text

MyObject_Type.ob_type = &PyType_Type;
```
Refer to section 3 of the Python FAQ
(http://www.python.org/doc/FAQ.html) for details on why you must
do this.


3.3 Using DLLs in Practice

dynamic-linking.html | building-on-windows.html | embedding.html | Extending and Embedding the Python Interpreter | contents.html
---
# 3.3 Using DLLs in Practice
Windows Python is built in Microsoft Visual C++; using other
compilers may or may not work (though Borland seems to). The rest of
this section is MSVC++ specific.
When creating DLLs in Windows, you must pass python15.lib to
the linker. To build two DLLs, spam and ni (which uses C functions
found in spam), you could use these commands:
```text

cl /LD /I/python/include spam.c ../libs/python15.lib
cl /LD /I/python/include ni.c spam.lib ../libs/python15.lib
```
The first command created three files: spam.obj,
spam.dll and spam.lib. Spam.dll does not contain
any Python functions (such as PyArg_ParseTuple()), but it
does know how to find the Python code thanks to python15.lib.
The second command created ni.dll (and .obj and
.lib), which knows how to find the necessary functions from
spam, and also from the Python executable.
Not every identifier is exported to the lookup table. If you want any
other modules (including Python) to be able to see your identifiers,
you have to say "_declspec(dllexport)", as in "void
_declspec(dllexport) initspam(void)" or "PyObject
_declspec(dllexport) *NiGetSpamData(void)".
Developer Studio will throw in a lot of import libraries that you do
not really need, adding about 100K to your executable. To get rid of
them, use the Project Settings dialog, Link tab, to specify
ignore default libraries. Add the correct
msvcrtxx.lib to the list of libraries.


Python 1.6 Documentation - September 18, 2000

Python Documentation | modindex.html
---
# Python Documentation
Release 1.6
September 18, 2000
---
See About the Python Documentation (about.html)
for information on suggesting changes.


About this document ...

manual-install.html | inst.html | Installing Python Modules | contents.html
---
# About this document ...
Installing Python Modules
This document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.
LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©
1993, 1994, 1995, 1996, 1997, Nikos
Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of
Leeds, and Copyright © 1997, 1998, Ross
Moore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,
Sydney.
The application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python
documentation has been heavily tailored by Fred L. Drake,
Jr. Original navigation icons were contributed by Christopher
Petrilli.
---
## Comments and Questions
General comments and questions regarding this document should
be sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in
this document, please report the bug at the Python Bug
Tracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).
Questions regarding how to use the information in this
document should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and
carries the same content).
For any of these channels, please be sure not to send HTML email.
Thanks.
---
manual-install.html | inst.html | Installing Python Modules | contents.html
---


3 Alternate Installation

node10.html | inst.html | alt-unix-prefix.html | Installing Python Modules | contents.html
---
# 3 Alternate Installation
Often, it is necessary or desirable to install modules to a location
other than the standard location for third-party Python modules. For
example, on a Unix system you might not have permission to write to the
standard third-party module directory. Or you might wish to try out a
module before making it a standard part of your local Python
installation; this is especially true when upgrading a distribution
already present: you want to make sure your existing base of scripts
still works with the new version before actually upgrading.
The Distutils `install` command is designed to make installing
module distributions to an alternate location simple and painless. The
basic idea is that you supply a base directory for the installation, and
the `install` command picks a set of directories (called an
installation scheme) under this base directory in which to
install files. The details differ across platforms, so read whichever
of the following section applies to you.


3.4 Alternate installation: Mac OS

alt-windows.html | alt-install.html | custom-install.html | Installing Python Modules | contents.html
---
## 3.4 Alternate installation: Mac OS
Like Windows, Mac OS has no notion of home directories (or even of
users), and a fairly simple standard Python installation. Thus, only a
--prefix option is needed. It defines the installation
base, and files are installed under it as follows:
** how do MacPython users run the interpreter with command-line args? **
** Corran Webster says: ``Modules are found in either :Lib or
:Mac:Lib, while extensions usually go in
:Mac:PlugIns''--does this mean that non-pure distributions should
be divided between :Mac:PlugIns and :Mac:Lib? If so, that
changes the granularity at which we care about modules: instead of
``modules from pure distributions'' and ``modules from non-pure
distributions'', it becomes ``modules from pure distributions'',
``Python modules from non-pure distributions'', and ``extensions from
non-pure distributions''. Is this necessary?!? **


alt-unix-prefix.html | alt-install.html | alt-windows.html | Installing Python Modules | contents.html
---
## 3.2 Alternate installation: Unix (the prefix scheme)
The ``prefix scheme'' is useful when you wish to use one Python
installation to perform the build/install (i.e., to run the setup
script), but install modules into the third-party module directory of a
different Python installation (or something that looks like a different
Python installation). If this sounds a trifle unusual, it is--that's
why the ``home scheme'' comes first. However, there are at least two
known cases where the prefix scheme will be useful.
First, consider that many Linux distributions put Python in /usr,
rather than the more traditional /usr/local. This is entirely
appropriate, since in those cases Python is part of ``the system''
rather than a local add-on. However, if you are installing Python
modules from source, you probably want them to go in
/usr/local/lib/python1.X rather than
/usr/lib/python1.X. This can be done with
```text

/usr/bin/python setup.py install --prefix=/usr/local
```
Another possibility is a network filesystem where the name used to write
to a remote directory is different from the name used to read it: for
example, the Python interpreter accessed as /usr/local/bin/python
might search for modules in /usr/local/lib/python1.X,
but those modules would have to be installed to, say,
/mnt/@server/export/lib/python1.X. This
could be done with
```text

/usr/local/bin/python setup.py install --prefix=/mnt/@server/export
```
In either case, the --prefix option defines the
installation base, and the --exec-prefix option defines
the platform-specific installation base, which is used for
platform-specific files. (Currently, this just means non-pure module
distributions, but could be expanded to C libraries, binary executables,
etc.) If --exec-prefix is not supplied, it defaults to
--prefix. Files are installed as follows:
There is no requirement that --prefix or
--exec-prefix actually point to an alternate Python
installation; if the directories listed above do not already exist, they
are created at installation time.
Incidentally, the real reason the prefix scheme is important is simply
that a standard Unix installation uses the prefix scheme, but with
--prefix and --exec-prefix supplied by
Python itself (as `sys.prefix` and `sys.exec_prefix`). Thus,
you might think you'll never use the prefix scheme, but every time you
run `python setup.py install` without any other options, you're
using it.
Note that installing extensions to an alternate Python installation has
no effect on how those extensions are built: in particular, the Python
header files (Python.h and friends) installed with the Python
interpreter used to run the setup script will be used in compiling
extensions. It is your responsibility to ensure that the interpreter
used to run extensions installed in this way is compatibile with the
interpreter used to build them. The best way to do this is to ensure
that the two interpreters are the same version of Python (possibly
different builds, or possibly copies of the same build). (Of course, if
your --prefix and --exec-prefix don't even
point to an alternate Python installation, this is immaterial.)


alt-install.html | alt-install.html | alt-unix-home.html | Installing Python Modules | contents.html
---
## 3.1 Alternate installation: Unix (the home scheme)
Under Unix, there are two ways to perform an alternate installation.
The ``prefix scheme'' is similar to how alternate installation works
under Windows and Mac OS, but is not necessarily the most useful way to
maintain a personal Python library. Hence, we document the more
convenient and commonly useful ``home scheme'' first.
The idea behind the ``home scheme'' is that you build and maintain a
personal stash of Python modules, probably under your home directory.
Installing a new module distribution is as simple as
```text

python setup.py install --home=<dir>
```
where you can supply any directory you like for the --home
option. Lazy typists can just type a tilde (); the
`install` command will expand this to your home directory:
```text

python setup.py install --home=~
```
The --home option defines the installation base
directory. Files are installed to the following directories under the
installation base as follows:


3.3 Alternate installation: Windows

alt-unix-home.html | alt-install.html | alt-macos.html | Installing Python Modules | contents.html
---
## 3.3 Alternate installation: Windows
Since Windows has no conception of a user's home directory, and since
the standard Python installation under Windows is simpler than that
under Unix, there's no point in having separate --prefix
and --home options. Just use the --prefix
option to specify a base directory, e.g.
```text

python setup.py install --prefix="\Temp\Python"
```
to install modules to the \Temp directory on the current
drive.
The installation base is defined by the --prefix option;
the --exec-prefix option is not supported under Windows.
Files are installed as follows:


5 Distutils Configuration Files

custom-install.html | inst.html | pre-distutils.html | Installing Python Modules | contents.html
---
# 5 Distutils Configuration Files
** not even implemented yet, much less documented! **


Contents

inst.html | inst.html | intro.html | Installing Python Modules
---
## Contents


4 Custom Installation

alt-macos.html | inst.html | config-files.html | Installing Python Modules | contents.html
---
# 4 Custom Installation
Sometimes, the alternate installation schemes described in
section 3 (alt-install.html#alt-install) just don't do what you want. You might
want to tweak just one or two directories while keeping everything under
the same base directory, or you might want to completely redefine the
installation scheme. In either case, you're creating a custom
installation scheme.
You probably noticed the column of ``override options'' in the tables
describing the alternate installation schemes above. Those options are
how you define a custom installation scheme. These override options can
be relative, absolute, or explicitly defined in terms of one of the
installation base directories. (There are two installation base
directories, and they are normally the same--they only differ when you
use the Unix ``prefix scheme'' and supply different
--prefix and --exec-prefix options.)
For example, say you're installing a module distribution to your home
directory under Unix--but you want scripts to go in
 /scripts rather than  /bin.
As you might expect, you can override this directory with the
--install-scripts option; in this case, it makes most
sense to supply a relative path, which will be interpreted relative to
the installation base directory (your home directory, in this case):
```text

python setup.py install --home=~ --install-scripts=scripts
```
Another Unix example: suppose your Python installation was built and
installed with a prefix of /usr/local/python, so under a standard
installation scripts will wind up in /usr/local/python/bin. If
you want them in /usr/local/bin instead, you would supply this
absolute directory for the --install-scripts option:
```text

python setup.py install --install-scripts=/usr/local/bin
```
(This performs an installation using the ``prefix scheme,'' where the
prefix is whatever your Python interpreter was installed with--
/usr/local/python in this case.)
If you maintain Python on Windows, you might want third-party modules to
live in a subdirectory of prefix, rather than right in
prefix itself. This is almost as easy as customizing the
script installation directory--you just have to remember that there are
two types of modules to worry about, pure modules and non-pure modules
(i.e., modules from a non-pure distribution). For example:
```text

python setup.py install --install-purelib=Site --install-platlib=Site
```
The specified installation directories are relative to prefix.
Of course, you also have to ensure that these directories are in
Python's module search path, e.g. by putting a .pth file in
prefix (** should have a section describing .pth files and
cross-ref it here **).
If you want to define an entire installation scheme, you just have to
supply all of the installation directory options. The recommended way
to do this is to supply relative paths; for example, if you want to
maintain all Python module-related files under python in your
home directory, and you want a separate directory for each platform that
you use your home directory from, you might define the following
installation scheme:
```text

python setup.py install --home=~ \
--install-purelib=python/lib \
--install-platlib=python/lib.$PLAT \
--install-scripts=python/scripts
--install-data=python/data
```
or, equivalently,
```text

python setup.py install --home=~/python \
--install-purelib=lib \
--install-platlib='lib.$PLAT' \
--install-scripts=scripts
--install-data=data
```
`$PLAT` is not (necessarily) an environment variable--it will be
expanded by the Distutils as it parses your command line options (just
as it does when parsing your configuration file(s)).
Obviously, specifying the entire installation scheme every time you
install a new module distribution would be very tedious. Thus, you can
put these options into your Distutils config file (see
section 5 (config-files.html#config-files)):
```text

[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-data=python/data
```
or, equivalently,
```text

[install]
install-base=$HOME/python
install-purelib=lib
install-platlib=lib.$PLAT
install-scripts=scripts
install-data=data
```
Note that these two are not equivalent if you supply a different
installation base directory when you run the setup script. For example,
```text

python setup.py --install-base=/tmp
```
would install pure modules to /tmp/python/lib in the first
case, and to /tmp/lib in the second case. (For the second
case, you probably want to supply an installation base of
/tmp/python.)
You probably noticed the use of `$HOME` and `$PLAT` in the
sample configuration file input. These are Distutils configuration
variables, which bear a strong resemblance to environment variables. In
fact, you can use environment variables in config files--on platforms
that have such a notion--but the Distutils additionally define a few
extra variables that may not be in your environment, such as
`$PLAT`. (And of course, you can only use the configuration
variables supplied by the Distutils on systems that don't have
environment variables, such as Mac OS (** true? **).) See
section 5 (config-files.html#config-files) for details.
** need some Windows and Mac OS examples--when would custom
installation schemes be needed on those platforms? **


Installing Python Modules

../index.html | contents.html | Installing Python Modules | contents.html
---
# Installing Python Modules
Greg Ward
E-mail: gward@python.net


Installing Python Modules


1 Introduction

contents.html | inst.html | trivial-inst.html | Installing Python Modules | contents.html
---
# 1 Introduction
Although Python's extensive standard library covers many programming
needs, there often comes a time when you need to add some new
functionality to your Python installation in the form of third-party
modules. This might be necessary to support your own programming, or to
support an application that you want to use and that happens to be
written in Python.
In the past, there has been little support for adding third-party
modules to an existing Python installation. With the introduction of
the Python Distribution Utilities (Distutils for short) in Python 2.0,
this is starting to change. Not everything will change overnight,
though, so while this document concentrates on installing module
distributions that use the Distutils, we will also spend some time
dealing with the old ways.
This document is aimed primarily at the people who need to install
third-party Python modules: end-users and system administrators who just
need to get some Python application running, and existing Python
programmers who want to add some new goodies to their toolbox. You
don't need to know Python to read this document; there will be some
brief forays into using Python's interactive mode to explore your
installation, but that's it. If you're looking for information on how
to distribute your own Python modules so that others may use them, see
the Distributing Python Modules (../dist/dist.html) manual.


6.1 The Makefile.pre.in file

pre-distutils.html | pre-distutils.html | manual-install.html | Installing Python Modules | contents.html
---
## 6.1 The Makefile.pre.in file


6.2 Installing modules manually

makefile-pre-in.html | pre-distutils.html | about.html | Installing Python Modules | contents.html
---
## 6.2 Installing modules manually


1.2 The new standard: Distutils

trivial-inst.html | intro.html | old-way.html | Installing Python Modules | contents.html
---
## 1.2 The new standard: Distutils
If you download a module source distribution, you can tell pretty
quickly if it was packaged and distributed in the standard way, i.e.
using the Distutils. First, the distribution's name and version number
will be featured prominently in the name of the downloaded archive, e.g.
foo-1.0.tar.gz or widget-0.9.7.zip. Next, the archive
will unpack into a similarly-named directory: foo-1.0 or
widget-0.9.7. Additionally, the distribution will contain a
setup script setup.py, and a README.txt (or possibly
README), which should explain that building and installing the
module distribution is a simple matter of running
```text

python setup.py install
```
If all these things are true, then you already know how to build and
install the modules you've just downloaded: run the command above.
Unless you need to install things in a non-standard way or customize the
build process, you don't really need this manual. Or rather, the above
command is everything you need to get out of this manual.


2.4 How installation works

node9.html | normal-install.html | alt-install.html | Installing Python Modules | contents.html
---
## 2.4 How installation works
After the `build` command runs (whether you run it explicitly,
or the `install` command does it for you), the work of the
`install` command is relatively simple: all it has to do is copy
everything under build/lib (or build/lib.plat)
to your chosen installation directory.
If you don't choose an installation directory--i.e., if you just run
`setup.py install`--then the `install` command installs to
the standard location for third-party Python modules. This location
varies by platform and by how you built/installed Python itself. On
Unix and Mac OS, it also depends on whether the module distribution
being installed is pure Python or contains extensions (``non-pure''):
Notes:
(1): Most Linux distributions include Python as a standard part of
the system, so prefix and exec-prefix are usually
both /usr on Linux. If you build Python yourself on Linux (or
any Unix-like system), the default prefix and
exec-prefix are /usr/local.
(2): The default installation directory on Windows was
C:\Program Files\Python under
Python 1.6a1, 1.5.2, and earlier.
prefix and exec-prefix stand for the directories
that Python is installed to, and where it finds its libraries at
run-time. They are always the same under Windows and Mac OS, and very
often the same under Unix. You can find out what your Python
installation uses for prefix and exec-prefix by
running Python in interactive mode and typing a few simple commands.
Under Unix, just type `python` at the shell prompt; under Windows,
run ``Python 2.0 (interpreter)'' ** right? **; under Mac OS, ** ??? **.
Once the interpreter is started, you type Python code at the
"»> " prompt. For example, on my Linux system, I type the three
Python statements shown below, and get the output as shown, to find
out my prefix and exec-prefix:
```text

Python 1.6 (#22, Sep 2 2000, 23:54:55) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Copyright (c) 1995-2000 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
>>> import sys
>>> sys.prefix
'/usr'
>>> sys.exec_prefix
'/usr'
```
If you don't want to install to the standard location, or if you don't
have permission to write there, then you need to read about alternate
installations in the next section.


2.1 Platform variations

normal-install.html | normal-install.html | node8.html | Installing Python Modules | contents.html
---
## 2.1 Platform variations
You should always run the setup command from the distribution root
directory, i.e. the top-level subdirectory that the module source
distribution unpacks into. For example, if you've just downloaded a
module source distribution foo-1.0.tar.gz onto a Unix system, the
normal thing to do is:
```text

gunzip -c foo-1.0.tar.gz | tar xf - # unpacks into directory foo-1.0
cd foo-1.0
python setup.py install
```
On Windows, you'd probably unpack the archive before opening the command
prompt. If you downloaded the archive file to
C:\Temp, then it probably unpacked (depending on
your software) into
C:\Temp\foo-1.0; from the command
prompt window, you would then run
```text

cd c:\temp\foo-1.0
python setup.py install
```
On Mac OS, ... ** again, how do you run Python scripts on Mac OS? **
** arg, my lovely ``bslash'' macro doesn't work in non-tt fonts! help
me LATEX, you're my only hope... **


2.2 Splitting the job up

node7.html | normal-install.html | node9.html | Installing Python Modules | contents.html
---
## 2.2 Splitting the job up
Running `setup.py install` builds and installs all modules in one
fell swoop. If you prefer to work incrementally--especially useful if
you want to customize the build process, or if things are going
wrong--you can use the setup script to do one thing at a time. This is
particularly helpful when the build and install will be done by
different users--e.g., you might want to build a module distribution
and hand it off to a system administrator for installation (or do it
yourself, with super-user privileges).
For example, you can build everything in one step, and then install
everything in a second step, by invoking the setup script twice:
```text

python setup.py build
python setup.py install
```
(If you do this, you will notice that running the `install`
command first runs the `build` command, which quickly notices
that it has nothing to do, since everything in the build
directory is up-to-date.)
** concrete reason for splitting things up? **


2.3 How building works

node8.html | normal-install.html | node10.html | Installing Python Modules | contents.html
---
## 2.3 How building works
As implied above, the `build` command is responsible for putting
the files to install into a build directory. By default, this is
build under the distribution root; if you're excessively
concerned with speed, or want to keep the source tree pristine, you can
change the build directory with the --build-base option.
For example:
```text

python setup.py build --build-base=/tmp/pybuild/foo-1.0
```
(Or you could do this permanently with a directive in your system or
personal Distutils configuration file; see
section 5 (config-files.html#config-files).) Normally, this isn't necessary.
The default layout for the build tree is as follows:
```text

--- build/ --- lib/
or
--- build/ --- lib.<plat>/
temp.<plat>/
```
where `<plat>` expands to a brief description of the current
OS/hardware platform. The first form, with just a lib directory,
is used for ``pure module distributions''--that is, module
distributions that include only pure Python modules. If a module
distribution contains any extensions (modules written in C/C++, or Java
for JPython), then the second form, with two `<plat>` directories,
is used. In that case, the temp.plat directory holds
temporary files generated by the compile/link process that don't
actually get installed. In either case, the lib (or
lib.plat) directory contains all Python modules (pure
Python and extensions) that will be installed.
In the future, more directories will be added to handle Python scripts,
documentation, binary executables, and whatever else is needed to handle
the job of installing Python modules and applications.


2 Standard Build and Install

old-way.html | inst.html | node7.html | Installing Python Modules | contents.html
---
# 2 Standard Build and Install
As described in section 1.2 (new-standard.html#new-standard), building and installing
a module distribution using the Distutils is usually one simple command:
```text

python setup.py install
```
On Unix, you'd run this command from a shell prompt; on Windows, you
have to open a command prompt window and do it there; on Mac OS ...
** what the heck do you do on Mac OS? **.


1.3 The old way: no standards

new-standard.html | intro.html | normal-install.html | Installing Python Modules | contents.html
---
## 1.3 The old way: no standards
Before the Distutils, there was no infrastructure to support installing
third-party modules in a consistent, standardized way. Thus, it's not
really possible to write a general manual for installing Python modules
that don't use the Distutils; the only truly general statement that can
be made is, ``Read the module's own installation instructions.''
However, if such instructions exist at all, they are often woefully
inadequate and targeted at experienced Python developers. Such users
are already familiar with how the Python library is laid out on their
platform, and know where to copy various files in order for Python to
find them. This document makes no such assumptions, and explains how
the Python library is laid out on three major platforms (Unix, Windows,
and Mac OS), so that you can understand what happens when the Distutils
do their job and know how to install modules manually when the
module author fails to provide a setup script.
Additionally, while there has not previously been a standard
installation mechanism, Python has had some standard machinery for
building extensions on Unix since Python ** version? **. This machinery
(the Makefile.pre.in file) is superseded by the Distutils, but it
will no doubt live on in older module distributions for a while. This
Makefile.pre.in mechanism is documented in the ``Extending &
Embedding Python'' manual, but that manual is aimed at module
developers--hence, we include documentation for builders/installers
here.
All of the pre-Distutils material is tucked away in
section 6 (pre-distutils.html#pre-distutils).


6 Pre-Distutils Conventions

config-files.html | inst.html | makefile-pre-in.html | Installing Python Modules | contents.html
---
# 6 Pre-Distutils Conventions


1.1 Best case: trivial installation

intro.html | intro.html | new-standard.html | Installing Python Modules | contents.html
---
## 1.1 Best case: trivial installation
In the best case, someone will have prepared a special version of the
module distribution you want to install that is targeted specifically at
your platform and is installed just like any other software on your
platform. For example, the module developer might make an executable
installer available for Windows users, an RPM package for users of
RPM-based Linux systems (Red Hat, SuSE, Mandrake, and many others), a
Debian package for users of Debian-based Linux systems (Debian proper,
Caldera, Corel, etc.), and so forth.
In that case, you would download the installer appropriate to your
platform and do the obvious thing with it: run it if it's an executable
installer, `rpm -install` it if it's an RPM, etc. You don't need
to run Python or a setup script, you don't need to compile
anything--you might not even need to read any instructions (although
it's always a good idea to do so anyways).
Of course, things will not always be that easy. You might be interested
in a module distribution that doesn't have an easy-to-use installer for
your platform. In that case, you'll have to start with the source
distribution released by the module's author/maintainer. Installing
from a source distribution is not too hard, as long as the modules are
packaged in the standard way. The bulk of this document is about
building and installing modules from standard source distributions.


About this document ...

genindex.html | lib.html | Python Library Reference | contents.html | genindex.html
---
# About this document ...
Python Library Reference,
September 18, 2000, Release 1.6
This document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.
LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©
1993, 1994, 1995, 1996, 1997, Nikos
Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of
Leeds, and Copyright © 1997, 1998, Ross
Moore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,
Sydney.
The application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python
documentation has been heavily tailored by Fred L. Drake,
Jr. Original navigation icons were contributed by Christopher
Petrilli.
---
## Comments and Questions
General comments and questions regarding this document should
be sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in
this document, please report the bug at the Python Bug
Tracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).
Questions regarding how to use the information in this
document should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and
carries the same content).
For any of these channels, please be sure not to send HTML email.
Thanks.
---
genindex.html | lib.html | Python Library Reference | contents.html | genindex.html
---


12.6.2 AddressList Objects

message-objects.html | module-rfc822.html | module-mimetools.html | Python Library Reference | contents.html | genindex.html
---
## 12.6.2 AddressList Objects
An AddressList instance has the following methods:
Finally, AddressList instances have one public instance variable:


16.1.1 Configuration Objects

module-al.html | module-al.html | al-port-objects.html | Python Library Reference | contents.html | genindex.html
---
## 16.1.1 Configuration Objects
Configuration objects (returned by newconfig() have the
following methods:


16.1.2 Port Objects

al-config-objects.html | module-al.html | module-al-constants.html | Python Library Reference | contents.html | genindex.html
---
## 16.1.2 Port Objects
Port objects, as returned by openport(), have the following
methods:


6. Generic Operating System Services

shlex-objects.html | lib.html | module-os.html | Python Library Reference | contents.html | genindex.html
---
# 6. Generic Operating System Services
The modules described in this chapter provide interfaces to operating
system features that are available on (almost) all operating systems,
such as files and a clock. The interfaces are generally modelled
after the Unix or C interfaces, but they are available on most
other systems as well. Here's an overview:


3.16.4 Exceptions and Error Handling

Querying_ASTs.html | module-parser.html | AST_Objects.html | Python Library Reference | contents.html | genindex.html
---
## 3.16.4 Exceptions and Error Handling
The parser module defines a single exception, but may also pass other
built-in exceptions from other portions of the Python runtime
environment. See each function for information about the exceptions
it can raise.
Note that the functions compileast(), expr(), and
suite() may throw exceptions which are normally thrown by the
parsing and compilation process. These include the built in
exceptions MemoryError, OverflowError,
SyntaxError, and SystemError. In these cases, these
exceptions carry all the meaning normally associated with them. Refer
to the descriptions of each function for detailed information.


3.16.6 Examples

AST_Objects.html | module-parser.html | node55.html | Python Library Reference | contents.html | genindex.html
---
## 3.16.6 Examples
The parser modules allows operations to be performed on the parse tree
of Python source code before the bytecode is generated, and provides
for inspection of the parse tree for information gathering purposes.
Two examples are presented. The simple example demonstrates emulation
of the compile() built-in function and
the complex example shows the use of a parse tree for information
discovery.


3.16.5 AST Objects

AST_Errors.html | module-parser.html | AST_Examples.html | Python Library Reference | contents.html | genindex.html
---
## 3.16.5 AST Objects
Ordered and equality comparisons are supported between AST objects.
Pickling of AST objects (using the pickle (module-pickle.html) module) is also
supported.
AST objects have the following methods:


11.16.1 Example basic HTTP client

module-asyncore.html | module-asyncore.html | netdata.html | Python Library Reference | contents.html | genindex.html
---
## 11.16.1 Example basic HTTP client
As a basic example, below is a very basic HTTP client that uses the
dispatcher class to implement its socket handling:
```text

class http_client(asyncore.dispatcher):
def __init__(self, host,path):
asyncore.dispatcher.__init__(self)
self.path = path
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect( (host, 80) )
self.buffer = 'GET %s HTTP/1.0\r\b\r\n' % self.path

def handle_connect(self):
pass

def handle_read(self):
data = self.recv(8192)
print data

def writeable(self):
return (len(self.buffer) > 0)

def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
```


14.4.1 AU_read Objects

module-sunau.html | module-sunau.html | au-write-objects.html | Python Library Reference | contents.html | genindex.html
---
## 14.4.1 AU_read Objects
AU_read objects, as returned by open() above, have the
following methods:
The following two methods define a term ``position'' which is compatible
between them, and is otherwise implementation dependant.
The following two functions are defined for compatibility with the
aifc (module-aifc.html), and don't do anything interesting.


14.4.2 AU_write Objects

au-read-objects.html | module-sunau.html | module-wave.html | Python Library Reference | contents.html | genindex.html
---
## 14.4.2 AU_write Objects
AU_write objects, as returned by open() above, have the
following methods:


17.1.1 Audio Device Objects

module-sunaudiodev.html | module-sunaudiodev.html | module-sunaudiodev-constants.html | Python Library Reference | contents.html | genindex.html
---
## 17.1.1 Audio Device Objects
The audio device objects are returned by open() define the
following methods (except `control` objects which only provide
getinfo(), setinfo(), fileno(), and
drain()):
The audio device supports asynchronous notification of various events,
through the SIGPOLL signal. Here's an example of how you might enable
this in Python:
```text

def handle_sigpoll(signum, frame):
print 'I got a SIGPOLL update'

import fcntl, signal, STROPTS

signal.signal(signal.SIGPOLL, handle_sigpoll)
fcntl.ioctl(audio_obj.fileno(), STROPTS.I_SETSIG, STROPTS.S_MSG)
```


12.10.1 Notes

module-binhex.html | module-binhex.html | module-uu.html | Python Library Reference | contents.html | genindex.html
---
## 12.10.1 Notes
There is an alternative, more powerful interface to the coder and
decoder, see the source for details.
If you code or decode textfiles on non-Macintosh platforms they will
still use the Macintosh newline convention (carriage-return as end of
line).


5.5.1 Example

module-bisect.html | module-bisect.html | module-array.html | Python Library Reference | contents.html | genindex.html
---
## 5.5.1 Example
The bisect() function is generally useful for categorizing
numeric data. This example uses bisect() to look up a
letter grade for an exam total (say) based on a set of ordered numeric
breakpoints: 85 and up is an `A', 75..84 is a `B', etc.


typesnumeric.html | typesnumeric.html | typesseq.html | Python Library Reference | contents.html | genindex.html
---
### 2.1.4.1 Bit-string Operations on Integer Types
Plain and long integer types support additional operations that make
sense only for bit-strings. Negative numbers are treated as their 2's
complement value (for long integers, this assumes a sufficiently large
number of bits that no overflow occurs during the operation).
The priorities of the binary bit-wise operations are all lower than
the numeric operations and higher than the comparisons; the unary
operation "~" has the same priority as the other unary numeric
operations ("+" and "-").
This table lists the bit-string operations sorted in ascending
priority (operations in the same box have the same priority):
Notes:
(1): Negative shift counts are illegal and cause a
ValueError to be raised.
(2): A left shift by n bits is equivalent to
multiplication by `pow(2, n )` without overflow check.
(3): A right shift by n bits is equivalent to
division by `pow(2, n )` without overflow check.


2.1.7.5 Code Objects

typesmethods.html | typesother.html | bltin-type-objects.html | Python Library Reference | contents.html | genindex.html
---
### 2.1.7.5 Code Objects
Code objects are used by the implementation to represent
``pseudo-compiled'' executable Python code such as a function body.
They differ from function objects because they don't contain a
reference to their global execution environment. Code objects are
returned by the built-in compile() function and can be
extracted from function objects through their func_code
attribute.
A code object can be executed or evaluated by passing it (instead of a
source string) to the exec statement or the built-in
eval() function.
See the Python Reference Manual (../ref/ref.html) for more
information.


2.1.7.8 The Ellipsis Object

bltin-null-object.html | typesother.html | bltin-file-objects.html | Python Library Reference | contents.html | genindex.html
---
### 2.1.7.8 The Ellipsis Object
This object is used by extended slice notation (see the
Python Reference Manual (../ref/ref.html)). It supports no
special operations. There is exactly one ellipsis object, named
Ellipsis (a built-in name).
It is written as `Ellipsis`.


2.1.7.9 File Objects

bltin-ellipsis-object.html | typesother.html | typesinternal.html | Python Library Reference | contents.html | genindex.html
---
### 2.1.7.9 File Objects
File objects are implemented using C's `stdio`package and can be created with the built-in function
open() described in section
2.3 (built-in-funcs.html#built-in-funcs), ``Built-in Functions.'' They are also returned
by some other built-in functions and methods, e.g.,
posix.popen() and posix.fdopen() and the
makefile() method of socket objects.
When a file operation fails for an I/O-related reason, the exception
IOError is raised. This includes situations where the
operation is not defined for some reason, like seek() on a tty
device or writing a file opened for reading.
Files have the following methods:
File objects also offer the following attributes:


2.1.7.7 The Null Object

bltin-type-objects.html | typesother.html | bltin-ellipsis-object.html | Python Library Reference | contents.html | genindex.html
---
### 2.1.7.7 The Null Object
This object is returned by functions that don't explicitly return a
value. It supports no special operations. There is exactly one null
object, named `None` (a built-in name).
It is written as `None`.


2.1.7.6 Type Objects

bltin-code-objects.html | typesother.html | bltin-null-object.html | Python Library Reference | contents.html | genindex.html
---
### 2.1.7.6 Type Objects
Type objects represent the various object types. An object's type is
accessed by the built-in function type(). There are no special
operations on types. The standard module types defines names
for all standard built-in types.
Types are written like this: `<type 'int'>`.


2.1.2 Boolean Operations

truth.html | types.html | comparisons.html | Python Library Reference | contents.html | genindex.html
---
## 2.1.2 Boolean Operations
These are the Boolean operations, ordered by ascending priority:
Notes:
(1): These only evaluate their second argument if needed for their outcome.
(2): "not" has a lower priority than non-Boolean operators, so
`not a == b` is interpreted as `not ( a == b )`, and `a == not b` is a syntax error.


7.11.1 Hash, BTree and Record Objects

module-bsddb.html | module-bsddb.html | module-zlib.html | Python Library Reference | contents.html | genindex.html
---
## 7.11.1 Hash, BTree and Record Objects
Once instantiated, hash, btree and record objects support the following
methods:
Example:


2.3 Built-in Functions

module-exceptions.html | builtin.html | python.html | Python Library Reference | contents.html | genindex.html
---
# 2.3 Built-in Functions
The Python interpreter has a number of functions built into it that
are always available. They are listed here in alphabetical order.


intro.html | lib.html | types.html | Python Library Reference | contents.html | genindex.html
---
# 2. Built-in Types, Exceptions and Functions
Names for built-in exceptions and functions are found in a separate
symbol table. This table is searched last when the interpreter looks
up the meaning of a name, so local and global
user-defined names can override built-in names. Built-in types are
described together here for easy reference.2.1 (#foot127)
The tables in this chapter document the priorities of operators by
listing them in order of ascending priority (within a table) and
grouping operators that have the same priority in the same box.
Binary operators of the same priority group from left to right.
(Unary operators group from right to left, but there you have no real
choice.) See Chapter 5 of the Python
Reference Manual (../ref/ref.html) for the complete picture on operator priorities.
---
#### Footnotes


3.29.1 Python Byte Code Instructions

module-dis.html | module-dis.html | module-new.html | Python Library Reference | contents.html | genindex.html
---
## 3.29.1 Python Byte Code Instructions
The Python compiler currently generates the following byte code
instructions.
Unary Operations take the top of the stack, apply the operation, and
push the result back on the stack.
Binary operations remove the top of the stack (TOS) and the second top-most
stack item (TOS1) from the stack. They perform the operation, and put the
result back on the stack.
The slice opcodes take up to three parameters.
Slice assignment needs even an additional parameter. As any statement,
they put nothing on the stack.
All of the following opcodes expect arguments. An argument is two
bytes, with the more significant byte last.


16.3.2 Parser Objects

player-objects.html | module-cd.html | module-fl.html | Python Library Reference | contents.html | genindex.html
---
## 16.3.2 Parser Objects
Parser objects (returned by createparser()) have the
following methods:


11.1.1 Introduction

module-cgi.html | module-cgi.html | Using_the_cgi_module.html | Python Library Reference | contents.html | genindex.html
---
## 11.1.1 Introduction
A CGI script is invoked by an HTTP server, usually to process user
input submitted through an HTML `<FORM>` or `<ISINDEX>` element.
Most often, CGI scripts live in the server's special cgi-bin
directory. The HTTP server places all sorts of information about the
request (such as the client's hostname, the requested URL, the query
string, and lots of other goodies) in the script's shell environment,
executes the script, and sends the script's output back to the client.
The script's input is connected to the client too, and sometimes the
form data is read this way; at other times the form data is passed via
the ``query string'' part of the URL. This module is intended
to take care of the different cases and provide a simpler interface to
the Python script. It also provides a number of utilities that help
in debugging scripts, and the latest addition is support for file
uploads from a form (if your browser supports it -- Grail 0.3 and
Netscape 2.0 do).
The output of a CGI script should consist of two sections, separated
by a blank line. The first section contains a number of headers,
telling the client what kind of data is following. Python code to
generate a minimal header section looks like this:
```text

print "Content-type: text/html" # HTML is following
print # blank line, end of headers
```
The second section is usually HTML, which allows the client software
to display nicely formatted text with header, in-line images, etc.
Here's Python code that prints a simple piece of HTML:
```text

print "<TITLE>CGI script output</TITLE>"
print "<H1>This is my first CGI script</H1>"
print "Hello, world!"
```
(It may not be fully legal HTML according to the letter of the
standard, but any browser will understand it.)


5.10.1 Cmd Objects

module-cmd.html | module-cmd.html | module-shlex.html | Python Library Reference | contents.html | genindex.html
---
## 5.10.1 Cmd Objects
A Cmd instance has the following methods:
Instances of Cmd subclasses have some public instance variables:


2.1.3 Comparisons

boolean.html | types.html | typesnumeric.html | Python Library Reference | contents.html | genindex.html
---
## 2.1.3 Comparisons
Comparison operations are supported by all objects. They all have the
same priority (which is higher than that of the Boolean operations).
Comparisons can be chained arbitrarily; for example, `x < y <= z` is equivalent to `x < y and y <= z`, except that y is evaluated only once (but
in both cases z is not evaluated at all when `x < y` is found to be false).
This table summarizes the comparison operations:
Notes:
(1): `<>` and `!=` are alternate spellings for the same operator.
(I couldn't choose between ABC and C! :-)
`!=` is the preferred spelling; `<>` is obsolescent.
Objects of different types, except different numeric types, never
compare equal; such objects are ordered consistently but arbitrarily
(so that sorting a heterogeneous array yields a consistent result).
Furthermore, some types (for example, file objects) support only a
degenerate notion of comparison where any two objects of that type are
unequal. Again, such objects are ordered arbitrarily but
consistently.
Instances of a class normally compare as non-equal unless the class
defines the __cmp__() method. Refer to the Python
Reference Manual for information on the use of this method to effect
object comparisons.
Implementation note: Objects of different types except
numbers are ordered by their type names; objects of the same types
that don't support proper comparison are ordered by their address.
Two more operations with the same syntactic priority,
"in" and "not in", are supported
only by sequence types (below).


7.15.1 Completer Objects

module-rlcompleter.html | module-rlcompleter.html | unix.html | Python Library Reference | contents.html | genindex.html
---
## 7.15.1 Completer Objects
Completer objects have the following method:


7.5.3 Condition Objects

rlock-objects.html | module-threading.html | semaphore-objects.html | Python Library Reference | contents.html | genindex.html
---
## 7.5.3 Condition Objects
A condition variable is always associated with some kind of lock;
this can be passed in or one will be created by default. (Passing
one in is useful when several condition variables must share the
same lock.)
A condition variable has acquire() and release()
methods that call the corresponding methods of the associated lock.
It also has a wait() method, and notify() and
notifyAll() methods. These three must only be called when
the calling thread has acquired the lock.
The wait() method releases the lock, and then blocks until it
is awakened by a notify() or notifyAll() call for
the same condition variable in another thread. Once awakened, it
re-acquires the lock and returns. It is also possible to specify a
timeout.
The notify() method wakes up one of the threads waiting for
the condition variable, if any are waiting. The notifyAll()
method wakes up all threads waiting for the condition variable.
Note: the notify() and notifyAll() methods don't
release the lock; this means that the thread or threads awakened will
not return from their wait() call immediately, but only when
the thread that called notify() or notifyAll()
finally relinquishes ownership of the lock.
Tip: the typical programming style using condition variables uses the
lock to synchronize access to some shared state; threads that are
interested in a particular change of state call wait()
repeatedly until they see the desired state, while threads that modify
the state call notify() or notifyAll() when they
change the state in such a way that it could possibly be a desired
state for one of the waiters. For example, the following code is a
generic producer-consumer situation with unlimited buffer capacity:
```text

# Consume one item
cv.acquire()
while not an_item_is_available():
cv.wait()
get_an_available_item()
cv.release()

# Produce one item
cv.acquire()
make_an_item_available()
cv.notify()
cv.release()
```
To choose between notify() and notifyAll(), consider
whether one state change can be interesting for only one or several
waiting threads. E.g. in a typical producer-consumer situation,
adding one item to the buffer only needs to wake up one consumer
thread.


5.7.1 ConfigParser Objects

module-ConfigParser.html | module-ConfigParser.html | module-fileinput.html | Python Library Reference | contents.html | genindex.html
---
## 5.7.1 ConfigParser Objects
ConfigParser instances have the following methods:


3.23.2 Interactive Console Objects

interpreter-objects.html | module-code.html | module-codeop.html | Python Library Reference | contents.html | genindex.html
---
## 3.23.2 Interactive Console Objects
The InteractiveConsole class is a subclass of
InteractiveInterpreter, and so offers all the methods of the
interpreter objects as well as the following additions.


Contents

front.html | lib.html | intro.html | Python Library Reference | genindex.html
---
## Contents


4.2.3 Module Contents

matching-searching.html | module-re.html | re-objects.html | Python Library Reference | contents.html | genindex.html
---
## 4.2.3 Module Contents
The module defines the following functions and constants, and an exception:


4.3.2 Module Contents

node91.html | module-regex.html | module-regsub.html | Python Library Reference | contents.html | genindex.html
---
## 4.3.2 Module Contents
The module defines these functions, and an exception:
Compiled regular expression objects support these methods:
Compiled regular expressions support these data attributes:


3.16.2 Converting AST Objects

Creating_ASTs.html | module-parser.html | Querying_ASTs.html | Python Library Reference | contents.html | genindex.html
---
## 3.16.2 Converting AST Objects
AST objects, regardless of the input used to create them, may be
converted to parse trees represented as list- or tuple- trees, or may
be compiled into executable code objects. Parse trees may be
extracted with or without line numbering information.


3.16.1 Creating AST Objects

module-parser.html | module-parser.html | Converting_ASTs.html | Python Library Reference | contents.html | genindex.html
---
## 3.16.1 Creating AST Objects
AST objects may be created from source code or from a parse tree.
When creating an AST object from source, different functions are used
to create the `'eval'` and `'exec'` forms.


15. Cryptographic Services

module-sndhdr.html | lib.html | module-md5.html | Python Library Reference | contents.html | genindex.html
---
# 15. Cryptographic Services
The modules described in this chapter implement various algorithms of
a cryptographic nature. They are available at the discretion of the
installation. Here's an overview:
md5 (module-md5.html) | RSA's MD5 message digest algorithm.
sha (module-sha.html) | NIST's secure hash algorithm, SHA.
mpz (module-mpz.html) | Interface to the GNU MP library for arbitrary
precision arithmetic.
rotor (module-rotor.html) | Enigma-like encryption and decryption.


6.11.1 Constants and Functions

module-curses.html | module-curses.html | curses-window-objects.html | Python Library Reference | contents.html | genindex.html
---
## 6.11.1 Constants and Functions
The curses module defines the following data members:
The module curses defines the following exception:
Note: Whenever x or y arguments to a function
or a method are optional, they default to the current cursor location.
Whenever attr is optional, it defaults to A_NORMAL.
The module curses defines the following functions:


6.11.2 Window Objects

curses-functions.html | module-curses.html | module-getopt.html | Python Library Reference | contents.html | genindex.html
---
## 6.11.2 Window Objects
Window objects, as returned by initscr() and
newwin() above, have the
following methods:


7.9.1 Database Objects

module-dbhash.html | module-dbhash.html | module-whichdb.html | Python Library Reference | contents.html | genindex.html
---
## 7.9.1 Database Objects
The database objects returned by open() provide the methods
common to all the DBM-style databases. The following methods are
available in addition to the standard methods.


9.1 Debugger Commands

module-pdb.html | module-pdb.html | node209.html | Python Library Reference | contents.html | genindex.html
---
# 9.1 Debugger Commands
The debugger recognizes the following commands. Most commands can be
abbreviated to one or two letters; e.g. "h(elp)" means that
either "h" or "help" can be used to enter the help
command (but not "he" or "hel", nor "H" or
"Help" or "HELP"). Arguments to commands must be
separated by whitespace (spaces or tabs). Optional arguments are
enclosed in square brackets ("[]") in the command syntax; the
square brackets must not be typed. Alternatives in the command syntax
are separated by a vertical bar ("|").
Entering a blank line repeats the last command entered. Exception: if
the last command was a "list" command, the next 11 lines are
listed.
Commands that the debugger doesn't recognize are assumed to be Python
statements and are executed in the context of the program being
debugged. Python statements can also be prefixed with an exclamation
point ("!"). This is a powerful way to inspect the program
being debugged; it is even possible to change a variable or call a
function. When an
exception occurs in such a statement, the exception name is printed
but the debugger's state is not changed.
Multiple commands may be entered on a single line, separated by
";;". (A single ";" is not used as it is
the separator for multiple commands in a line that is passed to
the Python parser.)
No intelligence is applied to separating the commands;
the input is split at the first ";;" pair, even if it is in
the middle of a quoted string.
The debugger supports aliases. Aliases can have parameters which
allows one a certain level of adaptability to the context under
examination.
If a file .pdbrc
exists in the user's home directory or in the current directory, it is
read in and executed as if it had been typed at the debugger prompt.
This is particularly useful for aliases. If both files exist, the one
in the home directory is read first and aliases defined there can be
overriden by the local file.
h(elp) [command]: Without argument, print the list of available commands. With a
command as argument, print help about that command. "help
pdb" displays the full documentation file; if the environment variable
$PAGER is defined, the file is piped through that command
instead. Since the command argument must be an identifier,
"help exec" must be entered to get help on the "!" command.
w(here): Print a stack trace, with the most recent frame at the bottom. An
arrow indicates the current frame, which determines the context of
most commands.
d(own): Move the current frame one level down in the stack trace
(to an newer frame).
u(p): Move the current frame one level up in the stack trace
(to a older frame).
b(reak) [[filename:]lineno`|`function[, condition]]: With a lineno argument, set a break there in the current
file. With a function argument, set a break at the first
executable statement within that function.
The line number may be prefixed with a filename and a colon,
to specify a breakpoint in another file (probably one that
hasn't been loaded yet). The file is searched on `sys.path`.
Note that each breakpoint is assigned a number to which all the other
breakpoint commands refer.
If a second argument is present, it is an expression which must
evaluate to true before the breakpoint is honored.
Without argument, list all breaks, including for each breakpoint,
the number of times that breakpoint has been hit, the current
ignore count, and the associated condition if any.
tbreak [[filename:]lineno`|`function[, condition]]: Temporary breakpoint, which is removed automatically when it is
first hit. The arguments are the same as break.
cl(ear) [bpnumber [bpnumber ...]]: With a space separated list of breakpoint numbers, clear those
breakpoints. Without argument, clear all breaks (but first
ask confirmation).
disable [bpnumber [bpnumber ...]]: Disables the breakpoints given as a space separated list of
breakpoint numbers. Disabling a breakpoint means it cannot cause
the program to stop execution, but unlike clearing a breakpoint, it
remains in the list of breakpoints and can be (re-)enabled.
enable [bpnumber [bpnumber ...]]: Enables the breakpoints specified.
ignore bpnumber [count]: Sets the ignore count for the given breakpoint number. If
count is omitted, the ignore count is set to 0. A breakpoint
becomes active when the ignore count is zero. When non-zero,
the count is decremented each time the breakpoint is reached
and the breakpoint is not disabled and any associated condition
evaluates to true.
condition bpnumber [condition]: Condition is an expression which must evaluate to true before
the breakpoint is honored. If condition is absent, any existing
condition is removed; i.e., the breakpoint is made unconditional.
s(tep): Execute the current line, stop at the first possible occasion
(either in a function that is called or on the next line in the
current function).
n(ext): Continue execution until the next line in the current function
is reached or it returns. (The difference between "next" and
"step" is that "step" stops inside a called function, while
"next" executes called functions at (nearly) full speed, only
stopping at the next line in the current function.)
r(eturn): Continue execution until the current function returns.
c(ont(inue)): Continue execution, only stop when a breakpoint is encountered.
l(ist) [first[, last]]: List source code for the current file. Without arguments, list 11
lines around the current line or continue the previous listing. With
one argument, list 11 lines around at that line. With two arguments,
list the given range; if the second argument is less than the first,
it is interpreted as a count.
a(rgs): Print the argument list of the current function.
p expression: Evaluate the expression in the current context and print its
value. (Note: "print" can also be used, but is not a debugger
command -- this executes the Python print statement.)
alias [name [command]]: Creates an alias called name that executes command. The
command must not be enclosed in quotes. Replaceable parameters
can be indicated by "%1", "%2", and so on, while "%*" is
replaced by all the parameters. If no command is given, the current
alias for name is shown. If no arguments are given, all
aliases are listed.
Aliases may be nested and can contain anything that can be
legally typed at the pdb prompt. Note that internal pdb commands
can be overridden by aliases. Such a command is
then hidden until the alias is removed. Aliasing is recursively
applied to the first word of the command line; all other words
in the line are left alone.
As an example, here are two useful aliases (especially when placed
in the .pdbrc file):
```text

#Print instance variables (usage "pi classInst")
alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
#Print instance variables in self
alias ps pi self
```
unalias name: Deletes the specified alias.
[!]statement: Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To set a global variable, you can prefix the assignment
command with a "global" command on the same line, e.g.:
```text

(Pdb) global list_options; list_options = ['-l']
(Pdb)
```
q(uit): Quit from the debugger.
The program being executed is aborted.


10.4 What Is Deterministic Profiling?

profile-instant.html | profile.html | module-profile.html | Python Library Reference | contents.html | genindex.html
---
# 10.4 What Is Deterministic Profiling?
Deterministic profiling is meant to reflect the fact that all
function call, function return, and exception events
are monitored, and precise timings are made for the intervals between
these events (during which time the user's code is executing). In
contrast, statistical profiling (which is not done by this
module) randomly samples the effective instruction pointer, and
deduces where time is being spent. The latter technique traditionally
involves less overhead (as the code does not need to be instrumented),
but provides only relative indications of where time is being spent.
In Python, since there is an interpreter active during execution, the
presence of instrumented code is not required to do deterministic
profiling. Python automatically provides a hook (optional
callback) for each event. In addition, the interpreted nature of
Python tends to add so much overhead to execution, that deterministic
profiling tends to only add small processing overhead in typical
applications. The result is that deterministic profiling is not that
expensive, yet provides extensive run time statistics about the
execution of a Python program.
Call count statistics can be used to identify bugs in code (surprising
counts), and to identify possible inline-expansion points (high call
counts). Internal time statistics can be used to identify ``hot
loops'' that should be carefully optimized. Cumulative time
statistics should be used to identify high level errors in the
selection of algorithms. Note that the unusual handling of cumulative
times in this profiler allows statistics for recursive implementations
of algorithms to be directly compared to iterative implementations.


8.5.1 Dl Objects

module-dl.html | module-dl.html | module-dbm.html | Python Library Reference | contents.html | genindex.html
---
## 8.5.1 Dl Objects
Dl objects, as returned by open() above, have the
following methods:


node145.html | module-locale.html | module-mutex.html | Python Library Reference | contents.html | genindex.html
---
## 6.18.2 For extension writers and programs that embed Python
Extension modules should never call setlocale(), except to
find out what the current locale is. But since the return value can
only be used portably to restore it, that is not very useful (except
perhaps to find out whether or not the locale is "C").
When Python is embedded in an application, if the application sets the
locale to something specific before initializing Python, that is
generally okay, and Python will use whatever locale is set,
except that the LC_NUMERIC locale should always be
"C".
The setlocale() function in the locale module
gives the Python progammer the impression that you can manipulate the
LC_NUMERIC locale setting, but this not the case at the C
level: C code will always find that the LC_NUMERIC locale
setting is "C". This is because too much would break when the
decimal point character is set to something else than a period
(e.g. the Python parser would break). Caveat: threads that run
without holding Python's global interpreter lock may occasionally find
that the numeric locale setting differs; this is because the only
portable way to implement this feature is to set the numeric locale
settings to what the user requests, extract the relevant
characteristics, and then restore the "C" numeric locale.


7.5.5 Event Objects

semaphore-objects.html | module-threading.html | thread-objects.html | Python Library Reference | contents.html | genindex.html
---
## 7.5.5 Event Objects
This is one of the simplest mechanisms for communication between
threads: one thread signals an event and one or more other threads
are waiting for it.
An event object manages an internal flag that can be set to true with
the set() method and reset to false with the clear() method. The
wait() method blocks until the flag is true.


3.15.1 Examples

module-imp.html | module-imp.html | module-parser.html | Python Library Reference | contents.html | genindex.html
---
## 3.15.1 Examples
The following function emulates what was the standard import statement
up to Python 1.4 (i.e., no hierarchical module names). (This
implementation wouldn't work in that version, since
find_module() has been extended and
load_module() has been added in 1.4.)
```text

import imp import sys

def __import__(name, globals=None, locals=None, fromlist=None):
# Fast path: see if the module has already been imported.
try:
return sys.modules[name]
except KeyError:
pass

# If any of the following calls raises an exception,
# there's a problem we can't handle -- let the caller handle it.

fp, pathname, description = imp.find_module(name)

try:
return imp.load_module(name, fp, pathname, description)
finally:
# Since we may exit via an exception, close fp explicitly.
if fp:
fp.close()
```


16.4.1 Functions Defined in Module fl

module-fl.html | module-fl.html | form-objects.html | Python Library Reference | contents.html | genindex.html
---
## 16.4.1 Functions Defined in Module fl
Module fl defines the following functions. For more
information about what they do, see the description of the equivalent
C function in the FORMS documentation:


16.4.2 Form Objects

FL_Functions.html | module-fl.html | forms-objects.html | Python Library Reference | contents.html | genindex.html
---
## 16.4.2 Form Objects
Form objects (returned by make_form() above) have the
following methods. Each method corresponds to a C function whose
name is prefixed with "fl_"; and whose first argument is a form
pointer; please refer to the official FORMS documentation for
descriptions.
All the add_*() methods return a Python object representing
the FORMS object. Methods of FORMS objects are described below. Most
kinds of FORMS object also have some methods specific to that kind;
these methods are listed here.
Form objects have the following data attributes; see the FORMS
documentation:


12.5.2 Formatter Implementations

formatter-interface.html | module-formatter.html | writer-interface.html | Python Library Reference | contents.html | genindex.html
---
## 12.5.2 Formatter Implementations
Two implementations of formatter objects are provided by this module.
Most applications may use one of these classes without modification or
subclassing.


12.5.1 The Formatter Interface

module-formatter.html | module-formatter.html | formatter-impls.html | Python Library Reference | contents.html | genindex.html
---
## 12.5.1 The Formatter Interface
Interfaces to create formatters are dependent on the specific
formatter class being instantiated. The interfaces described below
are the required interfaces which all formatters must support once
initialized.
One data element is defined at the module level:
The following attributes are defined for formatter instance objects:


16.4.3 FORMS Objects

form-objects.html | module-fl.html | module-fl-constants.html | Python Library Reference | contents.html | genindex.html
---
## 16.4.3 FORMS Objects
Besides methods specific to particular kinds of FORMS objects, all
FORMS objects also have the following methods:
FORMS objects have these data attributes; see the FORMS documentation:


Front Matter

lib.html | lib.html | contents.html | Python Library Reference | contents.html | genindex.html
---
# Front Matter
BEOPEN.COM TERMS AND CONDITIONS FOR PYTHON 2.0
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization (``Licensee'') accessing and otherwise
using this software in source or binary form and its associated
documentation (``the Software'').
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an ``AS IS''
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the ``BeOpen Python'' logos available
at http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI OPEN SOURCE LICENSE AGREEMENT
Python 1.6 is made available subject to the terms and conditions in
CNRI's License Agreement. This Agreement together with Python 1.6 may
be located on the Internet using the following unique, persistent
identifier (known as a handle): 1895.22/1012. This Agreement may also
be obtained from a proxy server on the Internet using the following
URL: http://hdl.handle.net/1895.22/1012.
CWI PERMISSIONS STATEMENT AND DISCLAIMER
Copyright © 1991 - 1995, Stichting Mathematisch Centrum
Amsterdam, The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
### Abstract:
Python is an extensible, interpreted, object-oriented programming
language. It supports a wide range of applications, from simple text
processing scripts to interactive WWW browsers.
While the Python Reference Manual (../ref/ref.html)
describes the exact syntax and semantics of the language, it does not
describe the standard library that is distributed with the language,
and which greatly enhances its immediate usability. This library
contains built-in modules (written in C) that provide access to system
functionality such as file I/O that would otherwise be inaccessible to
Python programmers, as well as modules written in Python that provide
standardized solutions for many problems that occur in everyday
programming. Some of these modules are explicitly designed to
encourage and enhance the portability of Python programs.
This library reference manual documents Python's standard library, as
well as many optional library modules (which may or may not be
available, depending on whether the underlying platform supports them
and on the configuration choices made at compile time). It also
documents the standard types of the language and its built-in
functions and exceptions, many of which are not or incompletely
documented in the Reference Manual.
This manual assumes basic knowledge about the Python language. For an
informal introduction to Python, see the
Python Tutorial (../tut/tut.html); the
Python Reference Manual (../ref/ref.html) remains the
highest authority on syntactic and semantic questions. Finally, the
manual entitled Extending and Embedding
the Python Interpreter (../ext/ext.html) describes how to add new extensions to Python
and how to embed it in other applications.


11.4.1 FTP Objects

module-ftplib.html | module-ftplib.html | module-gopherlib.html | Python Library Reference | contents.html | genindex.html
---
## 11.4.1 FTP Objects
Several methods are available in two flavors: one for handling text
files and another for binary files. These are named for the command
which is used followed by "lines" for the text version or
"binary" for the binary version.
FTP instances have the following methods:


11.1.4 Functions

node226.html | module-cgi.html | node228.html | Python Library Reference | contents.html | genindex.html
---
## 11.1.4 Functions
These are useful if you want more control, or if you want to employ
some of the algorithms implemented in this module in other
circumstances.


Index

modindex.html | lib.html | about.html | Python Library Reference | contents.html
---
## Index
---
. (#letter-.) |
= (#letter-=) |
_ (#letter-_) |
a (#letter-a) |
b (#letter-b) |
c (#letter-c) |
d (#letter-d) |
e (#letter-e) |
f (#letter-f) |
g (#letter-g) |
h (#letter-h) |
i (#letter-i) |
j (#letter-j) |
k (#letter-k) |
l (#letter-l) |
m (#letter-m) |
n (#letter-n) |
o (#letter-o) |
p (#letter-p) |
q (#letter-q) |
r (#letter-r) |
s (#letter-s) |
t (#letter-t) |
u (#letter-u) |
v (#letter-v) |
w (#letter-w) |
x (#letter-x) |
y (#letter-y) |
z (#letter-z)
---
## . (dot)
---
## =
---
## _ (underscore)
---
## A
---
## B
---
## C
---
## D
---
## E
---
## F
---
## G
---
## H
---
## I
---
## J
---
## K
---
## L
---
## M
---
## N
---
## O
---
## P
---
## Q
---
## R
---
## S
---
## T
---
## U
---
## V
---
## W
---
## X
---
## Y
---
## Z


12.2.1 HTMLParser Objects

module-htmllib.html | module-htmllib.html | module-htmlentitydefs.html | Python Library Reference | contents.html | genindex.html
---
## 12.2.1 HTMLParser Objects
In addition to tag methods, the HTMLParser class provides some
additional methods and instance variables for use within tag methods.


11.3.2 Example

node237.html | module-httplib.html | module-ftplib.html | Python Library Reference | contents.html | genindex.html
---
## 11.3.2 Example
Here is an example session:


11.7.2 IMAP4 Example

imap4-objects.html | module-imaplib.html | module-nntplib.html | Python Library Reference | contents.html | genindex.html
---
## 11.7.2 IMAP4 Example
Here is a minimal example (without error checking) that opens a
mailbox and retrieves and prints all messages:


11.7.1 IMAP4 Objects

module-imaplib.html | module-imaplib.html | imap4-example.html | Python Library Reference | contents.html | genindex.html
---
## 11.7.1 IMAP4 Objects
All IMAP4rev1 commands are represented by methods of the same name,
either upper-case or lower-case.
All arguments to commands are converted to strings, except for
"AUTHENTICATE", and the last argument to "APPEND" which is
passed as an IMAP4 literal. If necessary (the string contains IMAP4
protocol-sensitive characters and isn't enclosed with either
parentheses or double quotes) each string is quoted. However, the
password argument to the "LOGIN" command is always quoted.
Each command returns a tuple: `( type , [ data ,
...])` where type is usually `'OK'` or `'NO'`,
and data is either the text from the command response, or
mandated results from the command.
An IMAP4 instance has the following methods:
The following attributes are defined on instances of IMAP4:


Python Library Reference

../index.html | front.html | Python Library Reference | contents.html | genindex.html
---
# Python Library Reference
Guido van Rossum
Fred L. Drake, Jr., editor
BeOpen PythonLabs
E-mail: python-docs@python.org
September 18, 2000
Release 1.6


11. Internet Protocols and Support

profile-HotProfile.html | lib.html | module-cgi.html | Python Library Reference | contents.html | genindex.html
---
# 11. Internet Protocols and Support
The modules described in this chapter implement Internet protocols and
support for related technology. They are all implemented in Python.
Most of these modules require the presence of the system-dependent
module socket (module-socket.html), which is currently
supported on most popular platforms. Here is an overview:


3.23.1 Interactive Interpreter Objects

module-code.html | module-code.html | console-objects.html | Python Library Reference | contents.html | genindex.html
---
## 3.23.1 Interactive Interpreter Objects


1. Introduction

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


Python Library Reference


7.5.1 Lock Objects

module-threading.html | module-threading.html | rlock-objects.html | Python Library Reference | contents.html | genindex.html
---
## 7.5.1 Lock Objects
A primitive lock is a synchronization primitive that is not owned
by a particular thread when locked. In Python, it is currently
the lowest level synchronization primitive available, implemented
directly by the thread (module-thread.html) extension module.
A primitive lock is in one of two states, ``locked'' or ``unlocked''.
It is created in the unlocked state. It has two basic methods,
acquire() and release(). When the state is
unlocked, acquire() changes the state to locked and returns
immediately. When the state is locked, acquire() blocks
until a call to release() in another thread changes it to
unlocked, then the acquire() call resets it to locked and
returns. The release() method should only be called in the
locked state; it changes the state to unlocked and returns
immediately. When more than one thread is blocked in
acquire() waiting for the state to turn to unlocked, only one
thread proceeds when a release() call resets the state to
unlocked; which one of the waiting threads proceeds is not defined,
and may vary across implementations.
All methods are executed atomically.


12.18.1 Mailbox Objects

module-mailbox.html | module-mailbox.html | module-mhlib.html | Python Library Reference | contents.html | genindex.html
---
## 12.18.1 Mailbox Objects
All implementations of Mailbox objects have one externally visible
method:


4.2.5 Match Objects

re-objects.html | module-re.html | module-regex.html | Python Library Reference | contents.html | genindex.html
---
## 4.2.5 Match Objects
MatchObject instances support the following methods and attributes: