Library and Extension FAQ¶
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:
importsysprint(sys.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""":"execpython$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.
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 parameters:
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 function and classbehaviours, you should write test functions that exercise the behaviours. Atest suite 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.
Threads¶
How do I program using threads?¶
Be sure to use thethreading
module and not the_thread
module.Thethreading
module builds convenient abstractions on top of thelow-level primitives provided by the_thread
module.
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):print(name,i)foriinrange(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):print(name,i)foriinrange(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?¶
The easiest way is to use theconcurrent.futures
module,especially theThreadPoolExecutor
class.
Or, if you want fine control over the dispatching algorithm, you can writeyour own logic manually. Use thequeue
module to create a queuecontaining a list of jobs. TheQueue
class maintains alist of objects and has a.put(obj)
method that adds items to the queue anda.get()
method to return them. The class will take care of the lockingnecessary to ensure that each job is handed 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.current_thread(),end=' ')print('queue empty')breakelse:print('Worker',threading.current_thread(),end=' ')print('running with argument',arg)time.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 130283832797456)> running with argument 0Worker <Thread(worker 2, started 130283824404752)> running with argument 1Worker <Thread(worker 3, started 130283816012048)> running with argument 2Worker <Thread(worker 4, started 130283807619344)> running with argument 3Worker <Thread(worker 5, started 130283799226640)> running with argument 4Worker <Thread(worker 1, started 130283832797456)> 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 only onethread 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.setswitchinterval()
. 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. Adam Olsen recently did a similar experimentin hispython-safethreadproject. Unfortunately, both experiments exhibited a sharp drop in single-threadperformance (at least 30% slower), due to the amount of fine-grained lockingnecessary to compensate for the removal of the GIL.
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. TheProcessPoolExecutor
class in the newconcurrent.futures
module provides an easy way of doing so; themultiprocessing
module provides a lower-level API in case you wantmore control over dispatching of tasks.
Judicious use of C extensions will also help; if you use a C extension toperform a time-consuming task, the extension can release the GIL while thethread of execution is in the C code and allow other threads to get some workdone. Some standard library modules such aszlib
andhashlib
already do this.
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,"rb+")
, 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.Note that on Windows NTFS volumes, it does not copyalternate data streamsnorresource forkson macOS HFS+ volumes, though both are now rarely used.It also doesn’t copy file permissions and metadata, though usingshutil.copy2()
instead will preserve most (though not all) of it.
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:
importstructwithopen(filename,"rb")asf:s=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 access the serial (RS232) port?¶
For Win32, OSX, Linux, BSD, Jython, IronPython:
For Unix, see a Usenet post by Mitch Chapman:
Why doesn’t closing sys.stdout (stdin, stderr) really close it?¶
Pythonfile objects are a high-level layer ofabstraction on low-level C file descriptors.
For most file objects you create in Python via the built-inopen()
function,f.close()
marks the Python file object as being closed fromPython’s point of view, and also arranges to close the underlying C filedescriptor. This also happens automatically inf
’s destructor, whenf
becomes garbage.
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 file descriptor.
To close the underlying C file descriptor for one of these three, you shouldfirst be sure that’s what you really want to do (e.g., you may confuseextension modules trying to do I/O). If it is, useos.close()
:
os.close(stdin.fileno())os.close(stdout.fileno())os.close(stderr.fileno())
Or you can use the numeric constants 0, 1 and 2, respectively.
Network/Internet Programming¶
What WWW tools are there for Python?¶
See the chapters titledΠρωτόκολλα Internet και Υποστήριξη 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 athttps://web.archive.org/web/20210224183619/http://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 usesurllib.request
:
#!/usr/local/bin/pythonimporturllib.request# build the query stringqs="First=Josephine&MI=Q&Last=Public"# connect and send the server a pathreq=urllib.request.urlopen('http://www.some-server.out-there''/cgi-bin/some-cgi-script',data=qs)withreq:msg,hdrs=req.read(),req.info()
Note that in general for percent-encoded POST operations, query strings must bequoted usingurllib.parse.urlencode()
. For example, to sendname=GuySteele,Jr.
:
>>>importurllib.parse>>>urllib.parse.urlencode({'name':'Guy Steele, Jr.'})'name=Guy+Steele%2C+Jr.'
Δείτε επίσης
HOWTO Fetch Internet Resources Using The urllib Package for extensive examples.
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=input("From: ")toaddrs=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?¶
Theselect
module is commonly used to help with asynchronous I/O onsockets.
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()
methodto avoid creating an exception.It will just 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 toselect.select()
to check if it’s writable.
Databases¶
Are there any interfaces to database packages in Python?¶
Yes.
Interfaces to disk-based hashes such asDBM
andGDBM
are also included with standard Python. There is also thesqlite3
module, which provides a lightweight disk-based relationaldatabase.
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.
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 a random element from a given sequence.shuffle(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.