Library and Extension FAQ¶
Contents
General Library Questions¶
How do I find a module or application to perform task X?¶
Checkthe Library Reference to see if there’s a relevantstandard library module. (Eventually you’ll learn what’s in the standardlibrary and will be able to skip this step.)
For third-party packages, search thePython Package Index or tryGoogle oranother Web search engine. Searching for “Python” plus a keyword or two foryour topic of interest will usually find something helpful.
Where is the math.py (socket.py, regex.py, etc.) source file?¶
If you can’t find a source file for a module it may be a built-in ordynamically 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 likemathmodule.c
, somewhere in a C source directory (not on the Python Path).
There are (at least) three kinds of modules in Python:
modules written in Python (.py);
modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
modules written in C and linked with the interpreter; to get a list of these,type:
importsysprintsys.builtin_module_names
How do I make a Python script executable on Unix?¶
You need to do two things: the script file’s mode must be executable and thefirst line must begin with#!
followed by the path of the Pythoninterpreter.
The first is done by executingchmod+xscriptfile
or perhapschmod755scriptfile
.
The second can be done in a number of ways. The most straightforward way is towrite
#!/usr/local/bin/python
as the very first line of your file, using the pathname for where the Pythoninterpreter is installed on your platform.
If you would like the script to be independent of where the Python interpreterlives, you can use theenv program. Almost all Unix variants supportthe following, assuming the Python interpreter is in a directory on the user’sPATH
:
#!/usr/bin/env python
Don’t do this for CGI scripts. ThePATH
variable for CGI scripts isoften very minimal, so you need to use the actual absolute pathname of theinterpreter.
Occasionally, a user’s environment is so full that the/usr/bin/envprogram fails; or there’s no env program at all. In that case, you can try thefollowing hack (due to Alex Rezinsky):
#! /bin/sh""":"exec python $0 ${1+"$@"}"""
The minor disadvantage is that this defines the script’s __doc__ string.However, you can fix that by adding
__doc__="""...Whatever..."""
Is there a curses/termcap package for Python?¶
For Unix variants the standard Python source distribution comes with a cursesmodule in theModules subdirectory, though it’s not compiled by default.(Note that this is not available in the Windows distribution – there is nocurses module for Windows.)
Thecurses
module supports basic curses features as well as many additionalfunctions from ncurses and SYSV curses such as colour, alternative character setsupport, pads, and mouse support. This means the module isn’t compatible withoperating systems that only have BSD curses, but there don’t seem to be anycurrently maintained OSes that fall into this category.
For Windows: usethe consolelib module.
Is there an equivalent to C’s onexit() in Python?¶
Theatexit
module provides a register function that is similar to C’sonexit()
.
Why don’t my signal handlers work?¶
The most common problem is that the signal handler is declared with the wrongargument list. It is called as
handler(signum,frame)
so it should be declared with two arguments:
defhandler(signum,frame):...
Common tasks¶
How do I test a Python program or component?¶
Python comes with two testing frameworks. Thedoctest
module findsexamples in the docstrings for a module and runs them, comparing the output withthe expected output given in the docstring.
Theunittest
module is a fancier testing framework modelled on Java andSmalltalk testing frameworks.
To make testing easier, you should use good modular design in your program.Your program should have almost all functionalityencapsulated in either functions or class methods – and this sometimes has thesurprising and delightful effect of making the program run faster (because localvariable accesses are faster than global accesses). Furthermore the programshould avoid depending on mutating global variables, since this makes testingmuch more difficult to do.
The “global main logic” of your program may be as simple as
if__name__=="__main__":main_logic()
at the bottom of the main module of your program.
Once your program is organized as a tractable collection of functions and classbehaviours you should write test functions that exercise the behaviours. A testsuite that automates a sequence of tests can be associated with each module.This sounds like a lot of work, but since Python is so terse and flexible it’ssurprisingly easy. You can make coding much more pleasant and fun by writingyour test functions in parallel with the “production code”, since this makes iteasy to find bugs and even design flaws earlier.
“Support modules” that are not intended to be the main module of a program mayinclude a self-test of the module.
if__name__=="__main__":self_test()
Even programs that interact with complex external interfaces may be tested whenthe external interfaces are unavailable by using “fake” interfaces implementedin Python.
How do I create documentation from doc strings?¶
Thepydoc
module can create HTML from the doc strings in your Pythonsource code. An alternative for creating API documentation purely fromdocstrings isepydoc.Sphinx can also include docstring content.
How do I get a single keypress at a time?¶
For Unix variants there are several solutions. It’s straightforward to do thisusing curses, but curses is a fairly large module to learn. Here’s a solutionwithout curses:
importtermios,fcntl,sys,osfd=sys.stdin.fileno()oldterm=termios.tcgetattr(fd)newattr=termios.tcgetattr(fd)newattr[3]=newattr[3]&~termios.ICANON&~termios.ECHOtermios.tcsetattr(fd,termios.TCSANOW,newattr)oldflags=fcntl.fcntl(fd,fcntl.F_GETFL)fcntl.fcntl(fd,fcntl.F_SETFL,oldflags|os.O_NONBLOCK)try:while1:try:c=sys.stdin.read(1)print"Got character",repr(c)exceptIOError:passfinally:termios.tcsetattr(fd,termios.TCSAFLUSH,oldterm)fcntl.fcntl(fd,fcntl.F_SETFL,oldflags)
You need thetermios
and thefcntl
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.
termios.tcsetattr()
turns off stdin’s echoing and disables canonical mode.fcntl.fnctl()
is used to obtain stdin’s file descriptor flags and modifythem for non-blocking mode. Since reading stdin when it is empty results in anIOError
, this error is caught and ignored.
Threads¶
How do I program using threads?¶
Be sure to use thethreading
module and not thethread
module.Thethreading
module builds convenient abstractions on top of thelow-level primitives provided by thethread
module.
Aahz has a set of slides from his threading tutorial that are helpful; seehttp://www.pythoncraft.com/OSCON2001/.
None of my threads seem to run: why?¶
As soon as the main thread exits, all threads are killed. Your main thread isrunning too quickly, giving the threads no time to do any work.
A simple fix is to add a sleep to the end of the program that’s long enough forall the threads to finish:
importthreading,timedefthread_task(name,n):foriinrange(n):printname,iforiinrange(10):T=threading.Thread(target=thread_task,args=(str(i),i))T.start()time.sleep(10)# <----------------------------!
But now (on many platforms) the threads don’t run in parallel, but appear to runsequentially, one at a time! The reason is that the OS thread scheduler doesn’tstart a new thread until the previous thread is blocked.
A simple fix is to add a tiny sleep to the start of the run function:
defthread_task(name,n):time.sleep(0.001)# <---------------------!foriinrange(n):printname,iforiinrange(10):T=threading.Thread(target=thread_task,args=(str(i),i))T.start()time.sleep(10)
Instead of trying to guess a good delay value fortime.sleep()
,it’s better to use some kind of semaphore mechanism. One idea is to use theQueue
module to create a queue object, let each thread append a token tothe queue when it finishes, and let the main thread read as many tokens from thequeue as there are threads.
How do I parcel out work among a bunch of worker threads?¶
Use theQueue
module to create a queue containing a list of jobs. TheQueue
class maintains a list of objects and has a.put(obj)
method that adds items to the queue and a.get()
method to return them.The class will take care of the locking necessary to ensure that each job ishanded out exactly once.
Here’s a trivial example:
importthreading,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.)defworker():print'Running worker'time.sleep(0.1)whileTrue:try:arg=q.get(block=False)exceptQueue.Empty:print'Worker',threading.currentThread(),print'queue empty'breakelse:print'Worker',threading.currentThread(),print'running with argument',argtime.sleep(0.5)# Create queueq=Queue.Queue()# Start a pool of 5 workersforiinrange(5):t=threading.Thread(target=worker,name='worker%i'%(i+1))t.start()# Begin adding work to the queueforiinrange(50):q.put(i)# Give threads time to runprint'Main thread sleeping'time.sleep(5)
When run, this will produce the following output:
Running workerRunning workerRunning workerRunning workerRunning workerMain thread sleepingWorker <Thread(worker 1, started)> running with argument 0Worker <Thread(worker 2, started)> running with argument 1Worker <Thread(worker 3, started)> running with argument 2Worker <Thread(worker 4, started)> running with argument 3Worker <Thread(worker 5, started)> running with argument 4Worker <Thread(worker 1, started)> running with argument 5...
Consult the module’s documentation for more details; theQueue
class provides a featureful interface.
What kinds of global value mutation are thread-safe?¶
Aglobal interpreter lock (GIL) is used internally to ensure that onlyone thread runs in the Python VM at a time. In general, Python offers to switchamong threads only between bytecode instructions; how frequently it switches canbe set viasys.setcheckinterval()
. Each bytecode instruction andtherefore all the C implementation code reached from each instruction istherefore atomic from the point of view of a Python program.
In theory, this means an exact accounting requires an exact understanding of thePVM bytecode implementation. In practice, it means that operations on sharedvariables of built-in data types (ints, lists, dicts, etc) that “look atomic”really are.
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):
L.append(x)L1.extend(L2)x=L[i]x=L.pop()L1[i:j]=L2L.sort()x=yx.field=yD[x]=yD1.update(D2)D.keys()
These aren’t:
i=i+1L.append(L[-1])L[i]=L[j]D[x]=D[x]+1
Operations that replace other objects may invoke those other objects’__del__()
method when their reference count reaches zero, and that canaffect things. This is especially true for the mass updates to dictionaries andlists. When in doubt, use a mutex!
Can’t we get rid of the Global Interpreter Lock?¶
Theglobal interpreter lock (GIL) is often seen as a hindrance to Python’sdeployment on high-end multiprocessor server machines, because a multi-threadedPython program effectively only uses one CPU, due to the insistence that(almost) all Python code can only run while the GIL is held.
Back in the days of Python 1.5, Greg Stein actually implemented a comprehensivepatch set (the “free threading” patches) that removed the GIL and replaced itwith fine-grained locking. Unfortunately, even on Windows (where locks are veryefficient) this ran ordinary Python code about twice as slow as the interpreterusing the GIL. On Linux the performance loss was even worse because pthreadlocks aren’t as efficient.
Since then, the idea of getting rid of the GIL has occasionally come up butnobody has found a way to deal with the expected slowdown, and users who don’tuse threads would not be happy if their code ran at half the speed. Greg’sfree threading patch set has not been kept up-to-date for later Python versions.
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 multipleprocesses rather than multiplethreads. Judicious use of C extensions willalso help; if you use a C extension to perform a time-consuming task, theextension can release the GIL while the thread of execution is in the C code andallow other threads to get some work done.
It has been suggested that the GIL should be a per-interpreter-state lock ratherthan truly global; interpreters then wouldn’t be able to share objects.Unfortunately, this isn’t likely to happen either. It would be a tremendousamount of work, because many object implementations currently have global state.For example, small integers and short strings are cached; these caches wouldhave to be moved to the interpreter state. Other object types have their ownfree list; these free lists would have to be moved to the interpreter state.And so on.
And I doubt that it can even be done in finite time, because the same problemexists for 3rd party extensions. It is likely that 3rd party extensions arebeing written at a faster rate than you can convert them to store all theirglobal state in the interpreter state.
And finally, once you have multiple interpreters not sharing any state, whathave you gained over running each interpreter in a separate process?
Input and Output¶
How do I delete a file? (And other file questions…)¶
Useos.remove(filename)
oros.unlink(filename)
; for documentation, seetheos
module. The two functions are identical;unlink()
is simplythe name of the Unix system call for this function.
To remove a directory, useos.rmdir()
; useos.mkdir()
to create one.os.makedirs(path)
will create any intermediate directories inpath
thatdon’t exist.os.removedirs(path)
will remove intermediate directories aslong as they’re empty; if you want to delete an entire directory tree and itscontents, useshutil.rmtree()
.
To rename a file, useos.rename(old_path,new_path)
.
To truncate a file, open it usingf=open(filename,"r+")
, and usef.truncate(offset)
; offset defaults to the current seek position. There’salsoos.ftruncate(fd,offset)
for files opened withos.open()
, wherefd is the file descriptor (a small integer).
Theshutil
module also contains a number of functions to work on filesincludingcopyfile()
,copytree()
, andrmtree()
.
How do I copy a file?¶
Theshutil
module contains acopyfile()
function. Notethat on MacOS 9 it doesn’t copy the resource fork and Finder info.
How do I read (or write) binary data?¶
To read or write complex binary data formats, it’s best to use thestruct
module. It allows you to take a string containing binary data (usually numbers)and convert it to Python objects; and vice versa.
For example, the following code reads two 2-byte integers and one 4-byte integerin big-endian format from a file:
importstructf=open(filename,"rb")# Open in binary mode for portabilitys=f.read(8)x,y,z=struct.unpack(">hhl",s)
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 thestring.
For data that is more regular (e.g. a homogeneous list of ints or floats),you can also use thearray
module.
I can’t seem to use os.read() on a pipe created with os.popen(); why?¶
os.read()
is a low-level function which takes a file descriptor, a smallinteger representing the opened file.os.popen()
creates a high-levelfile object, the same type returned by the built-inopen()
function.Thus, to readn bytes from a pipep created withos.popen()
, you need tousep.read(n)
.
How do I run a subprocess with pipes connected to both input and output?¶
Use thepopen2
module. For example:
importpopen2fromchild,tochild=popen2.popen2("command")tochild.write("input\n")tochild.flush()output=fromchild.readline()
Warning: in general it is unwise to do this because you can easily cause adeadlock where your process is blocked waiting for output from the child whilethe child is blocked waiting for input from you. This can be caused by theparent expecting the child to output more text than it does or by data beingstuck in stdio buffers due to lack of flushing. The Python parentcan of course explicitly flush the data it sends to the child before it readsany output, but if the child is a naive C program it may have been written tonever explicitly flush its output, even if it is interactive, since flushing isnormally automatic.
Note that a deadlock is also possible if you usepopen3()
to read stdoutand stderr. If one of the two is too large for the internal buffer (increasingthe buffer size does not help) and youread()
the other one first, there isa deadlock, too.
Note on a bug in popen2: unless your program callswait()
orwaitpid()
,finished child processes are never removed, and eventually calls to popen2 willfail because of a limit on the number of child processes. Callingos.waitpid()
with theos.WNOHANG
option can prevent this; a goodplace to insert such a call would be before callingpopen2
again.
In many cases, all you really need is to run some data through a command and getthe result back. Unless the amount of data is very large, the easiest way to dothis is to write it to a temporary file and run the command with that temporaryfile as input. The standard moduletempfile
exports amktemp()
function to generate unique temporary file names.
importtempfileimportosclassPopen3:""" This is a deadlock-safe version of popen that returns an object with errorlevel, out (a string) and err (a string). (capturestderr may not work under windows.) Example: print Popen3('grep spam','\n\nhere spam\n\n').out """def__init__(self,command,input=None,capturestderr=None):outfile=tempfile.mktemp()command="(%s ) >%s"%(command,outfile)ifinput:infile=tempfile.mktemp()open(infile,"w").write(input)command=command+" <"+infileifcapturestderr:errfile=tempfile.mktemp()command=command+" 2>"+errfileself.errorlevel=os.system(command)>>8self.out=open(outfile,"r").read()os.remove(outfile)ifinput:os.remove(infile)ifcapturestderr:self.err=open(errfile,"r").read()os.remove(errfile)
Note that many interactive programs (e.g. vi) don’t work well with pipessubstituted 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 fromhttp://expectpy.sourceforge.net. A pure Python solution thatworks like expect ispexpect.
How do I access the serial (RS232) port?¶
For Win32, POSIX (Linux, BSD, etc.), Jython:
For Unix, see a Usenet post by Mitch Chapman:
Why doesn’t closing sys.stdout (stdin, stderr) really close it?¶
Python file objects are a high-level layer of abstraction on top of C streams,which in turn are a medium-level layer of abstraction on top of (among otherthings) low-level C file descriptors.
For most file objects you create in Python via the built-infile
constructor,f.close()
marks the Python file object as being closed fromPython’s point of view, and also arranges to close the underlying C stream.This also happens automatically inf
’s destructor, whenf
becomesgarbage.
But stdin, stdout and stderr are treated specially by Python, because of thespecial status also given to them by C. Runningsys.stdout.close()
marksthe Python-level file object as being closed, but doesnot close theassociated C stream.
To close the underlying C stream for one of these three, you should first besure that’s what you really want to do (e.g., you may confuse extension modulestrying to do I/O). If it is, use os.close:
os.close(0)# close C's stdin streamos.close(1)# close C's stdout streamos.close(2)# close C's stderr stream
Network/Internet Programming¶
What WWW tools are there for Python?¶
See the chapters titledInternet Protocols and Support andInternet Data Handling in the LibraryReference Manual. Python has many modules that will help you build server-sideand client-side web systems.
A summary of available frameworks is maintained by Paul Boddie athttps://wiki.python.org/moin/WebProgramming.
Cameron Laird maintains a useful set of pages about Python web technologies athttp://phaseit.net/claird/comp.lang.python/web_python.
How can I mimic CGI form submission (METHOD=POST)?¶
I would like to retrieve web pages that are the result of POSTing a form. Isthere existing code that would let me do this easily?
Yes. Here’s a simple example that uses httplib:
#!/usr/local/bin/pythonimporthttplib,sys,time# build the query stringqs="First=Josephine&MI=Q&Last=Public"# connect and send the server a pathhttpobj=httplib.HTTP('www.some-server.out-there',80)httpobj.putrequest('POST','/cgi-bin/some-cgi-script')# now generate the rest of the HTTP headers...httpobj.putheader('Accept','*/*')httpobj.putheader('Connection','Keep-Alive')httpobj.putheader('Content-type','application/x-www-form-urlencoded')httpobj.putheader('Content-length','%d'%len(qs))httpobj.endheaders()httpobj.send(qs)# find out what the server said in response...reply,msg,hdrs=httpobj.getreply()ifreply!=200:sys.stdout.write(httpobj.getfile().read())
Note that in general for percent-encoded POST operations, query strings must bequoted usingurllib.urlencode()
. For example, to sendname=GuySteele,Jr.
:
>>>importurllib>>>urllib.urlencode({'name':'Guy Steele, Jr.'})'name=Guy+Steele%2C+Jr.'
What module should I use to help with generating HTML?¶
You can find a collection of useful links on theWeb Programming wiki page.
How do I send mail from a Python script?¶
Use the standard library modulesmtplib
.
Here’s a very simple interactive mail sender that uses it. This method willwork on any host that supports an SMTP listener.
importsys,smtplibfromaddr=raw_input("From: ")toaddrs=raw_input("To: ").split(',')print"Enter message, end with ^D:"msg=''whileTrue:line=sys.stdin.readline()ifnotline:breakmsg+=line# The actual mail sendserver=smtplib.SMTP('localhost')server.sendmail(fromaddr,toaddrs,msg)server.quit()
A Unix-only alternative uses sendmail. The location of the sendmail programvaries between systems; sometimes it is/usr/lib/sendmail
, sometimes/usr/sbin/sendmail
. The sendmail manual page will help you out. Here’ssome sample code:
importosSENDMAIL="/usr/sbin/sendmail"# sendmail locationp=os.popen("%s -t -i"%SENDMAIL,"w")p.write("To: receiver@example.com\n")p.write("Subject: test\n")p.write("\n")# blank line separating headers from bodyp.write("Some text\n")p.write("some more text\n")sts=p.close()ifsts!=0:print"Sendmail exit status",sts
How do I avoid blocking in the connect() method of a socket?¶
The select module is commonly used to help with asynchronous I/O on sockets.
To prevent the TCP connect from blocking, you can set the socket to non-blockingmode. Then when you do theconnect()
, you will either connect immediately(unlikely) or get an exception that contains the error number as.errno
.errno.EINPROGRESS
indicates that the connection is in progress, but hasn’tfinished yet. Different OSes will return different values, so you’re going tohave to check what’s returned on your system.
You can use theconnect_ex()
method to avoid creating an exception. It willjust return the errno value. To poll, you can callconnect_ex()
again later– 0 orerrno.EISCONN
indicate that you’re connected – or you can pass thissocket to select to check if it’s writable.
Databases¶
Are there any interfaces to database packages in Python?¶
Yes.
Python 2.3 includes thebsddb
package which provides an interface to theBerkeleyDB library. Interfaces to disk-based hashes such asDBM
andGDBM
are also included with standard Python.
Support for most relational databases is available. See theDatabaseProgramming wiki page for details.
How do you implement persistent objects in Python?¶
Thepickle
library module solves this in a very general way (though youstill can’t store things like open files, sockets or windows), and theshelve
library module uses pickle and (g)dbm to create persistentmappings containing arbitrary Python objects. For better performance, you canuse thecPickle
module.
A more awkward way of doing things is to use pickle’s little sister, marshal.Themarshal
module provides very fast ways to store noncircular basicPython types to files and strings, and back again. Although marshal does not dofancy things like store instances or handle shared references properly, it doesrun extremely fast. For example, loading a half megabyte of data may take lessthan a third of a second. This often beats doing something more complex andgeneral such as using gdbm with pickle/shelve.
Why is cPickle so slow?¶
By defaultpickle
uses a relatively old and slow format for backwardcompatibility. You can however specify other protocol versions that arefaster:
largeString='z'*(100*1024)myPickle=cPickle.dumps(largeString,protocol=1)
If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?¶
Databases opened for write access with the bsddb module (and often by the anydbmmodule, since it will preferentially use bsddb) must explicitly be closed usingthe.close()
method of the database. The underlying library caches databasecontents which need to be converted to on-disk form and written.
If you have initialized a new bsddb database but not written anything to itbefore the program crashes, you will often wind up with a zero-length file andencounter an exception the next time the file is opened.
I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, ‘Invalid argument’). Help! How can I restore my data?¶
Don’t panic! Your data is probably intact. The most frequent cause for the erroris that you tried to open an earlier Berkeley DB file with a later version ofthe Berkeley DB library.
Many Linux systems now have all three versions of Berkeley DB available. If youare migrating from version 1 to a newer version use db_dump185 to dump a plaintext version of the database. If you are migrating from version 2 to version 3use 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 onyour computer. If you have version 3 of Berkeley DB installed, you should beable to use db2_load to create a native version 2 database.
You should move away from Berkeley DB version 1 files because the hash file codecontains known bugs that can corrupt your data.
Mathematics and Numerics¶
How do I generate random numbers in Python?¶
The standard modulerandom
implements a random number generator. Usageis simple:
importrandomrandom.random()
This returns a random floating point number in the range [0, 1).
There are also many other specialized generators in this module, such as:
randrange(a,b)
chooses an integer in the range [a, b).uniform(a,b)
chooses a floating point number in the range [a, b).normalvariate(mean,sdev)
samples the normal (Gaussian) distribution.
Some higher-level functions operate on sequences directly, such as:
choice(S)
chooses random element from a given sequenceshuffle(L)
shuffles a list in-place, i.e. permutes it randomly
There’s also aRandom
class you can instantiate to create independentmultiple random number generators.