<li><a class="reference" href="#general-library-questions" id="id3" name="id3">1 General Library Questions</a><ul class="auto-toc">
<li><a class="reference" href="#how-do-i-find-a-module-or-application-to-perform-task-x" id="id4" name="id4">1.1 How do I find a module or application to perform task X?</a></li>
<li><a class="reference" href="#where-is-the-math-py-socket-py-regex-py-etc-source-file" id="id5" name="id5">1.2 Where is the math.py (socket.py, regex.py, etc.) source file?</a></li>
<li><a class="reference" href="#how-do-i-make-a-python-script-executable-on-unix" id="id6" name="id6">1.3 How do I make a Python script executable on Unix?</a></li>
<li><a class="reference" href="#is-there-a-curses-termcap-package-for-python" id="id7" name="id7">1.4 Is there a curses/termcap package for Python?</a></li>
<li><a class="reference" href="#is-there-an-equivalent-to-c-s-onexit-in-python" id="id8" name="id8">1.5 Is there an equivalent to C's onexit() in Python?</a></li>
<li><a class="reference" href="#why-don-t-my-signal-handlers-work" id="id9" name="id9">1.6 Why don't my signal handlers work?</a></li>
</ul>
</li>
<li><a class="reference" href="#common-tasks" id="id10" name="id10">2 Common tasks</a><ul class="auto-toc">
<li><a class="reference" href="#how-do-i-test-a-python-program-or-component" id="id11" name="id11">2.1 How do I test a Python program or component?</a></li>
<li><a class="reference" href="#how-do-i-create-documentation-from-doc-strings" id="id12" name="id12">2.2 How do I create documentation from doc strings?</a></li>
<li><a class="reference" href="#how-do-i-get-a-single-keypress-at-a-time" id="id13" name="id13">2.3 How do I get a single keypress at a time?</a></li>
<li><a class="reference" href="#how-do-i-program-using-threads" id="id15" name="id15">3.1 How do I program using threads?</a></li>
<li><a class="reference" href="#none-of-my-threads-seem-to-run-why" id="id16" name="id16">3.2 None of my threads seem to run: why?</a></li>
<li><a class="reference" href="#how-do-i-parcel-out-work-among-a-bunch-of-worker-threads" id="id17" name="id17">3.3 How do I parcel out work among a bunch of worker threads?</a></li>
<li><a class="reference" href="#what-kinds-of-global-value-mutation-are-thread-safe" id="id18" name="id18">3.4 What kinds of global value mutation are thread-safe?</a></li>
<li><a class="reference" href="#can-t-we-get-rid-of-the-global-interpreter-lock" id="id19" name="id19">3.5 Can't we get rid of the Global Interpreter Lock?</a></li>
</ul>
</li>
<li><a class="reference" href="#input-and-output" id="id20" name="id20">4 Input and Output</a><ul class="auto-toc">
<li><a class="reference" href="#how-do-i-delete-a-file-and-other-file-questions" id="id21" name="id21">4.1 How do I delete a file? (And other file questions...)</a></li>
<li><a class="reference" href="#how-do-i-copy-a-file" id="id22" name="id22">4.2 How do I copy a file?</a></li>
<li><a class="reference" href="#how-do-i-read-or-write-binary-data" id="id23" name="id23">4.3 How do I read (or write) binary data?</a></li>
<li><a class="reference" href="#i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why" id="id24" name="id24">4.4 I can't seem to use os.read() on a pipe created with os.popen(); why?</a></li>
<li><a class="reference" href="#how-do-i-run-a-subprocess-with-pipes-connected-to-both-input-and-output" id="id25" name="id25">4.5 How do I run a subprocess with pipes connected to both input and output?</a></li>
<li><a class="reference" href="#how-do-i-access-the-serial-rs232-port" id="id26" name="id26">4.6 How do I access the serial (RS232) port?</a></li>
<li><a class="reference" href="#what-www-tools-are-there-for-python" id="id29" name="id29">5.1 What WWW tools are there for Python?</a></li>
<li><a class="reference" href="#how-can-i-mimic-cgi-form-submission-method-post" id="id30" name="id30">5.2 How can I mimic CGI form submission (METHOD=POST)?</a></li>
<li><a class="reference" href="#what-module-should-i-use-to-help-with-generating-html" id="id31" name="id31">5.3 What module should I use to help with generating HTML?</a></li>
<li><a class="reference" href="#how-do-i-send-mail-from-a-python-script" id="id32" name="id32">5.4 How do I send mail from a Python script?</a></li>
<li><a class="reference" href="#how-do-i-avoid-blocking-in-the-connect-method-of-a-socket" id="id33" name="id33">5.5 How do I avoid blocking in the connect() method of a socket?</a></li>
<li><a class="reference" href="#are-there-any-interfaces-to-database-packages-in-python" id="id35" name="id35">6.1 Are there any interfaces to database packages in Python?</a></li>
<li><a class="reference" href="#how-do-you-implement-persistent-objects-in-python" id="id36" name="id36">6.2 How do you implement persistent objects in Python?</a></li>
<li><a class="reference" href="#why-is-cpickle-so-slow" id="id37" name="id37">6.3 Why is cPickle so slow?</a></li>
<li><a class="reference" href="#if-my-program-crashes-with-a-bsddb-or-anydbm-database-open-it-gets-corrupted-how-come" id="id38" name="id38">6.4 If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?</a></li>
<li><a class="reference" href="#i-tried-to-open-berkeley-db-file-but-bsddb-produces-bsddb-error-22-invalid-argument-help-how-can-i-restore-my-data" id="id39" name="id39">6.5 I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data?</a></li>
</ul>
</li>
<li><a class="reference" href="#mathematics-and-numerics" id="id40" name="id40">7 Mathematics and Numerics</a><ul class="auto-toc">
<li><a class="reference" href="#how-do-i-generate-random-numbers-in-python" id="id41" name="id41">7.1 How do I generate random numbers in Python?</a></li>
</ul>
</li>
</ul>
</div>
<div class="section">
<h1><a class="toc-backref" href="#id3" id="general-library-questions" name="general-library-questions">1 General Library Questions</a></h1>
<div class="section">
<h2><a class="toc-backref" href="#id4" id="how-do-i-find-a-module-or-application-to-perform-task-x" name="how-do-i-find-a-module-or-application-to-perform-task-x">1.1 How do I find a module or application to perform task X?</a></h2>
<p>Check <a class="reference" href="http://www.python.org/doc/lib/">the Library Reference</a> to see
if there's a relevant standard library module. (Eventually you'll
learn what's in the standard library and will able to skip this step.)</p>
<p>Search the <a class="reference" href="http://cheeseshop.python.org/pypi">Python Package Index</a>.</p>
<p>Next, check the <a class="reference" href="http://www.vex.net/parnassus/">Vaults of Parnassus</a>,
an older index of packages.</p>
<p>Finally, try <a class="reference" href="http://www.google.com">Google</a> or other Web search
engine. Searching for "Python" plus a keyword or two for your topic
of interest will usually find something helpful.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id5" id="where-is-the-math-py-socket-py-regex-py-etc-source-file" name="where-is-the-math-py-socket-py-regex-py-etc-source-file">1.2 Where is the math.py (socket.py, regex.py, etc.) source file?</a></h2>
<p>If you can't find a source file for a module it may be a builtin
or dynamically loaded module implemented in C, C++ or other
compiled language. In this case you may not have the source
file or it may be something like mathmodule.c, somewhere in
a C source directory (not on the Python Path).</p>
<p>There are (at least) three kinds of modules in Python:</p>
<ol class="arabic">
<li><p class="first">modules written in Python (.py);</p>
</li>
<li><p class="first">modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);</p>
</li>
<li><p class="first">modules written in C and linked with the interpreter; to get a list
of these, type:</p>
<pre class="literal-block">
import sys
print sys.builtin_module_names
</pre>
</li>
</ol>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id6" id="how-do-i-make-a-python-script-executable-on-unix" name="how-do-i-make-a-python-script-executable-on-unix">1.3 How do I make a Python script executable on Unix?</a></h2>
<p>You need to do two things: the script file's mode must be executable
and the first line must begin with <tt class="docutils literal"><span class="pre">#!</span></tt> followed by the path of
the Python interpreter.</p>
<p>The first is done by executing <tt class="docutils literal"><span class="pre">chmod</span> <span class="pre">+x</span> <span class="pre">scriptfile</span></tt> or perhaps
<p>The second can be done in a number of ways. The most straightforward
way is to write</p>
<pre class="literal-block">
#!/usr/local/bin/python
</pre>
<p>as the very first line of your file, using the pathname for where the
Python interpreter is installed on your platform.</p>
<p>If you would like the script to be independent of where the Python
interpreter lives, you can use the "env" program. Almost all
Unix variants support the following, assuming the python interpreter
is in a directory on the user's $PATH:</p>
<pre class="literal-block">
#! /usr/bin/env python
</pre>
<p><em>Don't</em> do this for CGI scripts. The $PATH variable for
CGI scripts is often very minimal, so you need to use the actual
absolute pathname of the interpreter.</p>
<p>Occasionally, a user's environment is so full that the /usr/bin/env
program fails; or there's no env program at all.
In that case, you can try the following hack (due to Alex Rezinsky):</p>
<pre class="literal-block">
#! /bin/sh
""":"
exec python $0 ${1+"$@"}
"""
</pre>
<p>The minor disadvantage is that this defines the script's __doc__ string.
However, you can fix that by adding</p>
<pre class="literal-block">
__doc__ = """...Whatever..."""
</pre>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id7" id="is-there-a-curses-termcap-package-for-python" name="is-there-a-curses-termcap-package-for-python">1.4 Is there a curses/termcap package for Python?</a></h2>
<p>For Unix variants: The standard Python source distribution comes with
a curses module in the Modules/ subdirectory, though it's not compiled
by default (note that this is not available in the Windows
distribution -- there is no curses module for Windows).</p>
<p>The curses module supports basic curses features as well as many
additional functions from ncurses and SYSV curses such as colour,
alternative character set support, pads, and mouse support. This means
the module isn't compatible with operating systems that only
have BSD curses, but there don't seem to be any currently maintained
OSes that fall into this category.</p>
<p>For Windows: use <a class="reference" href="http://effbot.org/zone/console-index.htm">the consolelib module</a>.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id8" id="is-there-an-equivalent-to-c-s-onexit-in-python" name="is-there-an-equivalent-to-c-s-onexit-in-python">1.5 Is there an equivalent to C's onexit() in Python?</a></h2>
<p><a class="reference" href="http://www.python.org/doc/lib/module-atexit.html">The atexit module</a> provides a
register function that is similar to C's onexit.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id9" id="why-don-t-my-signal-handlers-work" name="why-don-t-my-signal-handlers-work">1.6 Why don't my signal handlers work?</a></h2>
<p>The most common problem is that the signal handler is declared
with the wrong argument list. It is called as</p>
<pre class="literal-block">
handler(signum, frame)
</pre>
<p>so it should be declared with two arguments:</p>
<pre class="literal-block">
def handler(signum, frame):
...
</pre>
</div>
</div>
<div class="section">
<h1><a class="toc-backref" href="#id10" id="common-tasks" name="common-tasks">2 Common tasks</a></h1>
<div class="section">
<h2><a class="toc-backref" href="#id11" id="how-do-i-test-a-python-program-or-component" name="how-do-i-test-a-python-program-or-component">2.1 How do I test a Python program or component?</a></h2>
<p>Python comes with two testing frameworks. The <a class="reference" href="http://www.python.org/doc/lib/module-doctest.html">doctest module</a> finds examples
in the docstrings for a module and runs them, comparing the output
with the expected output given in the docstring.</p>
<p>The <a class="reference" href="http://www.python.org/doc/lib/module-unittest.html">unittest module</a> is a fancier
testing framework modelled on Java and Smalltalk testing frameworks.</p>
<p>For testing, it helps to write the program so that it may be easily
tested by using good modular design. Your program should have almost
all functionality encapsulated in either functions or class methods --
and this sometimes has the surprising and delightful effect of making
the program run faster (because local variable accesses are faster
than global accesses). Furthermore the program should avoid depending
on mutating global variables, since this makes testing much more
difficult to do.</p>
<p>The "global main logic" of your program may be as simple
as</p>
<pre class="literal-block">
if __name__=="__main__":
main_logic()
</pre>
<p>at the bottom of the main module of your program.</p>
<p>Once your program is organized as a tractable collection
of functions and class behaviours you should write test
functions that exercise the behaviours. A test suite
can be associated with each module which automates
a sequence of tests. This sounds like a lot of work, but
since Python is so terse and flexible it's surprisingly easy.
You can make coding much more pleasant and fun by
writing your test functions in parallel with the "production
code", since this makes it easy to find bugs and even
design flaws earlier.</p>
<p>"Support modules" that are not intended to be the main module of a
program may include a self-test of the module.</p>
<pre class="literal-block">
if __name__ == "__main__":
self_test()
</pre>
<p>Even programs that interact with complex external interfaces may be
tested when the external interfaces are unavailable by using "fake"
interfaces implemented in Python.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id12" id="how-do-i-create-documentation-from-doc-strings" name="how-do-i-create-documentation-from-doc-strings">2.2 How do I create documentation from doc strings?</a></h2>
can create HTML from the doc strings in your Python source code. An
alternative is <a class="reference" href="http://starship.python.net/crew/danilo/pythondoc/">pythondoc</a>.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id13" id="how-do-i-get-a-single-keypress-at-a-time" name="how-do-i-get-a-single-keypress-at-a-time">2.3 How do I get a single keypress at a time?</a></h2>
<p>For Unix variants:There are several solutions.
It's straightforward to do this using curses, but curses is a
fairly large module to learn. Here's a solution without curses:</p>
<p>You need the <tt class="docutils literal"><span class="pre">termios</span></tt> and the <tt class="docutils literal"><span class="pre">fcntl</span></tt> module for any of this to work,
and I've only tried it on Linux, though it should work elsewhere.
In this code, characters are read and printed one at a time.</p>
<p><tt class="docutils literal"><span class="pre">termios.tcsetattr()</span></tt> turns off stdin's echoing and disables canonical
mode. <tt class="docutils literal"><span class="pre">fcntl.fnctl()</span></tt> is used to obtain stdin's file descriptor flags
and modify them for non-blocking mode. Since reading stdin when it is
empty results in an <tt class="docutils literal"><span class="pre">IOError</span></tt>, this error is caught and ignored.</p>
<h2><a class="toc-backref" href="#id15" id="how-do-i-program-using-threads" name="how-do-i-program-using-threads">3.1 How do I program using threads?</a></h2>
<p>Be sure to use <a class="reference" href="http://www.python.org/doc/lib/module-threading.html">the threading module</a> and not the
<p>Aahz has a set of slides from his threading tutorial that are helpful;
see <a class="reference" href="http://starship.python.net/crew/aahz/OSCON2001/">http://starship.python.net/crew/aahz/OSCON2001/</a>.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id16" id="none-of-my-threads-seem-to-run-why" name="none-of-my-threads-seem-to-run-why">3.2 None of my threads seem to run: why?</a></h2>
<p>As soon as the main thread exits, all threads are killed. Your main
thread is running too quickly, giving the threads no time to do any work.</p>
<p>A simple fix is to add a sleep to the end of the program
that's long enough for all the threads to finish:</p>
<pre class="literal-block">
import threading, time
def thread_task(name, n):
for i in range(n): print name, i
for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()
time.sleep(10) # <----------------------------!
</pre>
<p>But now (on many platforms) the threads don't run in parallel,
but appear to run sequentially, one at a time! The reason is
that the OS thread scheduler doesn't start a new thread until
the previous thread is blocked.</p>
<p>A simple fix is to add a tiny sleep to the start of the run
function:</p>
<pre class="literal-block">
def thread_task(name, n):
time.sleep(0.001) # <---------------------!
for i in range(n): print name, i
for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()
time.sleep(10)
</pre>
<p>Instead of trying to guess how long a <tt class="docutils literal"><span class="pre">time.sleep()</span></tt> delay will be
enough, it's better to use some kind of semaphore mechanism. One idea
is to use the <a class="reference" href="http://www.python.org/doc/lib/module-Queue.html">Queue module</a> to create a queue
object, let each thread append a token to the queue when it finishes,
and let the main thread read as many tokens from the queue as there
are threads.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id17" id="how-do-i-parcel-out-work-among-a-bunch-of-worker-threads" name="how-do-i-parcel-out-work-among-a-bunch-of-worker-threads">3.3 How do I parcel out work among a bunch of worker threads?</a></h2>
<p>Use the <a class="reference" href="http://www.python.org/doc/lib/module-Queue.html">Queue module</a> to create a queue
containing a list of jobs. The <tt class="docutils literal"><span class="pre">Queue</span></tt> class maintains a list of
objects with <tt class="docutils literal"><span class="pre">.put(obj)</span></tt> to add an item to the queue and <tt class="docutils literal"><span class="pre">.get()</span></tt>
to return an item. The class will take care of the locking necessary
to ensure that each job is handed out exactly once.</p>
<p>Here's a trivial example:</p>
<pre class="literal-block">
import threading, Queue, time
# The worker thread gets jobs off the queue. When the queue is empty, it
# assumes there will be no more work and exits.
# (Realistically workers will run until terminated.)
def worker ():
print 'Running worker'
time.sleep(0.1)
while True:
try:
arg = q.get(block=False)
except Queue.Empty:
print 'Worker', threading.currentThread(),
print 'queue empty'
break
else:
print 'Worker', threading.currentThread(),
print 'running with argument', arg
time.sleep(0.5)
# Create queue
q = Queue.Queue()
# Start a pool of 5 workers
for i in range(5):
t = threading.Thread(target=worker, name='worker %i' % (i+1))
t.start()
# Begin adding work to the queue
for i in range(50):
q.put(i)
# Give threads time to run
print 'Main thread sleeping'
time.sleep(5)
</pre>
<p>When run, this will produce the following output:</p>
<blockquote>
Running worker
Running worker
Running worker
Running worker
Running worker
Main thread sleeping
Worker <Thread(worker 1, started)> running with argument 0
Worker <Thread(worker 2, started)> running with argument 1
Worker <Thread(worker 3, started)> running with argument 2
Worker <Thread(worker 4, started)> running with argument 3
Worker <Thread(worker 5, started)> running with argument 4
Worker <Thread(worker 1, started)> running with argument 5
...</blockquote>
<p>Consult the module's documentation for more details; the <tt class="docutils literal"><span class="pre">Queue</span></tt>
class provides a featureful interface.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id18" id="what-kinds-of-global-value-mutation-are-thread-safe" name="what-kinds-of-global-value-mutation-are-thread-safe">3.4 What kinds of global value mutation are thread-safe?</a></h2>
<p>A global interpreter lock (GIL) is used internally to ensure that only
one thread runs in the Python VM at a time. In general, Python offers
to switch among threads only between bytecode instructions; how
frequently it switches can be set via <tt class="docutils literal"><span class="pre">sys.setcheckinterval()</span></tt>.
Each bytecode instruction and therefore all the C implementation code
reached from each instruction is therefore atomic from the point of view of a Python program.</p>
<p>In theory, this means an exact accounting requires an exact
understanding of the PVM bytecode implementation. In practice, it
means that operations on shared variables of builtin data types (ints,
lists, dicts, etc) that "look atomic" really are.</p>
<p>For example, the following operations are all atomic (L, L1, L2 are lists, D, D1, D2 are dicts, x, y
are objects, i, j are ints):</p>
<pre class="literal-block">
L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()
</pre>
<p>These aren't:</p>
<pre class="literal-block">
i = i+1
L.append(L[-1])
L[i] = L[j]
D[x] = D[x] + 1
</pre>
<p>Operations that replace other objects may invoke those other
objects' <tt class="docutils literal"><span class="pre">__del__</span></tt> method when their reference count reaches zero, and
that can affect things. This is especially true for the mass updates
to dictionaries and lists. When in doubt, use a mutex!</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id19" id="can-t-we-get-rid-of-the-global-interpreter-lock" name="can-t-we-get-rid-of-the-global-interpreter-lock">3.5 Can't we get rid of the Global Interpreter Lock?</a></h2>
<p>The Global Interpreter Lock (GIL) is often seen as a hindrance to
Python's deployment on high-end multiprocessor server machines,
because a multi-threaded Python program effectively only uses one CPU,
due to the insistence that (almost) all Python code can only run while
the GIL is held.</p>
<p>Back in the days of Python 1.5, Greg Stein actually implemented a
comprehensive patch set (the "free threading" patches) that removed
the GIL and replaced it with fine-grained locking. Unfortunately, even
on Windows (where locks are very efficient) this ran ordinary Python
code about twice as slow as the interpreter using the GIL. On Linux
the performance loss was even worse because pthread locks aren't as
efficient.</p>
<p>Since then, the idea of getting rid of the GIL has occasionally come
up but nobody has found a way to deal with the expected slowdown, and
users who don't use threads would not be happy if their code ran at
half at the speed. Greg's free threading patch set has not been kept
up-to-date for later Python versions.</p>
<p>This doesn't mean that you can't make good use of Python on multi-CPU
machines! You just have to be creative with dividing the work up
between multiple <em>processes</em> rather than multiple <em>threads</em>.
Judicious use of C extensions will also help; if you use a C extension
to perform a time-consuming task, the extension can release the GIL
while the thread of execution is in the C code and allow other threads
to get some work done.</p>
<p>It has been suggested that the GIL should be a per-interpreter-state
lock rather than truly global; interpreters then wouldn't be able to
share objects. Unfortunately, this isn't likely to happen either. It
would be a tremendous amount of work, because many object
implementations currently have global state. For example, small
integers and short strings are cached; these caches would have to be
moved to the interpreter state. Other object types have their own
free list; these free lists would have to be moved to the interpreter
state. And so on.</p>
<p>And I doubt that it can even be done in finite time, because the same
problem exists for 3rd party extensions. It is likely that 3rd party
extensions are being written at a faster rate than you can convert
them to store all their global state in the interpreter state.</p>
<p>And finally, once you have multiple interpreters not sharing any
state, what have you gained over running each interpreter
in a separate process?</p>
</div>
</div>
<div class="section">
<h1><a class="toc-backref" href="#id20" id="input-and-output" name="input-and-output">4 Input and Output</a></h1>
<div class="section">
<h2><a class="toc-backref" href="#id21" id="how-do-i-delete-a-file-and-other-file-questions" name="how-do-i-delete-a-file-and-other-file-questions">4.1 How do I delete a file? (And other file questions...)</a></h2>
<p>Use <tt class="docutils literal"><span class="pre">os.remove(filename)</span></tt> or <tt class="docutils literal"><span class="pre">os.unlink(filename)</span></tt>; for
documentation, see <a class="reference" href="http://www.python.org/doc/lib/module-posix.html">the POSIX module</a>. The two
functions are identical; <tt class="docutils literal"><span class="pre">unlink()</span></tt> is simply the name of the Unix
system call for this function.</p>
<p>To remove a directory, use <tt class="docutils literal"><span class="pre">os.rmdir()</span></tt>; use <tt class="docutils literal"><span class="pre">os.mkdir()</span></tt> to
create one. <tt class="docutils literal"><span class="pre">os.makedirs(path)</span></tt> will create any intermediate
directories in <tt class="docutils literal"><span class="pre">path</span></tt> that don't exist. <tt class="docutils literal"><span class="pre">os.removedirs(path)</span></tt> will
remove intermediate directories as long as they're empty; if you want
to delete an entire directory tree and its contents, use
<p>To rename a file, use <tt class="docutils literal"><span class="pre">os.rename(old_path,</span> <span class="pre">new_path)</span></tt>.</p>
<p>To truncate a file, open it using <tt class="docutils literal"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">open(filename,</span> <span class="pre">"r+")</span></tt>, and use
<tt class="docutils literal"><span class="pre">f.truncate(offset)</span></tt>; offset defaults to the current seek position.
There's also <tt class="docutils literal"><span class="pre">`os.ftruncate(fd,</span> <span class="pre">offset)</span></tt> for files opened with <tt class="docutils literal"><span class="pre">os.open()</span></tt>,
where <tt class="docutils literal"><span class="pre">fd</span></tt> is the file descriptor (a small integer).</p>
<p>The <tt class="docutils literal"><span class="pre">shutil</span></tt> module also contains a number of functions to work on files
including <tt class="docutils literal"><span class="pre">copyfile</span></tt>, <tt class="docutils literal"><span class="pre">copytree</span></tt>, and <tt class="docutils literal"><span class="pre">rmtree</span></tt>.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id22" id="how-do-i-copy-a-file" name="how-do-i-copy-a-file">4.2 How do I copy a file?</a></h2>
<p>The <tt class="docutils literal"><span class="pre">shutil</span></tt> module contains a <tt class="docutils literal"><span class="pre">copyfile()</span></tt> function. Note that
on MacOS 9 it doesn't copy the resource fork and Finder info.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id23" id="how-do-i-read-or-write-binary-data" name="how-do-i-read-or-write-binary-data">4.3 How do I read (or write) binary data?</a></h2>
<p>or complex data formats, it's best to use <a class="reference" href="http://www.python.org/doc/lib/module-struct.html">the struct module</a>. It allows you
to take a string containing binary data (usually numbers) and convert
it to Python objects; and vice versa.</p>
<p>For example, the following code reads two 2-byte integers
and one 4-byte integer in big-endian format from a file:</p>
<pre class="literal-block">
import struct
f = open(filename, "rb") # Open in binary mode for portability
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)
</pre>
<p>The '>' in the format string forces big-endian data; the letter
'h' reads one "short integer" (2 bytes), and 'l' reads one
"long integer" (4 bytes) from the string.</p>
<p>For data that is more regular (e.g. a homogeneous list of ints or
thefloats), you can also use <a class="reference" href="http://www.python.org/doc/lib/module-array.html">the array module</a>.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id24" id="i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why" name="i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why">4.4 I can't seem to use os.read() on a pipe created with os.popen(); why?</a></h2>
<p><tt class="docutils literal"><span class="pre">os.read()</span></tt> is a low-level function which takes a file descriptor, a
small integer representing the opened file. <tt class="docutils literal"><span class="pre">os.popen()</span></tt> creates a
high-level file object, the same type returned by the builtin
<tt class="docutils literal"><span class="pre">open()</span></tt> function. Thus, to read n bytes from a pipe p created with
<tt class="docutils literal"><span class="pre">os.popen()</span></tt>, you need to use <tt class="docutils literal"><span class="pre">p.read(n)</span></tt>.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id25" id="how-do-i-run-a-subprocess-with-pipes-connected-to-both-input-and-output" name="how-do-i-run-a-subprocess-with-pipes-connected-to-both-input-and-output">4.5 How do I run a subprocess with pipes connected to both input and output?</a></h2>
<p>Use <a class="reference" href="http://www.python.org/doc/lib/module-popen2.html">the popen2 module</a>. For example:</p>
<pre class="literal-block">
import popen2
fromchild, tochild = popen2.popen2("command")
tochild.write("input\n")
tochild.flush()
output = fromchild.readline()
</pre>
<p>Warning: in general it is unwise to do this because you can easily
cause a deadlock where your process is blocked waiting for output from
the child while the child is blocked waiting for input from you. This
can be caused because the parent expects the child to output more text
than it does, or it can be caused by data being stuck in stdio buffers
due to lack of flushing. The Python parent can of course explicitly
flush the data it sends to the child before it reads any output, but
if the child is a naive C program it may have been written to never
explicitly flush its output, even if it is interactive, since flushing
is normally automatic.</p>
<p>Note that a deadlock is also possible if you use <tt class="docutils literal"><span class="pre">popen3</span></tt> to read
stdout and stderr. If one of the two is too large for the internal
buffer (increasing the buffer size does not help) and you <tt class="docutils literal"><span class="pre">read()</span></tt>
the other one first, there is a deadlock, too.</p>
<p>Note on a bug in popen2: unless your program calls <tt class="docutils literal"><span class="pre">wait()</span></tt>
or <tt class="docutils literal"><span class="pre">waitpid()</span></tt>, finished child processes are never removed,
and eventually calls to popen2 will fail because of a limit on
the number of child processes. Calling <tt class="docutils literal"><span class="pre">os.waitpid</span></tt> with the
<tt class="docutils literal"><span class="pre">os.WNOHANG</span></tt> option can prevent this; a good place to insert such
a call would be before calling <tt class="docutils literal"><span class="pre">popen2</span></tt> again.</p>
<p>In many cases, all you really need is to run some data through a
command and get the result back. Unless the amount of data is very
large, the easiest way to do this is to write it to a temporary file
and run the command with that temporary file as input. The <a class="reference" href="http://www.python.org/doc/lib/module-tempfile.html">standard
module tempfile</a>
exports a <tt class="docutils literal"><span class="pre">mktemp()</span></tt> function to generate unique temporary file names.</p>
<pre class="literal-block">
import tempfile
import os
class Popen3:
"""
This is a deadlock-safe version of popen that returns
an object with errorlevel, out (a string) and err (a string).
<p>Note that many interactive programs (e.g. vi) don't work well with
pipes substituted for standard input and output. You will have to use
pseudo ttys ("ptys") instead of pipes. Or you can use a Python
interface to Don Libes' "expect" library. A Python extension that
interfaces to expect is called "expy" and available from
<a class="reference" href="http://expectpy.sourceforge.net">http://expectpy.sourceforge.net</a>. A pure Python solution that works
like expect is ` pexpect <<a class="reference" href="http://pexpect.sourceforge.net">http://pexpect.sourceforge.net</a>>`_.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id26" id="how-do-i-access-the-serial-rs232-port" name="how-do-i-access-the-serial-rs232-port">4.6 How do I access the serial (RS232) port?</a></h2>
<h2><a class="toc-backref" href="#id29" id="what-www-tools-are-there-for-python" name="what-www-tools-are-there-for-python">5.1 What WWW tools are there for Python?</a></h2>
<p>See the chapters titled <a class="reference" href="http://www.python.org/doc/lib/internet.html">"Internet Protocols and Support"</a> and <a class="reference" href="http://www.python.org/doc/lib/netdata.html">"Internet Data
Handling"</a> in the
Library Reference Manual. Python has many modules that will help you
build server-side and client-side web systems.</p>
<p>A summary of available frameworks is maintained by Paul Boddie at
<h2><a class="toc-backref" href="#id30" id="how-can-i-mimic-cgi-form-submission-method-post" name="how-can-i-mimic-cgi-form-submission-method-post">5.2 How can I mimic CGI form submission (METHOD=POST)?</a></h2>
<p>I would like to retrieve web pages that are the result of POSTing a
form. Is there existing code that would let me do this easily?</p>
<p>Yes. Here's a simple example that uses httplib:</p>
<p>Note that in general for URL-encoded POST operations, query
strings must be quoted by using <tt class="docutils literal"><span class="pre">urllib.quote()</span></tt>. For example to send name="Guy
Steele, Jr.":</p>
<pre class="literal-block">
>>> from urllib import quote
>>> x = quote("Guy Steele, Jr.")
>>> x
'Guy%20Steele,%20Jr.'
>>> query_string = "name="+x
>>> query_string
'name=Guy%20Steele,%20Jr.'
</pre>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id31" id="what-module-should-i-use-to-help-with-generating-html" name="what-module-should-i-use-to-help-with-generating-html">5.3 What module should I use to help with generating HTML?</a></h2>
<p>There are many different modules available:</p>
<ul class="simple">
<li>HTMLgen is a class library of objects corresponding to all the HTML
3.2 markup tags. It's used when you are writing in Python and wish
to synthesize HTML pages for generating a web or for CGI forms, etc.</li>
<li>DocumentTemplate and Zope Page Templates are two different systems that are
part of Zope.</li>
<li>Quixote's PTL uses Python syntax to assemble strings of text.</li>
</ul>
<p>Consult the <a class="reference" href="http://www.python.org/topics/web/">Web Programming topic guide</a> for more links.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id32" id="how-do-i-send-mail-from-a-python-script" name="how-do-i-send-mail-from-a-python-script">5.4 How do I send mail from a Python script?</a></h2>
<p>Use <a class="reference" href="http://www.python.org/doc/lib/module-smtplib.html">the standard library module smtplib</a>.</p>
<p>Here's a very simple interactive mail sender that uses it. This
method will work on any host that supports an SMTP listener.</p>
<pre class="literal-block">
import sys, smtplib
fromaddr = raw_input("From: ")
toaddrs = raw_input("To: ").split(',')
print "Enter message, end with ^D:"
msg = ''
while 1:
line = sys.stdin.readline()
if not line:
break
msg = msg + line
# The actual mail send
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</pre>
<p>A Unix-only alternative uses sendmail. The location of the
sendmail program varies between systems; sometimes it is
p.write("\n") # blank line separating headers from body
p.write("Some text\n")
p.write("some more text\n")
sts = p.close()
if sts != 0:
print "Sendmail exit status", sts
</pre>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id33" id="how-do-i-avoid-blocking-in-the-connect-method-of-a-socket" name="how-do-i-avoid-blocking-in-the-connect-method-of-a-socket">5.5 How do I avoid blocking in the connect() method of a socket?</a></h2>
<p>The select module is commonly used to help with asynchronous
I/O on sockets.</p>
<p>To prevent the TCP connect from blocking, you can set the socket to
non-blocking mode. Then when you do the <tt class="docutils literal"><span class="pre">connect()</span></tt>, you will
either connect immediately (unlikely) or get an exception that
contains the error number as <tt class="docutils literal"><span class="pre">.errno</span></tt>. <tt class="docutils literal"><span class="pre">errno.EINPROGRESS</span></tt>
indicates that the connection is in progress, but hasn't finished yet.
Different OSes will return different values, so you're going to have
to check what's returned on your system.</p>
<p>You can use the <tt class="docutils literal"><span class="pre">connect_ex()</span></tt> method to avoid creating an
exception. It will just return the errno value. To poll, you can
call <tt class="docutils literal"><span class="pre">connect_ex()</span></tt> again later -- 0 or <tt class="docutils literal"><span class="pre">errno.EISCONN</span></tt> indicate
that you're connected -- or you can pass this socket to select to
<h2><a class="toc-backref" href="#id35" id="are-there-any-interfaces-to-database-packages-in-python" name="are-there-any-interfaces-to-database-packages-in-python">6.1 Are there any interfaces to database packages in Python?</a></h2>
<p>Yes.</p>
<p>Python 2.3 includes the <tt class="docutils literal"><span class="pre">bsddb</span></tt> package which provides an interface
to the <a class="reference" href="http://www.python.org/doc/lib/module-bsddb.html">BerkeleyDB</a> library.
Interfaces to disk-based hashes such as <a class="reference" href="http://www.python.org/doc/lib/module-dbm.html">DBM</a> and <a class="reference" href="http://www.python.org/doc/lib/module-gdbm.html">GDBM</a> are also included
with standard Python.</p>
<p>Support for most relational databases is available. See the <a class="reference" href="http://www.python.org/topics/database">Database
Topic Guide</a> for details.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id36" id="how-do-you-implement-persistent-objects-in-python" name="how-do-you-implement-persistent-objects-in-python">6.2 How do you implement persistent objects in Python?</a></h2>
<p>The <a class="reference" href="http://www.python.org/doc/lib/module-pickle.html">pickle library module</a> solves this in a
very general way (though you still can't store things like open files,
sockets or windows), and the <a class="reference" href="http://www.python.org/doc/lib/module-shelve.html">shelve library module</a> uses pickle and
(g)dbm to create persistent mappings containing arbitrary Python
<p>A more awkward way of doing things is to use pickle's little sister,
marshal. <a class="reference" href="http://www.python.org/doc/lib/module-marshal.html">The marshal module</a> provides very
fast ways to store noncircular basic Python types to files and
strings, and back again. Although marshal does not do fancy things
like store instances or handle shared references properly, it does run
extremely fast. For example loading a half megabyte of data may take
less than a third of a second. This often beats doing something more
complex and general such as using gdbm with pickle/shelve.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id37" id="why-is-cpickle-so-slow" name="why-is-cpickle-so-slow">6.3 Why is cPickle so slow?</a></h2>
<p>The default format used by the pickle module is a slow one that
results in readable pickles. Making it the default, but it would
break backward compatibility:</p>
<pre class="literal-block">
largeString = 'z' * (100 * 1024)
myPickle = cPickle.dumps(largeString, protocol=1)
</pre>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id38" id="if-my-program-crashes-with-a-bsddb-or-anydbm-database-open-it-gets-corrupted-how-come" name="if-my-program-crashes-with-a-bsddb-or-anydbm-database-open-it-gets-corrupted-how-come">6.4 If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?</a></h2>
<p>Databases opened for write access with the bsddb module (and often by
the anydbm module, since it will preferentially use bsddb) must
explicitly be closed using the <tt class="docutils literal"><span class="pre">.close()</span></tt> method of the database. The
underlying library caches database contents which need to be
converted to on-disk form and written.</p>
<p>If you have initialized a new bsddb database but not written anything to
it before the program crashes, you will often wind up with a zero-length
file and encounter an exception the next time the file is opened.</p>
</div>
<div class="section">
<h2><a class="toc-backref" href="#id39" id="i-tried-to-open-berkeley-db-file-but-bsddb-produces-bsddb-error-22-invalid-argument-help-how-can-i-restore-my-data" name="i-tried-to-open-berkeley-db-file-but-bsddb-produces-bsddb-error-22-invalid-argument-help-how-can-i-restore-my-data">6.5 I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data?</a></h2>
<p>Don't panic! Your data is probably intact. The most frequent cause
for the error is that you tried to open an earlier Berkeley DB file
with a later version of the Berkeley DB library.</p>
<p>Many Linux systems now have all three versions of Berkeley DB
available. If you are migrating from version 1 to a newer version use
db_dump185 to dump a plain text version of the database.
If you are migrating from version 2 to version 3 use db2_dump to create
a plain text version of the database. In either case, use db_load to
create a new native database for the latest version installed on your
computer. If you have version 3 of Berkeley DB installed, you should
be able to use db2_load to create a native version 2 database.</p>
<p>You should move away from Berkeley DB version 1 files because
the hash file code contains known bugs that can corrupt your data.</p>
</div>
</div>
<div class="section">
<h1><a class="toc-backref" href="#id40" id="mathematics-and-numerics" name="mathematics-and-numerics">7 Mathematics and Numerics</a></h1>
<div class="section">
<h2><a class="toc-backref" href="#id41" id="how-do-i-generate-random-numbers-in-python" name="how-do-i-generate-random-numbers-in-python">7.1 How do I generate random numbers in Python?</a></h2>
<p>The <a class="reference" href="http://www.python.org/doc/lib/module-random.html">standard module random</a> implements a random number
generator. Usage is simple:</p>
<pre class="literal-block">
import random
random.random()
</pre>
<p>This returns a random floating point number in the range [0, 1).</p>
<p>There are also many other specialized generators in this module, such
as:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">randrange(a,</span> <span class="pre">b)</span></tt> chooses an integer in the range [a, b).</li>
<li><tt class="docutils literal"><span class="pre">uniform(a,</span> <span class="pre">b)</span></tt> chooses a floating point number in the range [a, b).</li>
<li><tt class="docutils literal"><span class="pre">normalvariate(mean,</span> <span class="pre">sdev)</span></tt> samples the normal (Gaussian) distribution.</li>
</ul>
<p>Some higher-level functions operate on sequences directly, such as:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">choice(S)</span></tt> chooses random element from a given sequence</li>
<li><tt class="docutils literal"><span class="pre">shuffle(L)</span></tt> shuffles a list in-place, i.e. permutes it randomly</li>
</ul>
<p>There's also a <tt class="docutils literal"><span class="pre">Random</span></tt> class you can instantiate
to create independent multiple random number generators.</p>