A. Reporting Bugs

supporting-cycle-detection.html | api.html | node80.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
10.9 Supporting Cyclic Garbarge (supporting-cycle-detection.html)
Up:
Python/C API Reference Manual (api.html)
Next:
B. History and License (node80.html)
---
# A. Reporting Bugs
Python is a mature programming language which has established a
reputation for stability. In order to maintain this reputation, the
developers would like to know of any deficiencies you find in Python
or its documentation.
Before submitting a report, you will be required to log into SourceForge;
this will make it possible for the developers to contact you
for additional information if needed. It is not possible to submit a
bug report anonymously.
All bug reports should be submitted via the Python Bug Tracker on
SourceForge (http://sourceforge.net/bugs/?group_id=5470). The
bug tracker offers a Web form which allows pertinent information to be
entered and submitted to the developers.
The first step in filing a report is to determine whether the problem
has already been reported. The advantage in doing so, aside from
saving the developers time, is that you learn what has been done to
fix it; it may be that the problem has already been fixed for the next
release, or additional information is needed (in which case you are
welcome to provide it if you can!). To do this, search the bug
database using the search box near the bottom of the page.
If the problem you're reporting is not already in the bug tracker, go
back to the Python Bug Tracker
(http://sourceforge.net/bugs/?group_id=5470). Select the
``Submit a Bug'' link at the top of the page to open the bug reporting
form.
The submission form has a number of fields. The only fields that are
required are the ``Summary'' and ``Details'' fields. For the summary,
enter a very short description of the problem; less than ten
words is good. In the Details field, describe the problem in detail,
including what you expected to happen and what did happen. Be sure to
include the version of Python you used, whether any extension modules
were involved, and what hardware and software platform you were using
(including version information as appropriate).
The only other field that you may want to set is the ``Category''
field, which allows you to place the bug report into a broad category
(such as ``Documentation'' or ``Library'').
Each bug report will be assigned to a developer who will determine
what needs to be done to correct the problem. You will
receive an update each time action is taken on the bug.
See Also:


10.6 Sequence Object Structures

number-structs.html | newTypes.html | buffer-structs.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
10.5 Number Object Structures (number-structs.html)
Up:
10. Object Implementation Support (newTypes.html)
Next:
10.7 Buffer Object Structures (buffer-structs.html)
---
# 10.6 Sequence Object Structures


6.3 Sequence Protocol

number.html | abstract.html | mapping.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
6.2 Number Protocol (number.html)
Up:
6. Abstract Objects Layer (abstract.html)
Next:
6.4 Mapping Protocol (mapping.html)
---
# 6.3 Sequence Protocol


7.3 Sequence Objects

node39.html | concrete.html | stringObjects.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
7.2.4.2 Complex Numbers as (node39.html)
Up:
7. Concrete Objects Layer (concrete.html)
Next:
7.3.1 String Objects (stringObjects.html)
---
# 7.3 Sequence Objects
Generic operations on sequence objects were discussed in the previous
chapter; this section deals with the specific kinds of sequence
objects that are intrinsic to the Python language.


7.5.7 Slice Objects

descriptor-objects.html | otherObjects.html | weakref-objects.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
7.5.6 Descriptor Objects (descriptor-objects.html)
Up:
7.5 Other Objects (otherObjects.html)
Next:
7.5.8 Weak Reference Objects (weakref-objects.html)
---
## 7.5.7 Slice Objects


4.1 Standard Exceptions

exceptionHandling.html | exceptionHandling.html | node15.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
4. Exception Handling (exceptionHandling.html)
Up:
4. Exception Handling (exceptionHandling.html)
Next:
4.2 Deprecation of String (node15.html)
---
# 4.1 Standard Exceptions
All standard Python exceptions are available as global variables whose
names are "PyExc_" followed by the Python exception name. These
have the type PyObject*; they are all class objects. For
completeness, here are all the variables:
Notes:
(1): This is a base class for other standard exceptions.
(2): This is the same as weakref.ReferenceError.
(3): Only defined on Windows; protect code that uses this by testing that
the preprocessor macro `MS_WINDOWS` is defined.


7.3.1 String Objects

sequenceObjects.html | sequenceObjects.html | unicodeObjects.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
7.3 Sequence Objects (sequenceObjects.html)
Up:
7.3 Sequence Objects (sequenceObjects.html)
Next:
7.3.2 Unicode Objects (unicodeObjects.html)
---
## 7.3.1 String Objects
These functions raise TypeError when expecting a string
parameter and are called with a non-string parameter.


supporting-iteration.html | newTypes.html | reporting-bugs.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
10.8 Supporting the Iterator (supporting-iteration.html)
Up:
10. Object Implementation Support (newTypes.html)
Next:
A. Reporting Bugs (reporting-bugs.html)
---
# 10.9 Supporting Cyclic Garbarge Collection
Python's support for detecting and collecting garbage which involves
circular references requires support from object types which are
``containers'' for other objects which may also be containers. Types
which do not store references to other objects, or which only store
references to atomic types (such as numbers or strings), do not need
to provide any explicit support for garbage collection.
An example showing the use of these interfaces can be found in
``Supporting the Cycle
Collector (../ext/example-cycle-support.html)'' in
Extending and Embedding the Python
Interpreter (../ext/ext.html).
To create a container type, the tp_flags field of the type
object must include the Py_TPFLAGS_HAVE_GC and provide an
implementation of the tp_traverse handler. If instances of the
type are mutable, a tp_clear implementation must also be
provided.
Constructors for container types must conform to two rules:
1. The memory for the object must be allocated using
PyObject_GC_New() or PyObject_GC_VarNew().
2. Once all the fields which may contain references to other
containers are initialized, it must call
PyObject_GC_Track().
Similarly, the deallocator for the object must conform to a similar
pair of rules:
1. Before fields which refer to other containers are invalidated,
PyObject_GC_UnTrack() must be called.
2. The object's memory must be deallocated using
PyObject_GC_Del().
The tp_traverse handler accepts a function parameter of this
type:
The tp_traverse handler must have the following type:
The tp_clear handler must be of the inquiry type, or
NULL if the object is immutable.


10.8 Supporting the Iterator Protocol

buffer-structs.html | newTypes.html | supporting-cycle-detection.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
10.7 Buffer Object Structures (buffer-structs.html)
Up:
10. Object Implementation Support (newTypes.html)
Next:
10.9 Supporting Cyclic Garbarge (supporting-cycle-detection.html)
---
# 10.8 Supporting the Iterator Protocol


initialization.html | initialization.html | profiling.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
8. Initialization, Finalization, and (initialization.html)
Up:
8. Initialization, Finalization, and (initialization.html)
Next:
8.2 Profiling and Tracing (profiling.html)
---
# 8.1 Thread State and the Global Interpreter Lock
The Python interpreter is not fully thread safe. In order to support
multi-threaded Python programs, there's a global lock that must be
held by the current thread before it can safely access Python objects.
Without the lock, even the simplest operations could cause problems in
a multi-threaded program: for example, when two threads simultaneously
increment the reference count of the same object, the reference count
could end up being incremented only once instead of twice.
Therefore, the rule exists that only the thread that has acquired the
global interpreter lock may operate on Python objects or call Python/C
API functions. In order to support multi-threaded Python programs,
the interpreter regularly releases and reacquires the lock -- by
default, every 100 bytecode instructions (this can be changed with
sys.setcheckinterval()). The lock is also released and
reacquired around potentially blocking I/O operations like reading or
writing a file, so that other threads can run while the thread that
requests the I/O is waiting for the I/O operation to complete.
The Python interpreter needs to keep some bookkeeping information
separate per thread -- for this it uses a data structure called
PyThreadState. This is new in Python
1.5; in earlier versions, such state was stored in global variables,
and switching threads could cause problems. In particular, exception
handling is now thread safe, when the application uses
sys.exc_info() to access the exception last raised in the
current thread.
There's one global variable left, however: the pointer to the current
PyThreadStatestructure. While most
thread packages have a way to store ``per-thread global data,''
Python's internal platform independent thread abstraction doesn't
support this yet. Therefore, the current thread state must be
manipulated explicitly.
This is easy enough in most cases. Most code manipulating the global
interpreter lock has the following simple structure:
```text

Save the thread state in a local variable.
Release the interpreter lock.
...Do some blocking I/O operation...
Reacquire the interpreter lock.
Restore the thread state from the local variable.
```
This is so common that a pair of macros exists to simplify it:
```text

Py_BEGIN_ALLOW_THREADS
...Do some blocking I/O operation...
Py_END_ALLOW_THREADS
```
The
Py_BEGIN_ALLOW_THREADSmacro opens a new block and declares a hidden local variable; the
Py_END_ALLOW_THREADSmacro closes the block. Another advantage of using these two macros
is that when Python is compiled without thread support, they are
defined empty, thus saving the thread state and lock manipulations.
When thread support is enabled, the block above expands to the
following code:
```text

PyThreadState *_save;

_save = PyEval_SaveThread();
...Do some blocking I/O operation...
PyEval_RestoreThread(_save);
```
Using even lower level primitives, we can get roughly the same effect
as follows:
```text

PyThreadState *_save;

_save = PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
...Do some blocking I/O operation...
PyEval_AcquireLock();
PyThreadState_Swap(_save);
```
There are some subtle differences; in particular,
PyEval_RestoreThread()saves
and restores the value of the global variable
errno, since the lock manipulation does not
guarantee that errno is left alone. Also, when thread support
is disabled,
PyEval_SaveThread()and
PyEval_RestoreThread() don't manipulate the lock; in this
case, PyEval_ReleaseLock()and
PyEval_AcquireLock()are not
available. This is done so that dynamically loaded extensions
compiled with thread support enabled can be loaded by an interpreter
that was compiled with disabled thread support.
The global interpreter lock is used to protect the pointer to the
current thread state. When releasing the lock and saving the thread
state, the current thread state pointer must be retrieved before the
lock is released (since another thread could immediately acquire the
lock and store its own thread state in the global variable).
Conversely, when acquiring the lock and restoring the thread state,
the lock must be acquired before storing the thread state pointer.
Why am I going on with so much detail about this? Because when
threads are created from C, they don't have the global interpreter
lock, nor is there a thread state data structure for them. Such
threads must bootstrap themselves into existence, by first creating a
thread state data structure, then acquiring the lock, and finally
storing their thread state pointer, before they can start using the
Python/C API. When they are done, they should reset the thread state
pointer, release the lock, and finally free their thread state data
structure.
When creating a thread data structure, you need to provide an
interpreter state data structure. The interpreter state data
structure hold global data that is shared by all threads in an
interpreter, for example the module administration
(`sys.modules`). Depending on your needs, you can either create
a new interpreter state data structure, or share the interpreter state
data structure used by the Python main thread (to access the latter,
you must obtain the thread state and access its interp member;
this must be done by a thread that is created by Python or by the main
thread after Python is initialized).
Assuming you have access to an interpreter object, the typical idiom
for calling into Python from a C thread is
```text

PyThreadState *tstate;
PyObject *result;

/* interp is your reference to an interpreter object. */
tstate = PyThreadState_New(interp);
PyEval_AcquireThread(tstate);

/* Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result */

/* Release the thread. No Python API allowed beyond this point. */
PyEval_ReleaseThread(tstate);

/* You can either delete the thread state, or save it
until you need it the next time. */
PyThreadState_Delete(tstate);
```
The following macros are normally used without a trailing semicolon;
look for example usage in the Python source distribution.
All of the following functions are only available when thread support
is enabled at compile time, and must be called only when the
interpreter lock has been created.


7.3.4 Tuple Objects

bufferObjects.html | sequenceObjects.html | listObjects.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
7.3.3 Buffer Objects (bufferObjects.html)
Up:
7.3 Sequence Objects (sequenceObjects.html)
Next:
7.3.5 List Objects (listObjects.html)
---
## 7.3.4 Tuple Objects


10.3 Type Objects

common-structs.html | newTypes.html | mapping-structs.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
10.2 Common Object Structures (common-structs.html)
Up:
10. Object Implementation Support (newTypes.html)
Next:
10.4 Mapping Object Structures (mapping-structs.html)
---
# 10.3 Type Objects
Perhaps one of the most important structures of the Python object
system is the structure that defines a new type: the
PyTypeObject structure. Type objects can be handled using any
of the PyObject_*() or PyType_*() functions,
but do not offer much that's interesting to most Python applications.
These objects are fundamental to how objects behave, so they are very
important to the interpreter itself and to any extension module that
implements new types.
Type objects are fairly large compared to most of the standard types.
The reason for the size is that each type object stores a large number
of values, mostly C function pointers, each of which implements a
small part of the type's functionality. The fields of the type object
are examined in detail in this section. The fields will be described
in the order in which they occur in the structure.
Typedefs:
unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
destructor, freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc,
setattrofunc, cmpfunc, reprfunc, hashfunc
The structure definition for PyTypeObject can be found in
Include/object.h. For convenience of reference, this repeats
the definition found there:
```text
typedef struct _typeobject {
PyObject_VAR_HEAD
char *tp_name; /* For printing, in format "<module>.<name>" */
int tp_basicsize, tp_itemsize; /* For allocation */

/* Methods to implement standard operations */

destructor tp_dealloc;
printfunc tp_print;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
cmpfunc tp_compare;
reprfunc tp_repr;

/* Method suites for standard classes */

PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;

/* More standard operations (here for binary compatibility) */

hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;

/* Functions to access object as input/output buffer */
PyBufferProcs *tp_as_buffer;

/* Flags to define presence of optional/expanded features */
long tp_flags;

char *tp_doc; /* Documentation string */

/* Assigned meaning in release 2.0 */
/* call function for all accessible objects */
traverseproc tp_traverse;

/* delete references to contained objects */
inquiry tp_clear;

/* Assigned meaning in release 2.1 */
/* rich comparisons */
richcmpfunc tp_richcompare;

/* weak reference enabler */
long tp_weaklistoffset;

/* Added in release 2.2 */
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;

/* Attribute descriptor and subclassing stuff */
struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
struct _typeobject *tp_base;
PyObject *tp_dict;
descrgetfunc tp_descr_get;
descrsetfunc tp_descr_set;
long tp_dictoffset;
initproc tp_init;
allocfunc tp_alloc;
newfunc tp_new;
freefunc tp_free; /* Low-level free-memory routine */
inquiry tp_is_gc; /* For PyObject_IS_GC */
PyObject *tp_bases;
PyObject *tp_mro; /* method resolution order */
PyObject *tp_cache;
PyObject *tp_subclasses;
PyObject *tp_weaklist;

} PyTypeObject;
```
Download as text (original file name: typestruct.h). (typestruct.txt)
The type object structure extends the PyVarObject structure.
The ob_size field is used for dynamic types (created
by type_new(), usually called from a class statement).
Note that PyType_Type (the metatype) initializes
tp_itemsize, which means that its instances (i.e. type
objects) must have the ob_size field.
PyNumberMethods *tp_as_number;
XXX
PySequenceMethods *tp_as_sequence;
XXX
PyMappingMethods *tp_as_mapping;
XXX
The following three fields only exist if the
Py_TPFLAGS_HAVE_RICHCOMPARE flag bit is set.
The next field only exists if the Py_TPFLAGS_HAVE_WEAKREFS
flag bit is set.
The next two fields only exist if the
Py_TPFLAGS_HAVE_CLASS flag bit is set.
The next fields, up to and including tp_weaklist, only exist
if the Py_TPFLAGS_HAVE_CLASS flag bit is set.
The remaining fields are only defined if the feature test macro
COUNT_ALLOCS is defined, and are for internal use only.
They are documented here for completeness. None of these fields are
inherited by subtypes.


7.1.1 Type Objects

fundamental.html | fundamental.html | noneObject.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
7.1 Fundamental Objects (fundamental.html)
Up:
7.1 Fundamental Objects (fundamental.html)
Next:
7.1.2 The None Object (noneObject.html)
---
## 7.1.1 Type Objects


1.2.2 Types

refcountDetails.html | objects.html | exceptions.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
1.2.1.1 Reference Count Details (refcountDetails.html)
Up:
1.2 Objects, Types and (objects.html)
Next:
1.3 Exceptions (exceptions.html)
---
## 1.2.2 Types
There are few other data types that play a significant role in
the Python/C API; most are simple C types such as int,
long, double and char*. A few structure types
are used to describe static tables used to list the functions exported
by a module or the data attributes of a new object type, and another
is used to describe the value of a complex number. These will
be discussed together with the functions that use them.


7.3.2.2 Methods and Slot Functions

builtinCodecs.html | unicodeObjects.html | bufferObjects.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
7.3.2.1 Built-in Codecs (builtinCodecs.html)
Up:
7.3.2 Unicode Objects (unicodeObjects.html)
Next:
7.3.3 Buffer Objects (bufferObjects.html)
---
### 7.3.2.2 Methods and Slot Functions
The following APIs are capable of handling Unicode objects and strings
on input (we refer to them as strings in the descriptions) and return
Unicode objects or integers as apporpriate.
They all return NULL or `-1` if an exception occurs.


7.3.2 Unicode Objects

stringObjects.html | sequenceObjects.html | builtinCodecs.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
7.3.1 String Objects (stringObjects.html)
Up:
7.3 Sequence Objects (sequenceObjects.html)
Next:
7.3.2.1 Built-in Codecs (builtinCodecs.html)
---
## 7.3.2 Unicode Objects
These are the basic Unicode object types used for the Unicode
implementation in Python:
The following APIs are really C macros and can be used to do fast
checks and to access internal read-only data of Unicode objects:
Unicode provides many different character properties. The most often
needed ones are available through these macros which are mapped to C
functions depending on the Python configuration.
These APIs can be used for fast direct character conversions:
To create Unicode objects and access their basic sequence properties,
use these APIs:
If the platform supports wchar_t and provides a header file
wchar.h, Python can interface directly to this type using the
following functions. Support is optimized if Python's own
Py_UNICODE type is identical to the system's wchar_t.


5. Utilities

node15.html | api.html | os.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
4.2 Deprecation of String (node15.html)
Up:
Python/C API Reference Manual (api.html)
Next:
5.1 Operating System Utilities (os.html)
---
# 5. Utilities
The functions in this chapter perform various utility tasks, ranging
from helping C code be more portable across platforms, using Python
modules from C, and parsing function arguments and constructing Python
values from C values.


2. The Very High Level Layer

embedding.html | api.html | countingRefs.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
1.4 Embedding Python (embedding.html)
Up:
Python/C API Reference Manual (api.html)
Next:
3. Reference Counting (countingRefs.html)
---
# 2. The Very High Level Layer
The functions in this chapter will let you execute Python source code
given in a file or a buffer, but they will not let you interact in a
more detailed way with the interpreter.
Several of these functions accept a start symbol from the grammar as a
parameter. The available start symbols are Py_eval_input,
Py_file_input, and Py_single_input. These are
described following the functions which accept them as parameters.
Note also that several of these functions take FILE*
parameters. On particular issue which needs to be handled carefully
is that the FILE structure for different C libraries can be
different and incompatible. Under Windows (at least), it is possible
for dynamically linked extensions to actually use different libraries,
so care should be taken that FILE* parameters are only passed
to these functions if it is certain that they were created by the same
library that the Python runtime is using.


7.5.8 Weak Reference Objects

slice-objects.html | otherObjects.html | cObjects.html | Python/C API Reference Manual | contents.html | genindex.html
Previous:
7.5.7 Slice Objects (slice-objects.html)
Up:
7.5 Other Objects (otherObjects.html)
Next:
7.5.9 CObjects (cObjects.html)
---
## 7.5.8 Weak Reference Objects
Python supports weak references as first-class objects. There
are two specific object types which directly implement weak
references. The first is a simple reference object, and the second
acts as a proxy for the original object as much as it can.


About this document ...

module-distutils.sysconfig.html | dist.html | Distributing Python Modules
Previous:
10 distutils.sysconfig (module-distutils.sysconfig.html)
Up:
Distributing Python Modules (dist.html)
---
# About this document ...
Distributing 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, either in the content or the presentation, 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.
---
module-distutils.sysconfig.html | dist.html | Distributing Python Modules
Previous:
10 distutils.sysconfig (module-distutils.sysconfig.html)
Up:
Distributing Python Modules (dist.html)
---


Distributing Python Modules

../index.html | intro.html | Distributing Python Modules
Up:
Python Documentation Index (../index.html)
Next:
1 Introduction (intro.html)
---
# Distributing Python Modules
Greg Ward
Email: distutils-sig@python.org
### Abstract:
This document describes the Python Distribution Utilities
(``Distutils'') from the module developer's point of view, describing
how to use the Distutils to make Python modules and extensions easily
available to a wider audience with very little overhead for
build/release/install mechanics.


Distributing Python Modules


1 Introduction

dist.html | dist.html | simple-example.html | Distributing Python Modules
Previous:
Distributing Python Modules (dist.html)
Up:
Distributing Python Modules (dist.html)
Next:
2 Concepts & Terminology (simple-example.html)
---
# 1 Introduction
This document covers using the Distutils to distribute your Python
modules, concentrating on the role of developer/distributor: if
you're looking for information on installing Python modules, you
should refer to the Installing Python
Modules (../inst/inst.html) manual.


sdist-cmd.html | dist.html | about.html | Distributing Python Modules
Previous:
9 Reference (sdist-cmd.html)
Up:
Distributing Python Modules (dist.html)
Next:
About this document ... (about.html)
---
# 10 distutils.sysconfig --
System configuration information
The distutils.sysconfig module provides access to Python's
low-level configuration information. The specific configuration
variables available depend heavily on the platform and configuration.
The specific variables depend on the build process for the specific
version of Python being run; the variables are those found in the
Makefile and configuration header that are installed with
Python on Unix systems. The configuration header is called
pyconfig.h for Python versions starting with 2.2, and
config.h for earlier versions of Python.
Some additional functions are provided which perform some useful
manipulations for other parts of the distutils package.
The following function is only intended for use within the
distutils package.
This function is even more special-purpose, and should only be used
from Python's own build procedures.


7 Registering with the Package Index

postinstallation-script.html | dist.html | single-ext.html | Distributing Python Modules
Previous:
6 Creating Built Distributions (postinstallation-script.html)
Up:
Distributing Python Modules (dist.html)
Next:
8 Examples (single-ext.html)
---
# 7 Registering with the Package Index
The Python Package Index (PyPI) holds meta-data describing distributions
packaged with distutils. The distutils command `register` is
used to submit your distribution's meta-data to the index. It is invoked
as follows:
```text

python setup.py register
```
Distutils will respond with the following prompt:
```text

running register
We need to know who you are, so please choose either:
1. use your existing login,
2. register as a new user,
3. have the server generate a new password for you (and email it to you), or
4. quit
Your selection [default 1]:
```
Note: if your username and password are saved locally, you will
not see this menu.
If you have not registered with PyPI, then you will need to do so now. You
should choose option 2, and enter your details as required. Soon after
submitting your details, you will receive an email which will be used to
confirm your registration.
Once you are registered, you may choose option 1 from the menu. You will
be prompted for your PyPI username and password, and `register`
will then submit your meta-data to the index.
You may submit any number of versions of your distribution to the index. If
you alter the meta-data for a particular version, you may submit it again
and the index will be updated.
PyPI holds a record for each (name, version) combination submitted. The
first user to submit information for a given name is designated the Owner
of that name. They may submit changes through the `register`
command or through the web interface. They may also designate other users
as Owners or Maintainers. Maintainers may edit the package information, but
not designate other Owners or Maintainers.
By default PyPI will list all versions of a given package. To hide certain
versions, the Hidden property should be set to yes. This must be edited
through the web interface.


6 Creating Built Distributions

source-dist.html | dist.html | package-index.html | Distributing Python Modules
Previous:
5 Creating a Source (source-dist.html)
Up:
Distributing Python Modules (dist.html)
Next:
7 Registering with the (package-index.html)
---
- 6.1 Creating dumb built distributions (postinstallation-script.html#SECTION000610000000000000000)
  6.2 Creating RPM packages (postinstallation-script.html#SECTION000620000000000000000)
  6.3 Creating Windows Installers (postinstallation-script.html#SECTION000630000000000000000)
  - 6.3.1 The Postinstallation script (postinstallation-script.html#SECTION000631000000000000000)
---
# 6 Creating Built Distributions
A ``built distribution'' is what you're probably used to thinking of
either as a ``binary package'' or an ``installer'' (depending on your
background). It's not necessarily binary, though, because it might
contain only Python source code and/or byte-code; and we don't call it a
package, because that word is already spoken for in Python. (And
``installer'' is a term specific to the Windows world. ** do Mac
people use it? **)
A built distribution is how you make life as easy as possible for
installers of your module distribution: for users of RPM-based Linux
systems, it's a binary RPM; for Windows users, it's an executable
installer; for Debian-based Linux users, it's a Debian package; and so
forth. Obviously, no one person will be able to create built
distributions for every platform under the sun, so the Distutils are
designed to enable module developers to concentrate on their
specialty--writing code and creating source distributions--while an
intermediary species called packagers springs up to turn source
distributions into built distributions for as many platforms as there
are packagers.
Of course, the module developer could be his own packager; or the
packager could be a volunteer ``out there'' somewhere who has access to
a platform which the original developer does not; or it could be
software periodically grabbing new source distributions and turning them
into built distributions for as many platforms as the software has
access to. Regardless of who they are, a packager uses the
setup script and the `bdist` command family to generate built
distributions.
As a simple example, if I run the following command in the Distutils
source tree:
```text

python setup.py bdist
```
then the Distutils builds my module distribution (the Distutils itself
in this case), does a ``fake'' installation (also in the build
directory), and creates the default type of built distribution for my
platform. The default format for built distributions is a ``dumb'' tar
file on Unix, and a simple executable installer on Windows. (That tar
file is considered ``dumb'' because it has to be unpacked in a specific
location to work.)
Thus, the above command on a Unix system creates
Distutils-1.0.plat.tar.gz; unpacking this tarball
from the right place installs the Distutils just as though you had
downloaded the source distribution and run `python setup.py
install`. (The ``right place'' is either the root of the filesystem or
Python's prefix directory, depending on the options given to
the `bdist_dumb` command; the default is to make dumb
distributions relative to prefix.)
Obviously, for pure Python distributions, this isn't any simpler than
just running `python setup.py install`--but for non-pure
distributions, which include extensions that would need to be
compiled, it can mean the difference between someone being able to use
your extensions or not. And creating ``smart'' built distributions,
such as an RPM package or an executable installer for Windows, is far
more convenient for users even if your distribution doesn't include
any extensions.
The `bdist` command has a --formats option,
similar to the `sdist` command, which you can use to select the
types of built distribution to generate: for example,
```text

python setup.py bdist --format=zip
```
would, when run on a Unix system, create
Distutils-1.0.plat.zip--again, this archive would be
unpacked from the root directory to install the Distutils.
The available formats for built distributions are:
Notes:
(1): default on Unix
(2): default on Windows ** to-do! **
(3): requires external utilities: tar and possibly one
of gzip, bzip2, or compress
(4): requires either external zip utility or
zipfile module (part of the standard Python library since
Python 1.6)
(5): requires external rpm utility, version 3.0.4 or
better (use `rpm -version` to find out which version you have)
You don't have to use the `bdist` command with the
--formats option; you can also use the command that
directly implements the format you're interested in. Some of these
`bdist` ``sub-commands'' actually generate several similar
formats; for instance, the `bdist_dumb` command generates all
the ``dumb'' archive formats (`tar`, `ztar`, `gztar`, and
`zip`), and `bdist_rpm` generates both binary and source
RPMs. The `bdist` sub-commands, and the formats generated by
each, are:
The following sections give details on the individual `bdist_*`
commands.
## 6.1 Creating dumb built distributions
** Need to document absolute vs. prefix-relative packages here, but
first I have to implement it! **
## 6.2 Creating RPM packages
The RPM format is used by many popular Linux distributions, including
Red Hat, SuSE, and Mandrake. If one of these (or any of the other
RPM-based Linux distributions) is your usual environment, creating RPM
packages for other users of that same distribution is trivial.
Depending on the complexity of your module distribution and differences
between Linux distributions, you may also be able to create RPMs that
work on different RPM-based distributions.
The usual way to create an RPM of your module distribution is to run the
`bdist_rpm` command:
```text

python setup.py bdist_rpm
```
or the `bdist` command with the --format option:
```text

python setup.py bdist --formats=rpm
```
The former allows you to specify RPM-specific options; the latter allows
you to easily specify multiple formats in one run. If you need to do
both, you can explicitly specify multiple `bdist_*` commands
and their options:
```text

python setup.py bdist_rpm --packager="John Doe <jdoe@python.net>" \
bdist_wininst --target_version="2.0"
```
Creating RPM packages is driven by a .spec file, much as using
the Distutils is driven by the setup script. To make your life easier,
the `bdist_rpm` command normally creates a .spec file
based on the information you supply in the setup script, on the command
line, and in any Distutils configuration files. Various options and
sections in the .spec file are derived from options in the setup
script as follows:
Additionally, there many options in .spec files that don't have
corresponding options in the setup script. Most of these are handled
through options to the `bdist_rpm` command as follows:
Obviously, supplying even a few of these options on the command-line
would be tedious and error-prone, so it's usually best to put them in
the setup configuration file, setup.cfg--see
section 4 (setup-config.html#setup-config). If you distribute or package many Python
module distributions, you might want to put options that apply to all of
them in your personal Distutils configuration file
(~/.pydistutils.cfg).
There are three steps to building a binary RPM package, all of which are
handled automatically by the Distutils:
1. create a .spec file, which describes the package (analogous
to the Distutils setup script; in fact, much of the information in the
setup script winds up in the .spec file)
2. create the source RPM
3. create the ``binary'' RPM (which may or may not contain binary
code, depending on whether your module distribution contains Python
extensions)
Normally, RPM bundles the last two steps together; when you use the
Distutils, all three steps are typically bundled together.
If you wish, you can separate these three steps. You can use the
--spec-only option to make `bdist_rpm` just
create the .spec file and exit; in this case, the .spec
file will be written to the ``distribution directory''--normally
dist/, but customizable with the --dist-dir
option. (Normally, the .spec file winds up deep in the ``build
tree,'' in a temporary directory created by `bdist_rpm`.)
** this isn't implemented yet--is it needed?! **
You can also specify a custom .spec file with the
--spec-file option; used in conjunction with
--spec-only, this gives you an opportunity to customize
the .spec file manually:
```text

> python setup.py bdist_rpm --spec-only
# ...edit dist/FooBar-1.0.spec
> python setup.py bdist_rpm --spec-file=dist/FooBar-1.0.spec
```
(Although a better way to do this is probably to override the standard
`bdist_rpm` command with one that writes whatever else you want
to the .spec file.)
## 6.3 Creating Windows Installers
Executable installers are the natural format for binary distributions
on Windows. They display a nice graphical user interface, display
some information about the module distribution to be installed taken
from the metadata in the setup script, let the user select a few
options, and start or cancel the installation.
Since the metadata is taken from the setup script, creating Windows
installers is usually as easy as running:
```text

python setup.py bdist_wininst
```
or the `bdist` command with the --formats option:
```text

python setup.py bdist --formats=wininst
```
If you have a pure module distribution (only containing pure Python
modules and packages), the resulting installer will be version
independent and have a name like foo-1.0.win32.exe. These
installers can even be created on Unix or MacOS platforms.
If you have a non-pure distribution, the extensions can only be
created on a Windows platform, and will be Python version dependent.
The installer filename will reflect this and now has the form
foo-1.0.win32-py2.0.exe. You have to create a separate installer
for every Python version you want to support.
The installer will try to compile pure modules into bytecode after
installation on the target system in normal and optimizing mode. If
you don't want this to happen for some reason, you can run the
`bdist_wininst` command with the
--no-target-compile and/or the
--no-target-optimize option.
By default the installer will display the cool ``Python Powered'' logo
when it is run, but you can also supply your own bitmap which must be
a Windows .bmp file with the --bitmap option.
The installer will also display a large title on the desktop
background window when it is run, which is constructed from the name
of your distribution and the version number. This can be changed to
another text by using the --title option.
The installer file will be written to the ``distribution directory''
-- normally dist/, but customizable with the
--dist-dir option.
### 6.3.1 The Postinstallation script
Starting with Python 2.3, a postinstallation script can be specified
which the --install-script option. The basename of the
script must be specified, and the script filename must also be listed
in the scripts argument to the setup function.
This script will be run at installation time on the target system
after all the files have been copied, with argv[1] set to '-install',
and again at uninstallation time before the files are removed with argv[1]
set to '-remove'.
The installation script runs embedded in the windows installer, every
output (sys.stdout, sys.stderr) is redirected into a buffer and will
be displayed in the GUI after the script has finished.
Some functions especially useful in this context are available in the
installation script.
```text

dir_created(pathname)
file_created(pathname)
```
These functions should be called when a directory or file is created
by the postinstall script at installation time. It will register the
pathname with the uninstaller, so that it will be removed when the
distribution is uninstalled. To be safe, directories are only removed
if they are empty.
```text

get_special_folder_path(csidl_string)
```
This function can be used to retrieve special folder locations on
Windows like the Start Menu or the Desktop. It returns the full path
to the folder. 'csidl_string' must be on of the following strings:
```text

"CSIDL_APPDATA"

"CSIDL_COMMON_STARTMENU"
"CSIDL_STARTMENU"

"CSIDL_COMMON_DESKTOPDIRECTORY"
"CSIDL_DESKTOPDIRECTORY"

"CSIDL_COMMON_STARTUP"
"CSIDL_STARTUP"

"CSIDL_COMMON_PROGRAMS"
"CSIDL_PROGRAMS"

"CSIDL_FONTS"
```
If the folder cannot be retrieved, OSError is raised.
Which folders are available depends on the exact Windows version, and probably
also the configuration. For details refer to Microsoft's documentation of the
`SHGetSpecialFolderPath` function.
```text

create_shortcut(target, description, filename[, arguments[,
workdir[, iconpath[, iconindex]]]])
```
This function creates a shortcut.
target is the path to the program to be started by the shortcut.
description is the description of the sortcut.
filename is the title of the shortcut that the user will see.
arguments specifies the command line arguments, if any.
workdir is the working directory for the program.
iconpath is the file containing the icon for the shortcut,
and iconindex is the index of the icon in the file
iconpath. Again, for details consult the Microsoft
documentation for the `IShellLink` interface.


9 Reference

single-ext.html | dist.html | module-distutils.sysconfig.html | Distributing Python Modules
Previous:
8 Examples (single-ext.html)
Up:
Distributing Python Modules (dist.html)
Next:
10 distutils.sysconfig (module-distutils.sysconfig.html)
---
- 9.1 Installing modules: the `install` command family (sdist-cmd.html#SECTION000910000000000000000)
  - 9.1.1 `install_data` (sdist-cmd.html#SECTION000911000000000000000)
  9.1.2 `install_scripts` (sdist-cmd.html#SECTION000912000000000000000)
  9.2 Creating a source distribution: the
  `sdist` command (sdist-cmd.html#SECTION000920000000000000000)
---
# 9 Reference
## 9.1 Installing modules: the `install` command family
The install command ensures that the build commands have been run and then
runs the subcommands `install_lib`,
`install_data` and
`install_scripts`.
### 9.1.1 `install_data`
This command installs all data files provided with the distribution.
### 9.1.2 `install_scripts`
This command installs all (Python) scripts in the distribution.
## 9.2 Creating a source distribution: the
`sdist` command
** fragment moved down from above: needs context! **
The manifest template commands are:
The patterns here are Unix-style ``glob'' patterns: `*` matches any
sequence of regular filename characters, `?` matches any single
regular filename character, and `[ range ]` matches any of the
characters in range (e.g., `a-z`, `a-zA-Z`,
`a-f0-9_.`). The definition of ``regular filename character'' is
platform-specific: on Unix it is anything except slash; on Windows
anything except backslash or colon; on MacOS anything except colon.
** Windows and MacOS support not there yet **


4 Writing the Setup Configuration File

setup-script.html | dist.html | source-dist.html | Distributing Python Modules
Previous:
3 Writing the Setup (setup-script.html)
Up:
Distributing Python Modules (dist.html)
Next:
5 Creating a Source (source-dist.html)
---
# 4 Writing the Setup Configuration File
Often, it's not possible to write down everything needed to build a
distribution a priori: you may need to get some information from
the user, or from the user's system, in order to proceed. As long as
that information is fairly simple--a list of directories to search for
C header files or libraries, for example--then providing a
configuration file, setup.cfg, for users to edit is a cheap and
easy way to solicit it. Configuration files also let you provide
default values for any command option, which the installer can then
override either on the command-line or by editing the config file.
The setup configuration file is a useful middle-ground between the setup
script--which, ideally, would be opaque to installers1 (#foot345)--and the command-line to the setup
script, which is outside of your control and entirely up to the
installer. In fact, setup.cfg (and any other Distutils
configuration files present on the target system) are processed after
the contents of the setup script, but before the command-line. This has
several useful consequences:
- installers can override some of what you put in setup.py by
editing setup.cfg
- you can provide non-standard defaults for options that are not
easily set in setup.py
- installers can override anything in setup.cfg using the
command-line options to setup.py
The basic syntax of the configuration file is simple:
```text

[command]
option=value
...
```
where command is one of the Distutils commands (e.g.
`build_py`, `install`), and option is one of
the options that command supports. Any number of options can be
supplied for each command, and any number of command sections can be
included in the file. Blank lines are ignored, as are comments, which
run from a "#" character until the end of the line. Long
option values can be split across multiple lines simply by indenting
the continuation lines.
You can find out the list of options supported by a particular command
with the universal --help option, e.g.
```text

> python setup.py --help build_ext
[...]
Options for 'build_ext' command:
--build-lib (-b) directory for compiled extension modules
--build-temp (-t) directory for temporary files (build by-products)
--inplace (-i) ignore build-lib and put compiled extensions into the
source directory alongside your pure Python modules
--include-dirs (-I) list of directories to search for header files
--define (-D) C preprocessor macros to define
--undef (-U) C preprocessor macros to undefine
[...]
```
Note that an option spelled --foo-bar on the command-line
is spelled foo_bar in configuration files.
For example, say you want your extensions to be built
``in-place''--that is, you have an extension pkg.ext, and you
want the compiled extension file (ext.so on Unix, say) to be put
in the same source directory as your pure Python modules
pkg.mod1 and pkg.mod2. You can always use the
--inplace option on the command-line to ensure this:
```text

python setup.py build_ext --inplace
```
But this requires that you always specify the `build_ext`
command explicitly, and remember to provide --inplace.
An easier way is to ``set and forget'' this option, by encoding it in
setup.cfg, the configuration file for this distribution:
```text

[build_ext]
inplace=1
```
This will affect all builds of this module distribution, whether or not
you explcitly specify `build_ext`. If you include
setup.cfg in your source distribution, it will also affect
end-user builds--which is probably a bad idea for this option, since
always building extensions in-place would break installation of the
module distribution. In certain peculiar cases, though, modules are
built right in their installation directory, so this is conceivably a
useful ability. (Distributing extensions that expect to be built in
their installation directory is almost always a bad idea, though.)
Another example: certain commands take a lot of options that don't
change from run to run; for example, `bdist_rpm` needs to know
everything required to generate a ``spec'' file for creating an RPM
distribution. Some of this information comes from the setup script, and
some is automatically generated by the Distutils (such as the list of
files installed). But some of it has to be supplied as options to
`bdist_rpm`, which would be very tedious to do on the
command-line for every run. Hence, here is a snippet from the
Distutils' own setup.cfg:
```text

[bdist_rpm]
release = 1
packager = Greg Ward <gward@python.net>
doc_files = CHANGES.txt
README.txt
USAGE.txt
doc/
examples/
```
Note that the doc_files option is simply a
whitespace-separated string split across multiple lines for readability.
See Also:


3 Writing the Setup Script

simple-example.html | dist.html | setup-config.html | Distributing Python Modules
Previous:
2 Concepts & Terminology (simple-example.html)
Up:
Distributing Python Modules (dist.html)
Next:
4 Writing the Setup (setup-config.html)
---
- 3.1 Listing whole packages (setup-script.html#SECTION000310000000000000000)
  3.2 Listing individual modules (setup-script.html#SECTION000320000000000000000)
  3.3 Describing extension modules (setup-script.html#SECTION000330000000000000000)
  - 3.3.1 Extension names and packages (setup-script.html#SECTION000331000000000000000)
  3.3.2 Extension source files (setup-script.html#SECTION000332000000000000000)
  3.3.3 Preprocessor options (setup-script.html#SECTION000333000000000000000)
  3.3.4 Library options (setup-script.html#SECTION000334000000000000000)
  3.3.5 Other options (setup-script.html#SECTION000335000000000000000)
  3.4 Installing Scripts (setup-script.html#SECTION000340000000000000000)
  3.5 Installing Additional Files (setup-script.html#SECTION000350000000000000000)
  3.6 Additional meta-data (setup-script.html#SECTION000360000000000000000)
  3.7 Debugging the setup script (setup-script.html#SECTION000370000000000000000)
---
# 3 Writing the Setup Script
The setup script is the centre of all activity in building,
distributing, and installing modules using the Distutils. The main
purpose of the setup script is to describe your module distribution to
the Distutils, so that the various commands that operate on your modules
do the right thing. As we saw in section 2.1 (simple-example.html#simple-example) above,
the setup script consists mainly of a call to setup(), and
most information supplied to the Distutils by the module developer is
supplied as keyword arguments to setup().
Here's a slightly more involved example, which we'll follow for the next
couple of sections: the Distutils' own setup script. (Keep in mind that
although the Distutils are included with Python 1.6 and later, they also
have an independent existence so that Python 1.5.2 users can use them to
install other module distributions. The Distutils' own setup script,
shown here, is used to install the package into Python 1.5.2.)
```text

#!/usr/bin/env python

from distutils.core import setup

setup(name="Distutils",
version="1.0",
description="Python Distribution Utilities",
author="Greg Ward",
author_email="gward@python.net",
url="http://www.python.org/sigs/distutils-sig/",
packages=['distutils', 'distutils.command'],
)
```
There are only two differences between this and the trivial one-file
distribution presented in section 2.1 (simple-example.html#simple-example): more
metadata, and the specification of pure Python modules by package,
rather than by module. This is important since the Distutils consist of
a couple of dozen modules split into (so far) two packages; an explicit
list of every module would be tedious to generate and difficult to
maintain. For more information on the additional meta-data, see
section 3.7 (setup-script.html#meta-data).
Note that any pathnames (files or directories) supplied in the setup
script should be written using the Unix convention, i.e.
slash-separated. The Distutils will take care of converting this
platform-neutral representation into whatever is appropriate on your
current platform before actually using the pathname. This makes your
setup script portable across operating systems, which of course is one
of the major goals of the Distutils. In this spirit, all pathnames in
this document are slash-separated. (MacOS programmers should keep in
mind that the absence of a leading slash indicates a relative
path, the opposite of the MacOS convention with colons.)
This, of course, only applies to pathnames given to Distutils
functions. If you, for example, use standard Python functions such as
glob.glob() or os.listdir() to specify files, you
should be careful to write portable code instead of hardcoding path
separators:
```text

glob.glob(os.path.join('mydir', 'subdir', '*.html'))
os.listdir(os.path.join('mydir', 'subdir'))
```
## 3.1 Listing whole packages
The packages option tells the Distutils to process (build,
distribute, install, etc.) all pure Python modules found in each package
mentioned in the packages list. In order to do this, of
course, there has to be a correspondence between package names and
directories in the filesystem. The default correspondence is the most
obvious one, i.e. package distutils is found in the directory
distutils relative to the distribution root. Thus, when you say
`packages = ['foo']` in your setup script, you are promising that
the Distutils will find a file foo/__init__.py (which might
be spelled differently on your system, but you get the idea) relative to
the directory where your setup script lives. If you break this
promise, the Distutils will issue a warning but still process the broken
package anyways.
If you use a different convention to lay out your source directory,
that's no problem: you just have to supply the package_dir
option to tell the Distutils about your convention. For example, say
you keep all Python source under lib, so that modules in the
``root package'' (i.e., not in any package at all) are in
lib, modules in the foo package are in lib/foo,
and so forth. Then you would put
```text

package_dir = {'': 'lib'}
```
in your setup script. The keys to this dictionary are package names,
and an empty package name stands for the root package. The values are
directory names relative to your distribution root. In this case, when
you say `packages = ['foo']`, you are promising that the file
lib/foo/__init__.py exists.
Another possible convention is to put the foo package right in
lib, the foo.bar package in lib/bar, etc. This
would be written in the setup script as
```text

package_dir = {'foo': 'lib'}
```
A `package : dir` entry in the package_dir
dictionary implicitly applies to all packages below package, so
the foo.bar case is automatically handled here. In this
example, having `packages = ['foo', 'foo.bar']` tells the Distutils
to look for lib/__init__.py and
lib/bar/__init__.py. (Keep in mind that although
package_dir applies recursively, you must explicitly list all
packages in packages: the Distutils will not recursively
scan your source tree looking for any directory with an
__init__.py file.)
## 3.2 Listing individual modules
For a small module distribution, you might prefer to list all modules
rather than listing packages--especially the case of a single module
that goes in the ``root package'' (i.e., no package at all). This
simplest case was shown in section 2.1 (simple-example.html#simple-example); here is a
slightly more involved example:
```text

py_modules = ['mod1', 'pkg.mod2']
```
This describes two modules, one of them in the ``root'' package, the
other in the pkg package. Again, the default package/directory
layout implies that these two modules can be found in mod1.py and
pkg/mod2.py, and that pkg/__init__.py exists as well.
And again, you can override the package/directory correspondence using
the package_dir option.
## 3.3 Describing extension modules
Just as writing Python extension modules is a bit more complicated than
writing pure Python modules, describing them to the Distutils is a bit
more complicated. Unlike pure modules, it's not enough just to list
modules or packages and expect the Distutils to go out and find the
right files; you have to specify the extension name, source file(s), and
any compile/link requirements (include directories, libraries to link
with, etc.).
All of this is done through another keyword argument to
setup(), the extensions option. extensions
is just a list of Extension instances, each of which describes a
single extension module. Suppose your distribution includes a single
extension, called foo and implemented by foo.c. If no
additional instructions to the compiler/linker are needed, describing
this extension is quite simple:
```text

uExtension("foo", ["foo.c"])
```
The Extension class can be imported from
distutils.core along with setup(). Thus, the setup
script for a module distribution that contains only this one extension
and nothing else might be:
```text

from distutils.core import setup, Extension
setup(name="foo", version="1.0",
ext_modules=[Extension("foo", ["foo.c"])])
```
The Extension class (actually, the underlying extension-building
machinery implemented by the `build_ext` command) supports a
great deal of flexibility in describing Python extensions, which is
explained in the following sections.
### 3.3.1 Extension names and packages
The first argument to the Extension constructor is always the
name of the extension, including any package names. For example,
```text

Extension("foo", ["src/foo1.c", "src/foo2.c"])
```
describes an extension that lives in the root package, while
```text

Extension("pkg.foo", ["src/foo1.c", "src/foo2.c"])
```
describes the same extension in the pkg package. The source
files and resulting object code are identical in both cases; the only
difference is where in the filesystem (and therefore where in Python's
namespace hierarchy) the resulting extension lives.
If you have a number of extensions all in the same package (or all under
the same base package), use the ext_package keyword argument
to setup(). For example,
```text

setup(...
ext_package="pkg",
ext_modules=[Extension("foo", ["foo.c"]),
Extension("subpkg.bar", ["bar.c"])]
)
```
will compile foo.c to the extension pkg.foo, and
bar.c to pkg.subpkg.bar.
### 3.3.2 Extension source files
The second argument to the Extension constructor is a list of
source files. Since the Distutils currently only support C, C++, and
Objective-C extensions, these are normally C/C++/Objective-C source
files. (Be sure to use appropriate extensions to distinguish C++ source files: .cc and .cpp seem to be recognized by both
Unix and Windows compilers.)
However, you can also include SWIG interface (.i) files in the
list; the `build_ext` command knows how to deal with SWIG
extensions: it will run SWIG on the interface file and compile the
resulting C/C++ file into your extension.
** SWIG support is rough around the edges and largely untested;
especially SWIG support for C++ extensions! Explain in more detail
here when the interface firms up. **
On some platforms, you can include non-source files that are processed
by the compiler and included in your extension. Currently, this just
means Windows message text (.mc) files and resource definition
(.rc) files for Visual C++. These will be compiled to binary resource
(.res) files and linked into the executable.
### 3.3.3 Preprocessor options
Three optional arguments to Extension will help if you need to
specify include directories to search or preprocessor macros to
define/undefine: `include_dirs`, `define_macros`, and
`undef_macros`.
For example, if your extension requires header files in the
include directory under your distribution root, use the
`include_dirs` option:
```text

Extension("foo", ["foo.c"], include_dirs=["include"])
```
You can specify absolute directories there; if you know that your
extension will only be built on Unix systems with X11R6 installed to
/usr, you can get away with
```text

Extension("foo", ["foo.c"], include_dirs=["/usr/include/X11"])
```
You should avoid this sort of non-portable usage if you plan to
distribute your code: it's probably better to write C code like
```text

#include <X11/Xlib.h>
```
If you need to include header files from some other Python extension,
you can take advantage of the fact that header files are installed in a
consistent way by the Distutils `install_header` command. For
example, the Numerical Python header files are installed (on a standard
Unix installation) to /usr/local/include/python1.5/Numerical.
(The exact location will differ according to your platform and Python
installation.) Since the Python include
directory--/usr/local/include/python1.5 in this case--is always
included in the search path when building Python extensions, the best
approach is to write C code like
```text

#include <Numerical/arrayobject.h>
```
If you must put the Numerical include directory right into your
header search path, though, you can find that directory using the
Distutils sysconfig module:
```text

from distutils.sysconfig import get_python_inc
incdir = os.path.join(get_python_inc(plat_specific=1), "Numerical")
setup(...,
Extension(..., include_dirs=[incdir]))
```
Even though this is quite portable--it will work on any Python
installation, regardless of platform--it's probably easier to just
write your C code in the sensible way.
You can define and undefine pre-processor macros with the
`define_macros` and `undef_macros` options.
`define_macros` takes a list of `(name, value)` tuples, where
`name` is the name of the macro to define (a string) and
`value` is its value: either a string or `None`. (Defining a
macro `FOO` to `None` is the equivalent of a bare
`#define FOO` in your C source: with most compilers, this sets
`FOO` to the string `1`.) `undef_macros` is just
a list of macros to undefine.
For example:
```text

Extension(...,
define_macros=[('NDEBUG', '1')],
('HAVE_STRFTIME', None),
undef_macros=['HAVE_FOO', 'HAVE_BAR'])
```
is the equivalent of having this at the top of every C source file:
```text

#define NDEBUG 1
#define HAVE_STRFTIME
#undef HAVE_FOO
#undef HAVE_BAR
```
### 3.3.4 Library options
You can also specify the libraries to link against when building your
extension, and the directories to search for those libraries. The
`libraries` option is a list of libraries to link against,
`library_dirs` is a list of directories to search for libraries at
link-time, and `runtime_library_dirs` is a list of directories to
search for shared (dynamically loaded) libraries at run-time.
For example, if you need to link against libraries known to be in the
standard library search path on target systems
```text

Extension(...,
libraries=["gdbm", "readline"])
```
If you need to link with libraries in a non-standard location, you'll
have to include the location in `library_dirs`:
```text

Extension(...,
library_dirs=["/usr/X11R6/lib"],
libraries=["X11", "Xt"])
```
(Again, this sort of non-portable construct should be avoided if you
intend to distribute your code.)
** Should mention clib libraries here or somewhere else! **
### 3.3.5 Other options
There are still some other options which can be used to handle special
cases.
The extra_objects option is a list of object files to be passed
to the linker. These files must not have extensions, as the default
extension for the compiler is used.
extra_compile_args and extra_link_args can be used
to specify additional command line options for the respective compiler and
linker command lines.
export_symbols is only useful on Windows. It can contain a list
of symbols (functions or variables) to be exported. This option
is not needed when building compiled extensions: Distutils
will automatically add `initmodule`
to the list of exported symbols.
## 3.4 Installing Scripts
So far we have been dealing with pure and non-pure Python modules,
which are usually not run by themselves but imported by scripts.
Scripts are files containing Python source code, intended to be
started from the command line. Scripts don't require Distutils to do
anything very complicated. The only clever feature is that if the
first line of the script starts with `#!` and contains the word
``python'', the Distutils will adjust the first line to refer to the
current interpreter location.
The scripts option simply is a list of files to be handled
in this way. From the PyXML setup script:
```text

setup (...
scripts = ['scripts/xmlproc_parse', 'scripts/xmlproc_val']
)
```
## 3.5 Installing Additional Files
The data_files option can be used to specify additional
files needed by the module distribution: configuration files, message
catalogs, data files, anything which doesn't fit in the previous
categories.
data_files specifies a sequence of (directory,
files) pairs in the following way:
```text

setup(...
data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
('config', ['cfg/data.cfg']),
('/etc/init.d', ['init-script'])]
)
```
Note that you can specify the directory names where the data files
will be installed, but you cannot rename the data files themselves.
Each (directory, files) pair in the sequence specifies the
installation directory and the files to install there. If
directory is a relative path, it is interpreted relative to the
installation prefix (Python's `sys.prefix` for pure-Python
packages, `sys.exec_prefix` for packages that contain extension
modules). Each file name in files is interpreted relative to
the setup.py script at the top of the package source
distribution. No directory information from files is used to
determine the final location of the installed file; only the name of
the file is used.
You can specify the data_files options as a simple sequence
of files without specifying a target directory, but this is not recommended,
and the `install` command will print a warning in this case.
To install data files directly in the target directory, an empty
string should be given as the directory.
## 3.6 Additional meta-data
The setup script may include additional meta-data beyond the name and
version. This information includes:
Notes:
(1): These fields are required.
(2): It is recommended that versions take the form
major.minor[.patch[.sub]].
(3): Either the author or the maintainer must be identified.
(4): These fields should not be used if your package is to be
compatible with Python versions prior to 2.2.3 or 2.3. The list is
available from the PyPI website (http://www.python.org/pypi).
"short string": A single line of text, not more than 200 characters.
"long string": Multiple lines of plain text in ReStructuredText
format (see http://docutils.sf.net/).
"list of strings": See below.
None of the string values may be Unicode.
Encoding the version information is an art in itself. Python packages
generally adhere to the version format
major.minor[.patch][sub]. The major number is
0 for
initial, experimental releases of software. It is incremented for
releases that represent major milestones in a package. The minor
number is incremented when important new features are added to the
package. The patch number increments when bug-fix releases are
made. Additional trailing version information is sometimes used to
indicate sub-releases. These are "a1,a2,...,aN" (for alpha releases,
where functionality and API may change), "b1,b2,...,bN" (for beta
releases, which only fix bugs) and "pr1,pr2,...,prN" (for final
pre-release release testing). Some examples:
0.1.0: the first, experimental release of a package
1.0.1a2: the second alpha release of the first patch version of 1.0
classifiers are specified in a python list:
```text

setup(...
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Python Software Foundation License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: Communications :: Email',
'Topic :: Office/Business',
'Topic :: Software Development :: Bug Tracking',
],
)
```
If you wish to include classifiers in your setup.py file and also
wish to remain backwards-compatible with Python releases prior to 2.2.3,
then you can include the following code fragment in your setup.py
before the `setup()` call.
```text

# patch distutils if it can't cope with the "classifiers" or
# "download_url" keywords
if sys.version < '2.2.3':
from distutils.dist import DistributionMetadata
DistributionMetadata.classifiers = None
DistributionMetadata.download_url = None
```
## 3.7 Debugging the setup script
Sometimes things go wrong, and the setup script doesn't do what the
developer wants.
Distutils catches any exceptions when running the setup script, and
print a simple error message before the script is terminated. The
motivation for this behaviour is to not confuse administrators who
don't know much about Python and are trying to install a package. If
they get a big long traceback from deep inside the guts of Distutils,
they may think the package or the Python installation is broken
because they don't read all the way down to the bottom and see that
it's a permission problem.
On the other hand, this doesn't help the developer to find the cause
of the failure. For this purpose, the DISTUTILS_DEBUG environment
variable can be set to anything except an empty string, and distutils
will now print detailed information what it is doing, and prints the
full traceback in case an exception occurrs.


2 Concepts & Terminology

intro.html | dist.html | setup-script.html | Distributing Python Modules
Previous:
1 Introduction (intro.html)
Up:
Distributing Python Modules (dist.html)
Next:
3 Writing the Setup (setup-script.html)
---
- 2.1 A Simple Example (simple-example.html#SECTION000210000000000000000)
  2.2 General Python terminology (simple-example.html#SECTION000220000000000000000)
  2.3 Distutils-specific terminology (simple-example.html#SECTION000230000000000000000)
---
# 2 Concepts & Terminology
Using the Distutils is quite simple, both for module developers and for
users/administrators installing third-party modules. As a developer,
your responsibilities (apart from writing solid, well-documented and
well-tested code, of course!) are:
- write a setup script (setup.py by convention)
- (optional) write a setup configuration file
- create a source distribution
- (optional) create one or more built (binary) distributions
Each of these tasks is covered in this document.
Not all module developers have access to a multitude of platforms, so
it's not always feasible to expect them to create a multitude of built
distributions. It is hoped that a class of intermediaries, called
packagers, will arise to address this need. Packagers will take
source distributions released by module developers, build them on one or
more platforms, and release the resulting built distributions. Thus,
users on the most popular platforms will be able to install most popular
Python module distributions in the most natural way for their platform,
without having to run a single setup script or compile a line of code.
## 2.1 A Simple Example
The setup script is usually quite simple, although since it's written
in Python, there are no arbitrary limits to what you can do with it,
though you should be careful about putting arbitrarily expensive
operations in your setup script. Unlike, say, Autoconf-style configure
scripts, the setup script may be run multiple times in the course of
building and installing your module distribution.
If all you want to do is distribute a module called foo,
contained in a file foo.py, then your setup script can be as
simple as this:
```text

from distutils.core import setup
setup(name="foo",
version="1.0",
py_modules=["foo"])
```
Some observations:
- most information that you supply to the Distutils is supplied as
keyword arguments to the setup() function
- those keyword arguments fall into two categories: package
metadata (name, version number) and information about what's in the
package (a list of pure Python modules, in this case)
- modules are specified by module name, not filename (the same will
hold true for packages and extensions)
- it's recommended that you supply a little more metadata, in
particular your name, email address and a URL for the project
(see section 3 (setup-script.html#setup-script) for an example)
To create a source distribution for this module, you would create a
setup script, setup.py, containing the above code, and run:
```text

python setup.py sdist
```
which will create an archive file (e.g., tarball on Unix, ZIP file on
Windows) containing your setup script setup.py, and your module
foo.py. The archive file will be named foo-1.0.tar.gz (or
.zip), and will unpack into a directory foo-1.0.
If an end-user wishes to install your foo module, all she has
to do is download foo-1.0.tar.gz (or .zip), unpack it,
and--from the foo-1.0 directory--run
```text

python setup.py install
```
which will ultimately copy foo.py to the appropriate directory
for third-party modules in their Python installation.
This simple example demonstrates some fundamental concepts of the
Distutils. First, both developers and installers have the same basic
user interface, i.e. the setup script. The difference is which
Distutils commands they use: the `sdist` command is
almost exclusively for module developers, while `install` is
more often for installers (although most developers will want to install
their own code occasionally).
If you want to make things really easy for your users, you can create
one or more built distributions for them. For instance, if you are
running on a Windows machine, and want to make things easy for other
Windows users, you can create an executable installer (the most
appropriate type of built distribution for this platform) with the
`bdist_wininst` command. For example:
```text

python setup.py bdist_wininst
```
will create an executable installer, foo-1.0.win32.exe, in the
current directory.
Other useful built distribution formats are RPM, implemented by the
`bdist_rpm` command, Solaris pkgtool
(`bdist_pkgtool`), and HP-UX swinstall
(`bdist_sdux`). For example, the following command will
create an RPM file called foo-1.0.noarch.rpm:
```text

python setup.py bdist_rpm
```
(The `bdist_rpm` command uses the `rpm` executable,
therefore this has to be run on an RPM-based system such as Red Hat
Linux, SuSE Linux, or Mandrake Linux.)
You can find out what distribution formats are available at any time by
running
```text

python setup.py bdist --help-formats
```
## 2.2 General Python terminology
If you're reading this document, you probably have a good idea of what
modules, extensions, and so forth are. Nevertheless, just to be sure
that everyone is operating from a common starting point, we offer the
following glossary of common Python terms:
module: the basic unit of code reusability in Python: a block of
code imported by some other code. Three types of modules concern us
here: pure Python modules, extension modules, and packages.
pure Python module: a module written in Python and contained in a
single .py file (and possibly associated .pyc and/or
.pyo files). Sometimes referred to as a ``pure module.''
extension module: a module written in the low-level language of
the Python implementation: C/C++ for Python, Java for Jython.
Typically contained in a single dynamically loadable pre-compiled
file, e.g. a shared object (.so) file for Python extensions on
Unix, a DLL (given the .pyd extension) for Python extensions
on Windows, or a Java class file for Jython extensions. (Note that
currently, the Distutils only handles C/C++ extensions for Python.)
package: a module that contains other modules; typically contained
in a directory in the filesystem and distinguished from other
directories by the presence of a file __init__.py.
root package: the root of the hierarchy of packages. (This isn't
really a package, since it doesn't have an __init__.py
file. But we have to call it something.) The vast majority of the
standard library is in the root package, as are many small, standalone
third-party modules that don't belong to a larger module collection.
Unlike regular packages, modules in the root package can be found in
many directories: in fact, every directory listed in `sys.path`
contributes modules to the root package.
## 2.3 Distutils-specific terminology
The following terms apply more specifically to the domain of
distributing Python modules using the Distutils:
module distribution: a collection of Python modules distributed
together as a single downloadable resource and meant to be installed
en masse. Examples of some well-known module distributions are
Numeric Python, PyXML, PIL (the Python Imaging Library), or
mxBase. (This would be called a package, except that term
is already taken in the Python context: a single module distribution
may contain zero, one, or many Python packages.)
pure module distribution: a module distribution that contains only
pure Python modules and packages. Sometimes referred to as a ``pure
distribution.''
non-pure module distribution: a module distribution that contains
at least one extension module. Sometimes referred to as a ``non-pure
distribution.''
distribution root: the top-level directory of your source tree (or
source distribution); the directory where setup.py exists. Generally
setup.py will be run from this directory.


8 Examples

package-index.html | dist.html | sdist-cmd.html | Distributing Python Modules
Previous:
7 Registering with the (package-index.html)
Up:
Distributing Python Modules (dist.html)
Next:
9 Reference (sdist-cmd.html)
---
- 8.1 Pure Python distribution (by module) (single-ext.html#SECTION000810000000000000000)
  8.2 Pure Python distribution (by package) (single-ext.html#SECTION000820000000000000000)
  8.3 Single extension module (single-ext.html#SECTION000830000000000000000)
---
# 8 Examples
## 8.1 Pure Python distribution (by module)
If you're just distributing a couple of modules, especially if they
don't live in a particular package, you can specify them individually
using the py_modules option in the setup script.
In the simplest case, you'll have two files to worry about: a setup
script and the single module you're distributing, foo.py in this
example:
```text

<root>/
setup.py
foo.py
```
(In all diagrams in this section, `<root>` will refer to the
distribution root directory.) A minimal setup script to describe this
situation would be:
```text

from distutils.core import setup
setup(name = "foo", version = "1.0",
py_modules = ["foo"])
```
Note that the name of the distribution is specified independently with
the name option, and there's no rule that says it has to be the
same as the name of the sole module in the distribution (although that's
probably a good convention to follow). However, the distribution name
is used to generate filenames, so you should stick to letters, digits,
underscores, and hyphens.
Since py_modules is a list, you can of course specify multiple
modules, eg. if you're distributing modules foo and
bar, your setup might look like this:
```text

<root>/
setup.py
foo.py
bar.py
```
and the setup script might be
```text

from distutils.core import setup
setup(name = "foobar", version = "1.0",
py_modules = ["foo", "bar"])
```
You can put module source files into another directory, but if you have
enough modules to do that, it's probably easier to specify modules by
package rather than listing them individually.
## 8.2 Pure Python distribution (by package)
If you have more than a couple of modules to distribute, especially if
they are in multiple packages, it's probably easier to specify whole
packages rather than individual modules. This works even if your
modules are not in a package; you can just tell the Distutils to process
modules from the root package, and that works the same as any other
package (except that you don't have to have an __init__.py
file).
The setup script from the last example could also be written as
```text

from distutils.core import setup
setup(name = "foobar", version = "1.0",
packages = [""])
```
(The empty string stands for the root package.)
If those two files are moved into a subdirectory, but remain in the root
package, e.g.:
```text

<root>/
setup.py
src/ foo.py
bar.py
```
then you would still specify the root package, but you have to tell the
Distutils where source files in the root package live:
```text

from distutils.core import setup
setup(name = "foobar", version = "1.0",
package_dir = {"": "src"},
packages = [""])
```
More typically, though, you will want to distribute multiple modules in
the same package (or in sub-packages). For example, if the foo
and bar modules belong in package foobar, one way to
layout your source tree is
```text

<root>/
setup.py
foobar/
__init__.py
foo.py
bar.py
```
This is in fact the default layout expected by the Distutils, and the
one that requires the least work to describe in your setup script:
```text

from distutils.core import setup
setup(name = "foobar", version = "1.0",
packages = ["foobar"])
```
If you want to put modules in directories not named for their package,
then you need to use the package_dir option again. For
example, if the src directory holds modules in the
foobar package:
```text

<root>/
setup.py
src/
__init__.py
foo.py
bar.py
```
an appropriate setup script would be
```text

from distutils.core import setup
setup(name = "foobar", version = "1.0",
package_dir = {"foobar" : "src"},
packages = ["foobar"])
```
Or, you might put modules from your main package right in the
distribution root:
```text

<root>/
setup.py
__init__.py
foo.py
bar.py
```
in which case your setup script would be
```text

from distutils.core import setup
setup(name = "foobar", version = "1.0",
package_dir = {"foobar" : ""},
packages = ["foobar"])
```
(The empty string also stands for the current directory.)
If you have sub-packages, they must be explicitly listed in
packages, but any entries in package_dir
automatically extend to sub-packages. (In other words, the Distutils
does not scan your source tree, trying to figure out which
directories correspond to Python packages by looking for
__init__.py files.) Thus, if the default layout grows a
sub-package:
```text

<root>/
setup.py
foobar/
__init__.py
foo.py
bar.py
subfoo/
__init__.py
blah.py
```
then the corresponding setup script would be
```text

from distutils.core import setup
setup(name = "foobar", version = "1.0",
packages = ["foobar", "foobar.subfoo"])
```
(Again, the empty string in package_dir stands for the current
directory.)
## 8.3 Single extension module
Extension modules are specified using the ext_modules option.
package_dir has no effect on where extension source files are
found; it only affects the source for pure Python modules. The simplest
case, a single extension module in a single C source file, is:
```text

<root>/
setup.py
foo.c
```
If the foo extension belongs in the root package, the setup
script for this could be
```text

from distutils.core import setup
setup(name = "foobar", version = "1.0",
ext_modules = [Extension("foo", ["foo.c"])])
```
If the extension actually belongs in a package, say foopkg,
then
With exactly the same source tree layout, this extension can be put in
the foopkg package simply by changing the name of the
extension:
```text

from distutils.core import setup
setup(name = "foobar", version = "1.0",
ext_modules = [Extension("foopkg.foo", ["foo.c"])])
```


5 Creating a Source Distribution

setup-config.html | dist.html | postinstallation-script.html | Distributing Python Modules
Previous:
4 Writing the Setup (setup-config.html)
Up:
Distributing Python Modules (dist.html)
Next:
6 Creating Built Distributions (postinstallation-script.html)
---
- 5.1 Specifying the files to distribute (source-dist.html#SECTION000510000000000000000)
  5.2 Manifest-related options (source-dist.html#SECTION000520000000000000000)
---
# 5 Creating a Source Distribution
As shown in section 2.1 (simple-example.html#simple-example), you use the
`sdist` command to create a source distribution. In the
simplest case,
```text

python setup.py sdist
```
(assuming you haven't specified any `sdist` options in the setup
script or config file), `sdist` creates the archive of the
default format for the current platform. The default format is a gzip'ed
tar file (.tar.gz) on Unix, and ZIP file on Windows.
** no MacOS support here **
You can specify as many formats as you like using the
--formats option, for example:
```text

python setup.py sdist --formats=gztar,zip
```
to create a gzipped tarball and a zip file. The available formats are:
Notes:
(1): default on Windows
(2): default on Unix
(3): requires either external zip utility or
zipfile module (part of the standard Python library since
Python 1.6)
(4): requires external utilities: tar and possibly one
of gzip, bzip2, or compress
## 5.1 Specifying the files to distribute
If you don't supply an explicit list of files (or instructions on how to
generate one), the `sdist` command puts a minimal default set
into the source distribution:
- all Python source files implied by the py_modules and
packages options
- all C source files mentioned in the ext_modules or
libraries options (** getting C library sources currently
broken - no get_source_files() method in build_clib.py! **)
- anything that looks like a test script: test/test*.py
(currently, the Distutils don't do anything with test scripts except
include them in source distributions, but in the future there will be
a standard for testing Python module distributions)
- README.txt (or README), setup.py (or whatever
you called your setup script), and setup.cfg
Sometimes this is enough, but usually you will want to specify
additional files to distribute. The typical way to do this is to write
a manifest template, called MANIFEST.in by default. The
manifest template is just a list of instructions for how to generate
your manifest file, MANIFEST, which is the exact list of files to
include in your source distribution. The `sdist` command
processes this template and generates a manifest based on its
instructions and what it finds in the filesystem.
If you prefer to roll your own manifest file, the format is simple: one
filename per line, regular files (or symlinks to them) only. If you do
supply your own MANIFEST, you must specify everything: the
default set of files described above does not apply in this case.
The manifest template has one command per line, where each command
specifies a set of files to include or exclude from the source
distribution. For an example, again we turn to the Distutils' own
manifest template:
```text

include *.txt
recursive-include examples *.txt *.py
prune examples/sample?/build
```
The meanings should be fairly clear: include all files in the
distribution root matching `*.txt`, all files anywhere under the
examples directory matching `*.txt` or `*.py`, and
exclude all directories matching `examples/sample?/build`. All of
this is done after the standard include set, so you can exclude
files from the standard set with explicit instructions in the manifest
template. (Or, you can use the --no-defaults option to
disable the standard set entirely.) There are several other commands
available in the manifest template mini-language; see
section 9.2 (sdist-cmd.html#sdist-cmd).
The order of commands in the manifest template matters: initially, we
have the list of default files as described above, and each command in
the template adds to or removes from that list of files. Once we have
fully processed the manifest template, we remove files that should not
be included in the source distribution:
- all files in the Distutils ``build'' tree (default build/)
- all files in directories named RCS or CVS
Now we have our complete list of files, which is written to the manifest
for future reference, and then used to build the source distribution
archive(s).
You can disable the default set of included files with the
--no-defaults option, and you can disable the standard
exclude set with --no-prune.
Following the Distutils' own manifest template, let's trace how the
`sdist` command builds the list of files to include in the
Distutils source distribution:
1. include all Python source files in the distutils and
distutils/command subdirectories (because packages
corresponding to those two directories were mentioned in the
packages option in the setup script--see
section 3 (setup-script.html#setup-script))
2. include README.txt, setup.py, and setup.cfg
(standard files)
3. include test/test*.py (standard files)
4. include *.txt in the distribution root (this will find
README.txt a second time, but such redundancies are weeded out
later)
5. include anything matching *.txt or *.py in the
sub-tree under examples,
6. exclude all files in the sub-trees starting at directories
matching examples/sample?/build--this may exclude files
included by the previous two steps, so it's important that the
`prune` command in the manifest template comes after the
`recursive-include` command
7. exclude the entire build tree, and any RCS or
CVS directories
Just like in the setup script, file and directory names in the manifest
template should always be slash-separated; the Distutils will take care
of converting them to the standard representation on your platform.
That way, the manifest template is portable across operating systems.
## 5.2 Manifest-related options
The normal course of operations for the `sdist` command is as
follows:
- if the manifest file, MANIFEST doesn't exist, read
MANIFEST.in and create the manifest
- if neither MANIFEST nor MANIFEST.in exist, create a
manifest with just the default file set
- if either MANIFEST.in or the setup script (setup.py)
are more recent than MANIFEST, recreate MANIFEST by
reading MANIFEST.in
- use the list of files now in MANIFEST (either just
generated or read in) to create the source distribution archive(s)
There are a couple of options that modify this behaviour. First, use
the --no-defaults and --no-prune to
disable the standard ``include'' and ``exclude'' sets.
Second, you might want to force the manifest to be regenerated--for
example, if you have added or removed files or directories that match an
existing pattern in the manifest template, you should regenerate the
manifest:
```text

python setup.py sdist --force-manifest
```
Or, you might just want to (re)generate the manifest, but not create a
source distribution:
```text

python setup.py sdist --manifest-only
```
--manifest-only implies --force-manifest.
-o is a shortcut for --manifest-only, and
-f for --force-manifest.


About this document ...

discussion.html | doc.html | Documenting Python | contents.html
Previous:
8.2 Discussion Forums (discussion.html)
Up:
Documenting Python (doc.html)
---
# About this document ...
Documenting Python,
July 29, 2003, Release 2.3
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, either in the content or the presentation, 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.


5 Document Classes

latex-structure.html | doc.html | special-constructs.html | Documenting Python | contents.html
Previous:
4.2 Hierarchical Structure (latex-structure.html)
Up:
Documenting Python (doc.html)
Next:
6 Special Markup Constructs (special-constructs.html)
---
# 5 Document Classes
Two LATEX document classes are defined specifically for use with
the Python documentation. The `manual` class is for large
documents which are sectioned into chapters, and the `howto`
class is for smaller documents.
The `manual` documents are larger and are used for most of the
standard documents. This document class is based on the standard
LATEX `report` class and is formatted very much like a long
technical report. The Python Reference
Manual (../ref/ref.html) is a good example of a `manual` document, and the
Python Library Reference (../lib/lib.html) is a large
example.
The `howto` documents are shorter, and don't have the large
structure of the `manual` documents. This class is based on
the standard LATEX `article` class and is formatted somewhat
like the Linux Documentation Project's ``HOWTO'' series as done
originally using the LinuxDoc software. The original intent for the
document class was that it serve a similar role as the LDP's HOWTO
series, but the applicability of the class turns out to be somewhat
broader. This class is used for ``how-to'' documents (this
document is an example) and for shorter reference manuals for small,
fairly cohesive module libraries. Examples of the later use include
Using
Kerberos from Python (http://starship.python.net/crew/fdrake/manuals/krb5py/krb5py.html), which contains reference material for an
extension package. These documents are roughly equivalent to a
single chapter from a larger work.


Contents

doc.html | doc.html | intro.html | Documenting Python
Previous:
Documenting Python (doc.html)
Up:
Documenting Python (doc.html)
Next:
1 Introduction (intro.html)
---
## Contents
Table of Contents
- 1 Introduction (intro.html)
  2 Directory Structure (directories.html)
  3 Style Guide (style-guide.html)
  4 LATEX Primer (latex-primer.html)
  - 4.1 Syntax (latex-syntax.html)
  4.2 Hierarchical Structure (latex-structure.html)
  5 Document Classes (classes.html)
  6 Special Markup Constructs (special-constructs.html)
  - 6.1 Markup for the Preamble (preamble-info.html)
  6.2 Meta-information Markup (meta-info.html)
  6.3 Information Units (info-units.html)
  6.4 Showing Code Examples (showing-examples.html)
  6.5 Inline Markup (inline-markup.html)
  6.6 Miscellaneous Text Markup (misc-text-markup.html)
  6.7 Module-specific Markup (module-markup.html)
  6.8 Library-level Markup (library-markup.html)
  6.9 Table Markup (table-markup.html)
  6.10 Reference List Markup (references.html)
  6.11 Index-generating Markup (indexing.html)
  6.12 Grammar Production Displays (grammar-displays.html)
  6.13 Graphical Interface Components (gui-markup.html)
  7 Processing Tools (tools.html)
  - 7.1 External Tools (tools-external.html)
  7.2 Internal Tools (tools-internal.html)
  7.3 Working on Cygwin (cygwin.html)
  8 Future Directions (futures.html)
  - 8.1 Structured Documentation (structured.html)
  8.2 Discussion Forums (discussion.html)
  About this document ... (about.html)
End of Table of Contents


7.3 Working on Cygwin

tools-internal.html | tools.html | futures.html | Documenting Python | contents.html
Previous:
7.2 Internal Tools (tools-internal.html)
Up:
7 Processing Tools (tools.html)
Next:
8 Future Directions (futures.html)
---
## 7.3 Working on Cygwin
Installing the required tools under Cygwin under Cygwin can be a
little tedious, if only because many packages are more difficult
to install under Cygwin.
Using the Cygwin installer, make sure your Cygwin installation
includes Perl, Python, and the TEX packages. Perl and Python
are located under Interpreters in the installer.
The TEX packages are located in the Text
section; installing the `tetex-beta`, `texmf`,
`texmf-base`, and `texmf-extra` ensures that all the
required packages are available. (There may be a more minimal
set, but I've not spent time trying to minimize the installation.)
The netpbm package is used by LATEX2HTML, and must be
installed before LATEX2HTML can be successfully installed, even
though they will never be used for most Python documentation.
References to download locations are located in the netpbm
README (http://netpbm.sourceforge.net/README). Install according
to the instructions.
LATEX2HTML can be installed from the source archive, but only
after munging one of the files in the distribution. Edit the file
L2hos.pm in the top level of the unpacked distribution;
near the bottom of the file, change the text
`$^O` with the text `'unix'`. Proceed
using this command to build and install the software:
```text

% configure && make install
```
You should now be able to build at least the HTML, PDF, and
PostScript versions of the formatted documentation.


2 Directory Structure

intro.html | doc.html | style-guide.html | Documenting Python | contents.html
Previous:
1 Introduction (intro.html)
Up:
Documenting Python (doc.html)
Next:
3 Style Guide (style-guide.html)
---
# 2 Directory Structure
The source distribution for the standard Python documentation
contains a large number of directories. While third-party documents
do not need to be placed into this structure or need to be placed
within a similar structure, it can be helpful to know where to look
for examples and tools when developing new documents using the
Python documentation tools. This section describes this directory
structure.
The documentation sources are usually placed within the Python
source distribution as the top-level directory Doc/, but
are not dependent on the Python source distribution in any way.
The Doc/ directory contains a few files and several
subdirectories. The files are mostly self-explanatory, including a
README and a Makefile. The directories fall into
three categories: