blob: 6a2682fc381c0181385a6516ed01525b60b16337 [file] [log] [blame]
Georg Brandld7413152009-10-11 21:25:26 +00001:tocdepth: 2
2
3=========================
4Library and Extension FAQ
5=========================
6
7.. contents::
8
9General Library Questions
10=========================
11
12How do I find a module or application to perform task X?
13--------------------------------------------------------
14
15Check :ref:`the Library Reference <library-index>` to see if there's a relevant
16standard library module. (Eventually you'll learn what's in the standard
Ezio Melottib35480e2012-05-13 20:14:04 +030017library and will be able to skip this step.)
Georg Brandld7413152009-10-11 21:25:26 +000018
Georg Brandl495f7b52009-10-27 15:28:25 +000019For third-party packages, search the `Python Package Index
20<http://pypi.python.org/pypi>`_ or try `Google <http://www.google.com>`_ or
21another Web search engine. Searching for "Python" plus a keyword or two for
22your topic of interest will usually find something helpful.
Georg Brandld7413152009-10-11 21:25:26 +000023
24
25Where is the math.py (socket.py, regex.py, etc.) source file?
26-------------------------------------------------------------
27
Georg Brandlc4a55fc2010-02-06 18:46:57 +000028If you can't find a source file for a module it may be a built-in or
29dynamically loaded module implemented in C, C++ or other compiled language.
30In this case you may not have the source file or it may be something like
Ezio Melottib35480e2012-05-13 20:14:04 +030031:file:`mathmodule.c`, somewhere in a C source directory (not on the Python Path).
Georg Brandld7413152009-10-11 21:25:26 +000032
33There are (at least) three kinds of modules in Python:
34
351) modules written in Python (.py);
362) modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
373) modules written in C and linked with the interpreter; to get a list of these,
38 type::
39
40 import sys
Georg Brandl9e4ff752009-12-19 17:57:51 +000041 print(sys.builtin_module_names)
Georg Brandld7413152009-10-11 21:25:26 +000042
43
44How do I make a Python script executable on Unix?
45-------------------------------------------------
46
47You need to do two things: the script file's mode must be executable and the
48first line must begin with ``#!`` followed by the path of the Python
49interpreter.
50
51The first is done by executing ``chmod +x scriptfile`` or perhaps ``chmod 755
52scriptfile``.
53
54The second can be done in a number of ways. The most straightforward way is to
55write ::
56
57 #!/usr/local/bin/python
58
59as the very first line of your file, using the pathname for where the Python
60interpreter is installed on your platform.
61
62If you would like the script to be independent of where the Python interpreter
Ezio Melottib35480e2012-05-13 20:14:04 +030063lives, you can use the :program:`env` program. Almost all Unix variants support
64the following, assuming the Python interpreter is in a directory on the user's
65:envvar:`PATH`::
Georg Brandld7413152009-10-11 21:25:26 +000066
67 #!/usr/bin/env python
68
Ezio Melottib35480e2012-05-13 20:14:04 +030069*Don't* do this for CGI scripts. The :envvar:`PATH` variable for CGI scripts is
70often very minimal, so you need to use the actual absolute pathname of the
Georg Brandld7413152009-10-11 21:25:26 +000071interpreter.
72
Ezio Melottib35480e2012-05-13 20:14:04 +030073Occasionally, a user's environment is so full that the :program:`/usr/bin/env`
74program fails; or there's no env program at all. In that case, you can try the
Georg Brandld7413152009-10-11 21:25:26 +000075following hack (due to Alex Rezinsky)::
76
77 #! /bin/sh
78 """:"
79 exec python $0 ${1+"$@"}
80 """
81
82The minor disadvantage is that this defines the script's __doc__ string.
83However, you can fix that by adding ::
84
85 __doc__ = """...Whatever..."""
86
87
88
89Is there a curses/termcap package for Python?
90---------------------------------------------
91
92.. XXX curses *is* built by default, isn't it?
93
94For Unix variants: The standard Python source distribution comes with a curses
Ezio Melottib35480e2012-05-13 20:14:04 +030095module in the :source:`Modules` subdirectory, though it's not compiled by default.
96(Note that this is not available in the Windows distribution -- there is no
97curses module for Windows.)
Georg Brandld7413152009-10-11 21:25:26 +000098
Ezio Melottib35480e2012-05-13 20:14:04 +030099The :mod:`curses` module supports basic curses features as well as many additional
Georg Brandld7413152009-10-11 21:25:26 +0000100functions from ncurses and SYSV curses such as colour, alternative character set
101support, pads, and mouse support. This means the module isn't compatible with
102operating systems that only have BSD curses, but there don't seem to be any
103currently maintained OSes that fall into this category.
104
105For Windows: use `the consolelib module
106<http://effbot.org/zone/console-index.htm>`_.
107
108
109Is there an equivalent to C's onexit() in Python?
110-------------------------------------------------
111
112The :mod:`atexit` module provides a register function that is similar to C's
Ezio Melottib35480e2012-05-13 20:14:04 +0300113:c:func:`onexit`.
Georg Brandld7413152009-10-11 21:25:26 +0000114
115
116Why don't my signal handlers work?
117----------------------------------
118
119The most common problem is that the signal handler is declared with the wrong
120argument list. It is called as ::
121
122 handler(signum, frame)
123
124so it should be declared with two arguments::
125
126 def handler(signum, frame):
127 ...
128
129
130Common tasks
131============
132
133How do I test a Python program or component?
134--------------------------------------------
135
136Python comes with two testing frameworks. The :mod:`doctest` module finds
137examples in the docstrings for a module and runs them, comparing the output with
138the expected output given in the docstring.
139
140The :mod:`unittest` module is a fancier testing framework modelled on Java and
141Smalltalk testing frameworks.
142
Ezio Melottib35480e2012-05-13 20:14:04 +0300143To make testing easier, you should use good modular design in your program.
144Your program should have almost all functionality
Georg Brandld7413152009-10-11 21:25:26 +0000145encapsulated in either functions or class methods -- and this sometimes has the
146surprising and delightful effect of making the program run faster (because local
147variable accesses are faster than global accesses). Furthermore the program
148should avoid depending on mutating global variables, since this makes testing
149much more difficult to do.
150
151The "global main logic" of your program may be as simple as ::
152
153 if __name__ == "__main__":
154 main_logic()
155
156at the bottom of the main module of your program.
157
158Once your program is organized as a tractable collection of functions and class
159behaviours you should write test functions that exercise the behaviours. A test
Ezio Melottib35480e2012-05-13 20:14:04 +0300160suite that automates a sequence of tests can be associated with each module.
Georg Brandld7413152009-10-11 21:25:26 +0000161This sounds like a lot of work, but since Python is so terse and flexible it's
162surprisingly easy. You can make coding much more pleasant and fun by writing
163your test functions in parallel with the "production code", since this makes it
164easy to find bugs and even design flaws earlier.
165
166"Support modules" that are not intended to be the main module of a program may
167include a self-test of the module. ::
168
169 if __name__ == "__main__":
170 self_test()
171
172Even programs that interact with complex external interfaces may be tested when
173the external interfaces are unavailable by using "fake" interfaces implemented
174in Python.
175
176
177How do I create documentation from doc strings?
178-----------------------------------------------
179
Georg Brandld7413152009-10-11 21:25:26 +0000180The :mod:`pydoc` module can create HTML from the doc strings in your Python
Georg Brandl495f7b52009-10-27 15:28:25 +0000181source code. An alternative for creating API documentation purely from
182docstrings is `epydoc <http://epydoc.sf.net/>`_. `Sphinx
183<http://sphinx.pocoo.org>`_ can also include docstring content.
Georg Brandld7413152009-10-11 21:25:26 +0000184
185
186How do I get a single keypress at a time?
187-----------------------------------------
188
Ezio Melottib35480e2012-05-13 20:14:04 +0300189For Unix variants there are several solutions. It's straightforward to do this
Georg Brandl9e4ff752009-12-19 17:57:51 +0000190using curses, but curses is a fairly large module to learn.
191
192.. XXX this doesn't work out of the box, some IO expert needs to check why
193
194 Here's a solution without curses::
Georg Brandld7413152009-10-11 21:25:26 +0000195
196 import termios, fcntl, sys, os
197 fd = sys.stdin.fileno()
198
199 oldterm = termios.tcgetattr(fd)
200 newattr = termios.tcgetattr(fd)
201 newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
202 termios.tcsetattr(fd, termios.TCSANOW, newattr)
203
204 oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
205 fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
206
207 try:
Georg Brandl9e4ff752009-12-19 17:57:51 +0000208 while True:
Georg Brandld7413152009-10-11 21:25:26 +0000209 try:
210 c = sys.stdin.read(1)
Georg Brandl9e4ff752009-12-19 17:57:51 +0000211 print("Got character", repr(c))
Andrew Svetlov5f11a002012-12-18 23:16:44 +0200212 except OSError:
Georg Brandl9e4ff752009-12-19 17:57:51 +0000213 pass
Georg Brandld7413152009-10-11 21:25:26 +0000214 finally:
215 termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
216 fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
217
Georg Brandl9e4ff752009-12-19 17:57:51 +0000218 You need the :mod:`termios` and the :mod:`fcntl` module for any of this to
219 work, and I've only tried it on Linux, though it should work elsewhere. In
220 this code, characters are read and printed one at a time.
Georg Brandld7413152009-10-11 21:25:26 +0000221
Georg Brandl9e4ff752009-12-19 17:57:51 +0000222 :func:`termios.tcsetattr` turns off stdin's echoing and disables canonical
223 mode. :func:`fcntl.fnctl` is used to obtain stdin's file descriptor flags
224 and modify them for non-blocking mode. Since reading stdin when it is empty
Andrew Svetlov5f11a002012-12-18 23:16:44 +0200225 results in an :exc:`OSError`, this error is caught and ignored.
Georg Brandld7413152009-10-11 21:25:26 +0000226
Andrew Svetlov8a045cb2012-12-19 13:45:30 +0200227 .. versionchanged:: 3.3
228 *sys.stdin.read* used to raise :exc:`IOError`. Starting from Python 3.3
229 :exc:`IOError` is alias for :exc:`OSError`.
230
Georg Brandld7413152009-10-11 21:25:26 +0000231
232Threads
233=======
234
235How do I program using threads?
236-------------------------------
237
Georg Brandld404fa62009-10-13 16:55:12 +0000238Be sure to use the :mod:`threading` module and not the :mod:`_thread` module.
Georg Brandld7413152009-10-11 21:25:26 +0000239The :mod:`threading` module builds convenient abstractions on top of the
Georg Brandld404fa62009-10-13 16:55:12 +0000240low-level primitives provided by the :mod:`_thread` module.
Georg Brandld7413152009-10-11 21:25:26 +0000241
242Aahz has a set of slides from his threading tutorial that are helpful; see
Georg Brandl495f7b52009-10-27 15:28:25 +0000243http://www.pythoncraft.com/OSCON2001/.
Georg Brandld7413152009-10-11 21:25:26 +0000244
245
246None of my threads seem to run: why?
247------------------------------------
248
249As soon as the main thread exits, all threads are killed. Your main thread is
250running too quickly, giving the threads no time to do any work.
251
252A simple fix is to add a sleep to the end of the program that's long enough for
253all the threads to finish::
254
255 import threading, time
256
257 def thread_task(name, n):
Georg Brandl9e4ff752009-12-19 17:57:51 +0000258 for i in range(n): print(name, i)
Georg Brandld7413152009-10-11 21:25:26 +0000259
260 for i in range(10):
261 T = threading.Thread(target=thread_task, args=(str(i), i))
262 T.start()
263
Georg Brandl9e4ff752009-12-19 17:57:51 +0000264 time.sleep(10) # <---------------------------!
Georg Brandld7413152009-10-11 21:25:26 +0000265
266But now (on many platforms) the threads don't run in parallel, but appear to run
267sequentially, one at a time! The reason is that the OS thread scheduler doesn't
268start a new thread until the previous thread is blocked.
269
270A simple fix is to add a tiny sleep to the start of the run function::
271
272 def thread_task(name, n):
Georg Brandl9e4ff752009-12-19 17:57:51 +0000273 time.sleep(0.001) # <--------------------!
274 for i in range(n): print(name, i)
Georg Brandld7413152009-10-11 21:25:26 +0000275
276 for i in range(10):
277 T = threading.Thread(target=thread_task, args=(str(i), i))
278 T.start()
279
280 time.sleep(10)
281
Ezio Melottib35480e2012-05-13 20:14:04 +0300282Instead of trying to guess a good delay value for :func:`time.sleep`,
Georg Brandld7413152009-10-11 21:25:26 +0000283it's better to use some kind of semaphore mechanism. One idea is to use the
Georg Brandld404fa62009-10-13 16:55:12 +0000284:mod:`queue` module to create a queue object, let each thread append a token to
Georg Brandld7413152009-10-11 21:25:26 +0000285the queue when it finishes, and let the main thread read as many tokens from the
286queue as there are threads.
287
288
289How do I parcel out work among a bunch of worker threads?
290---------------------------------------------------------
291
Antoine Pitrou11480b62011-02-05 11:18:34 +0000292The easiest way is to use the new :mod:`concurrent.futures` module,
293especially the :mod:`~concurrent.futures.ThreadPoolExecutor` class.
294
295Or, if you want fine control over the dispatching algorithm, you can write
296your own logic manually. Use the :mod:`queue` module to create a queue
297containing a list of jobs. The :class:`~queue.Queue` class maintains a
Ezio Melottib35480e2012-05-13 20:14:04 +0300298list of objects and has a ``.put(obj)`` method that adds items to the queue and
299a ``.get()`` method to return them. The class will take care of the locking
300necessary to ensure that each job is handed out exactly once.
Georg Brandld7413152009-10-11 21:25:26 +0000301
302Here's a trivial example::
303
Georg Brandl9e4ff752009-12-19 17:57:51 +0000304 import threading, queue, time
Georg Brandld7413152009-10-11 21:25:26 +0000305
306 # The worker thread gets jobs off the queue. When the queue is empty, it
307 # assumes there will be no more work and exits.
308 # (Realistically workers will run until terminated.)
Ezio Melottib35480e2012-05-13 20:14:04 +0300309 def worker():
Georg Brandl9e4ff752009-12-19 17:57:51 +0000310 print('Running worker')
Georg Brandld7413152009-10-11 21:25:26 +0000311 time.sleep(0.1)
312 while True:
313 try:
314 arg = q.get(block=False)
Georg Brandl9e4ff752009-12-19 17:57:51 +0000315 except queue.Empty:
316 print('Worker', threading.currentThread(), end=' ')
317 print('queue empty')
Georg Brandld7413152009-10-11 21:25:26 +0000318 break
319 else:
Georg Brandl9e4ff752009-12-19 17:57:51 +0000320 print('Worker', threading.currentThread(), end=' ')
321 print('running with argument', arg)
Georg Brandld7413152009-10-11 21:25:26 +0000322 time.sleep(0.5)
323
324 # Create queue
Georg Brandl9e4ff752009-12-19 17:57:51 +0000325 q = queue.Queue()
Georg Brandld7413152009-10-11 21:25:26 +0000326
327 # Start a pool of 5 workers
328 for i in range(5):
329 t = threading.Thread(target=worker, name='worker %i' % (i+1))
330 t.start()
331
332 # Begin adding work to the queue
333 for i in range(50):
334 q.put(i)
335
336 # Give threads time to run
Georg Brandl9e4ff752009-12-19 17:57:51 +0000337 print('Main thread sleeping')
Georg Brandld7413152009-10-11 21:25:26 +0000338 time.sleep(5)
339
Ezio Melottib35480e2012-05-13 20:14:04 +0300340When run, this will produce the following output:
341
342.. code-block:: none
Georg Brandld7413152009-10-11 21:25:26 +0000343
344 Running worker
345 Running worker
346 Running worker
347 Running worker
348 Running worker
349 Main thread sleeping
Georg Brandl9e4ff752009-12-19 17:57:51 +0000350 Worker <Thread(worker 1, started 130283832797456)> running with argument 0
351 Worker <Thread(worker 2, started 130283824404752)> running with argument 1
352 Worker <Thread(worker 3, started 130283816012048)> running with argument 2
353 Worker <Thread(worker 4, started 130283807619344)> running with argument 3
354 Worker <Thread(worker 5, started 130283799226640)> running with argument 4
355 Worker <Thread(worker 1, started 130283832797456)> running with argument 5
Georg Brandld7413152009-10-11 21:25:26 +0000356 ...
357
Georg Brandl3539afd2012-05-30 22:03:20 +0200358Consult the module's documentation for more details; the :class:`~queue.Queue`
Ezio Melottib35480e2012-05-13 20:14:04 +0300359class provides a featureful interface.
Georg Brandld7413152009-10-11 21:25:26 +0000360
361
362What kinds of global value mutation are thread-safe?
363----------------------------------------------------
364
Antoine Pitrou11480b62011-02-05 11:18:34 +0000365A :term:`global interpreter lock` (GIL) is used internally to ensure that only one
Georg Brandld7413152009-10-11 21:25:26 +0000366thread runs in the Python VM at a time. In general, Python offers to switch
367among threads only between bytecode instructions; how frequently it switches can
Georg Brandl9e4ff752009-12-19 17:57:51 +0000368be set via :func:`sys.setswitchinterval`. Each bytecode instruction and
Georg Brandld7413152009-10-11 21:25:26 +0000369therefore all the C implementation code reached from each instruction is
370therefore atomic from the point of view of a Python program.
371
372In theory, this means an exact accounting requires an exact understanding of the
373PVM bytecode implementation. In practice, it means that operations on shared
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000374variables of built-in data types (ints, lists, dicts, etc) that "look atomic"
Georg Brandld7413152009-10-11 21:25:26 +0000375really are.
376
377For example, the following operations are all atomic (L, L1, L2 are lists, D,
378D1, D2 are dicts, x, y are objects, i, j are ints)::
379
380 L.append(x)
381 L1.extend(L2)
382 x = L[i]
383 x = L.pop()
384 L1[i:j] = L2
385 L.sort()
386 x = y
387 x.field = y
388 D[x] = y
389 D1.update(D2)
390 D.keys()
391
392These aren't::
393
394 i = i+1
395 L.append(L[-1])
396 L[i] = L[j]
397 D[x] = D[x] + 1
398
399Operations that replace other objects may invoke those other objects'
400:meth:`__del__` method when their reference count reaches zero, and that can
401affect things. This is especially true for the mass updates to dictionaries and
402lists. When in doubt, use a mutex!
403
404
405Can't we get rid of the Global Interpreter Lock?
406------------------------------------------------
407
Georg Brandl495f7b52009-10-27 15:28:25 +0000408.. XXX link to dbeazley's talk about GIL?
Georg Brandld7413152009-10-11 21:25:26 +0000409
Antoine Pitrou11480b62011-02-05 11:18:34 +0000410The :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's
Georg Brandld7413152009-10-11 21:25:26 +0000411deployment on high-end multiprocessor server machines, because a multi-threaded
412Python program effectively only uses one CPU, due to the insistence that
413(almost) all Python code can only run while the GIL is held.
414
415Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive
416patch set (the "free threading" patches) that removed the GIL and replaced it
Antoine Pitrou11480b62011-02-05 11:18:34 +0000417with fine-grained locking. Adam Olsen recently did a similar experiment
418in his `python-safethread <http://code.google.com/p/python-safethread/>`_
419project. Unfortunately, both experiments exhibited a sharp drop in single-thread
420performance (at least 30% slower), due to the amount of fine-grained locking
421necessary to compensate for the removal of the GIL.
Georg Brandld7413152009-10-11 21:25:26 +0000422
423This doesn't mean that you can't make good use of Python on multi-CPU machines!
424You just have to be creative with dividing the work up between multiple
Antoine Pitrou11480b62011-02-05 11:18:34 +0000425*processes* rather than multiple *threads*. The
426:class:`~concurrent.futures.ProcessPoolExecutor` class in the new
427:mod:`concurrent.futures` module provides an easy way of doing so; the
428:mod:`multiprocessing` module provides a lower-level API in case you want
429more control over dispatching of tasks.
430
431Judicious use of C extensions will also help; if you use a C extension to
432perform a time-consuming task, the extension can release the GIL while the
433thread of execution is in the C code and allow other threads to get some work
434done. Some standard library modules such as :mod:`zlib` and :mod:`hashlib`
435already do this.
Georg Brandld7413152009-10-11 21:25:26 +0000436
437It has been suggested that the GIL should be a per-interpreter-state lock rather
438than truly global; interpreters then wouldn't be able to share objects.
439Unfortunately, this isn't likely to happen either. It would be a tremendous
440amount of work, because many object implementations currently have global state.
441For example, small integers and short strings are cached; these caches would
442have to be moved to the interpreter state. Other object types have their own
443free list; these free lists would have to be moved to the interpreter state.
444And so on.
445
446And I doubt that it can even be done in finite time, because the same problem
447exists for 3rd party extensions. It is likely that 3rd party extensions are
448being written at a faster rate than you can convert them to store all their
449global state in the interpreter state.
450
451And finally, once you have multiple interpreters not sharing any state, what
452have you gained over running each interpreter in a separate process?
453
454
455Input and Output
456================
457
458How do I delete a file? (And other file questions...)
459-----------------------------------------------------
460
461Use ``os.remove(filename)`` or ``os.unlink(filename)``; for documentation, see
Georg Brandl9e4ff752009-12-19 17:57:51 +0000462the :mod:`os` module. The two functions are identical; :func:`~os.unlink` is simply
Georg Brandld7413152009-10-11 21:25:26 +0000463the name of the Unix system call for this function.
464
465To remove a directory, use :func:`os.rmdir`; use :func:`os.mkdir` to create one.
466``os.makedirs(path)`` will create any intermediate directories in ``path`` that
467don't exist. ``os.removedirs(path)`` will remove intermediate directories as
468long as they're empty; if you want to delete an entire directory tree and its
469contents, use :func:`shutil.rmtree`.
470
471To rename a file, use ``os.rename(old_path, new_path)``.
472
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000473To truncate a file, open it using ``f = open(filename, "rb+")``, and use
Georg Brandld7413152009-10-11 21:25:26 +0000474``f.truncate(offset)``; offset defaults to the current seek position. There's
Georg Brandl682d7e02010-10-06 10:26:05 +0000475also ``os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where
Ezio Melottib35480e2012-05-13 20:14:04 +0300476*fd* is the file descriptor (a small integer).
Georg Brandld7413152009-10-11 21:25:26 +0000477
478The :mod:`shutil` module also contains a number of functions to work on files
479including :func:`~shutil.copyfile`, :func:`~shutil.copytree`, and
480:func:`~shutil.rmtree`.
481
482
483How do I copy a file?
484---------------------
485
486The :mod:`shutil` module contains a :func:`~shutil.copyfile` function. Note
487that on MacOS 9 it doesn't copy the resource fork and Finder info.
488
489
490How do I read (or write) binary data?
491-------------------------------------
492
493To read or write complex binary data formats, it's best to use the :mod:`struct`
494module. It allows you to take a string containing binary data (usually numbers)
495and convert it to Python objects; and vice versa.
496
497For example, the following code reads two 2-byte integers and one 4-byte integer
498in big-endian format from a file::
499
500 import struct
501
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000502 with open(filename, "rb") as f:
503 s = f.read(8)
504 x, y, z = struct.unpack(">hhl", s)
Georg Brandld7413152009-10-11 21:25:26 +0000505
506The '>' in the format string forces big-endian data; the letter 'h' reads one
507"short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the
508string.
509
Ezio Melottib35480e2012-05-13 20:14:04 +0300510For data that is more regular (e.g. a homogeneous list of ints or floats),
Georg Brandld7413152009-10-11 21:25:26 +0000511you can also use the :mod:`array` module.
512
Ezio Melottib35480e2012-05-13 20:14:04 +0300513.. note::
514 To read and write binary data, it is mandatory to open the file in
515 binary mode (here, passing ``"rb"`` to :func:`open`). If you use
516 ``"r"`` instead (the default), the file will be open in text mode
517 and ``f.read()`` will return :class:`str` objects rather than
518 :class:`bytes` objects.
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000519
Georg Brandld7413152009-10-11 21:25:26 +0000520
521I can't seem to use os.read() on a pipe created with os.popen(); why?
522---------------------------------------------------------------------
523
524:func:`os.read` is a low-level function which takes a file descriptor, a small
525integer representing the opened file. :func:`os.popen` creates a high-level
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000526file object, the same type returned by the built-in :func:`open` function.
Ezio Melottib35480e2012-05-13 20:14:04 +0300527Thus, to read *n* bytes from a pipe *p* created with :func:`os.popen`, you need to
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000528use ``p.read(n)``.
Georg Brandld7413152009-10-11 21:25:26 +0000529
530
Georg Brandl9e4ff752009-12-19 17:57:51 +0000531.. XXX update to use subprocess. See the :ref:`subprocess-replacements` section.
Georg Brandld7413152009-10-11 21:25:26 +0000532
Georg Brandl9e4ff752009-12-19 17:57:51 +0000533 How do I run a subprocess with pipes connected to both input and output?
534 ------------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000535
Georg Brandl9e4ff752009-12-19 17:57:51 +0000536 Use the :mod:`popen2` module. For example::
Georg Brandld7413152009-10-11 21:25:26 +0000537
Georg Brandl9e4ff752009-12-19 17:57:51 +0000538 import popen2
539 fromchild, tochild = popen2.popen2("command")
540 tochild.write("input\n")
541 tochild.flush()
542 output = fromchild.readline()
Georg Brandld7413152009-10-11 21:25:26 +0000543
Georg Brandl9e4ff752009-12-19 17:57:51 +0000544 Warning: in general it is unwise to do this because you can easily cause a
545 deadlock where your process is blocked waiting for output from the child
546 while the child is blocked waiting for input from you. This can be caused
Ezio Melottib35480e2012-05-13 20:14:04 +0300547 by the parent expecting the child to output more text than it does or
548 by data being stuck in stdio buffers due to lack of flushing.
Georg Brandl9e4ff752009-12-19 17:57:51 +0000549 The Python parent can of course explicitly flush the data it sends to the
550 child before it reads any output, but if the child is a naive C program it
551 may have been written to never explicitly flush its output, even if it is
552 interactive, since flushing is normally automatic.
Georg Brandld7413152009-10-11 21:25:26 +0000553
Georg Brandl9e4ff752009-12-19 17:57:51 +0000554 Note that a deadlock is also possible if you use :func:`popen3` to read
555 stdout and stderr. If one of the two is too large for the internal buffer
556 (increasing the buffer size does not help) and you ``read()`` the other one
557 first, there is a deadlock, too.
Georg Brandld7413152009-10-11 21:25:26 +0000558
Georg Brandl9e4ff752009-12-19 17:57:51 +0000559 Note on a bug in popen2: unless your program calls ``wait()`` or
560 ``waitpid()``, finished child processes are never removed, and eventually
561 calls to popen2 will fail because of a limit on the number of child
562 processes. Calling :func:`os.waitpid` with the :data:`os.WNOHANG` option can
563 prevent this; a good place to insert such a call would be before calling
564 ``popen2`` again.
Georg Brandld7413152009-10-11 21:25:26 +0000565
Georg Brandl9e4ff752009-12-19 17:57:51 +0000566 In many cases, all you really need is to run some data through a command and
567 get the result back. Unless the amount of data is very large, the easiest
568 way to do this is to write it to a temporary file and run the command with
569 that temporary file as input. The standard module :mod:`tempfile` exports a
Ezio Melottib35480e2012-05-13 20:14:04 +0300570 :func:`~tempfile.mktemp` function to generate unique temporary file names. ::
Georg Brandld7413152009-10-11 21:25:26 +0000571
Georg Brandl9e4ff752009-12-19 17:57:51 +0000572 import tempfile
573 import os
Georg Brandld7413152009-10-11 21:25:26 +0000574
Georg Brandl9e4ff752009-12-19 17:57:51 +0000575 class Popen3:
576 """
577 This is a deadlock-safe version of popen that returns
578 an object with errorlevel, out (a string) and err (a string).
579 (capturestderr may not work under windows.)
580 Example: print(Popen3('grep spam','\n\nhere spam\n\n').out)
581 """
582 def __init__(self,command,input=None,capturestderr=None):
583 outfile=tempfile.mktemp()
584 command="( %s ) > %s" % (command,outfile)
585 if input:
586 infile=tempfile.mktemp()
587 open(infile,"w").write(input)
588 command=command+" <"+infile
589 if capturestderr:
590 errfile=tempfile.mktemp()
591 command=command+" 2>"+errfile
592 self.errorlevel=os.system(command) >> 8
593 self.out=open(outfile,"r").read()
594 os.remove(outfile)
595 if input:
596 os.remove(infile)
597 if capturestderr:
598 self.err=open(errfile,"r").read()
599 os.remove(errfile)
Georg Brandld7413152009-10-11 21:25:26 +0000600
Georg Brandl9e4ff752009-12-19 17:57:51 +0000601 Note that many interactive programs (e.g. vi) don't work well with pipes
602 substituted for standard input and output. You will have to use pseudo ttys
603 ("ptys") instead of pipes. Or you can use a Python interface to Don Libes'
604 "expect" library. A Python extension that interfaces to expect is called
605 "expy" and available from http://expectpy.sourceforge.net. A pure Python
606 solution that works like expect is `pexpect
607 <http://pypi.python.org/pypi/pexpect/>`_.
Georg Brandld7413152009-10-11 21:25:26 +0000608
609
610How do I access the serial (RS232) port?
611----------------------------------------
612
613For Win32, POSIX (Linux, BSD, etc.), Jython:
614
615 http://pyserial.sourceforge.net
616
617For Unix, see a Usenet post by Mitch Chapman:
618
619 http://groups.google.com/groups?selm=34A04430.CF9@ohioee.com
620
621
622Why doesn't closing sys.stdout (stdin, stderr) really close it?
623---------------------------------------------------------------
624
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000625Python :term:`file objects <file object>` are a high-level layer of
626abstraction on low-level C file descriptors.
Georg Brandld7413152009-10-11 21:25:26 +0000627
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000628For most file objects you create in Python via the built-in :func:`open`
629function, ``f.close()`` marks the Python file object as being closed from
630Python's point of view, and also arranges to close the underlying C file
631descriptor. This also happens automatically in ``f``'s destructor, when
632``f`` becomes garbage.
Georg Brandld7413152009-10-11 21:25:26 +0000633
634But stdin, stdout and stderr are treated specially by Python, because of the
635special status also given to them by C. Running ``sys.stdout.close()`` marks
636the Python-level file object as being closed, but does *not* close the
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000637associated C file descriptor.
Georg Brandld7413152009-10-11 21:25:26 +0000638
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000639To close the underlying C file descriptor for one of these three, you should
640first be sure that's what you really want to do (e.g., you may confuse
641extension modules trying to do I/O). If it is, use :func:`os.close`::
Georg Brandld7413152009-10-11 21:25:26 +0000642
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000643 os.close(stdin.fileno())
644 os.close(stdout.fileno())
645 os.close(stderr.fileno())
646
647Or you can use the numeric constants 0, 1 and 2, respectively.
Georg Brandld7413152009-10-11 21:25:26 +0000648
649
650Network/Internet Programming
651============================
652
653What WWW tools are there for Python?
654------------------------------------
655
656See the chapters titled :ref:`internet` and :ref:`netdata` in the Library
657Reference Manual. Python has many modules that will help you build server-side
658and client-side web systems.
659
660.. XXX check if wiki page is still up to date
661
662A summary of available frameworks is maintained by Paul Boddie at
663http://wiki.python.org/moin/WebProgramming .
664
665Cameron Laird maintains a useful set of pages about Python web technologies at
666http://phaseit.net/claird/comp.lang.python/web_python.
667
668
669How can I mimic CGI form submission (METHOD=POST)?
670--------------------------------------------------
671
672I would like to retrieve web pages that are the result of POSTing a form. Is
673there existing code that would let me do this easily?
674
Georg Brandl9e4ff752009-12-19 17:57:51 +0000675Yes. Here's a simple example that uses urllib.request::
Georg Brandld7413152009-10-11 21:25:26 +0000676
677 #!/usr/local/bin/python
678
Georg Brandl9e4ff752009-12-19 17:57:51 +0000679 import urllib.request
Georg Brandld7413152009-10-11 21:25:26 +0000680
681 ### build the query string
682 qs = "First=Josephine&MI=Q&Last=Public"
683
684 ### connect and send the server a path
Georg Brandl9e4ff752009-12-19 17:57:51 +0000685 req = urllib.request.urlopen('http://www.some-server.out-there'
686 '/cgi-bin/some-cgi-script', data=qs)
687 msg, hdrs = req.read(), req.info()
Georg Brandld7413152009-10-11 21:25:26 +0000688
Georg Brandl54ebb782010-08-14 15:48:49 +0000689Note that in general for percent-encoded POST operations, query strings must be
Ezio Melottib35480e2012-05-13 20:14:04 +0300690quoted using :func:`urllib.parse.urlencode`. For example, to send
691``name=Guy Steele, Jr.``::
Georg Brandld7413152009-10-11 21:25:26 +0000692
Georg Brandl9e4ff752009-12-19 17:57:51 +0000693 >>> import urllib.parse
694 >>> urllib.parse.urlencode({'name': 'Guy Steele, Jr.'})
695 'name=Guy+Steele%2C+Jr.'
696
697.. seealso:: :ref:`urllib-howto` for extensive examples.
Georg Brandld7413152009-10-11 21:25:26 +0000698
699
700What module should I use to help with generating HTML?
701------------------------------------------------------
702
703.. XXX add modern template languages
704
Ezio Melottib35480e2012-05-13 20:14:04 +0300705You can find a collection of useful links on the `Web Programming wiki page
706<http://wiki.python.org/moin/WebProgramming>`_.
Georg Brandld7413152009-10-11 21:25:26 +0000707
708
709How do I send mail from a Python script?
710----------------------------------------
711
712Use the standard library module :mod:`smtplib`.
713
714Here's a very simple interactive mail sender that uses it. This method will
715work on any host that supports an SMTP listener. ::
716
717 import sys, smtplib
718
Georg Brandl9e4ff752009-12-19 17:57:51 +0000719 fromaddr = input("From: ")
720 toaddrs = input("To: ").split(',')
721 print("Enter message, end with ^D:")
Georg Brandld7413152009-10-11 21:25:26 +0000722 msg = ''
723 while True:
724 line = sys.stdin.readline()
725 if not line:
726 break
727 msg += line
728
729 # The actual mail send
730 server = smtplib.SMTP('localhost')
731 server.sendmail(fromaddr, toaddrs, msg)
732 server.quit()
733
734A Unix-only alternative uses sendmail. The location of the sendmail program
Ezio Melottib35480e2012-05-13 20:14:04 +0300735varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes
Georg Brandld7413152009-10-11 21:25:26 +0000736``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's
737some sample code::
738
Georg Brandl9e4ff752009-12-19 17:57:51 +0000739 SENDMAIL = "/usr/sbin/sendmail" # sendmail location
Georg Brandld7413152009-10-11 21:25:26 +0000740 import os
741 p = os.popen("%s -t -i" % SENDMAIL, "w")
742 p.write("To: receiver@example.com\n")
743 p.write("Subject: test\n")
Georg Brandl9e4ff752009-12-19 17:57:51 +0000744 p.write("\n") # blank line separating headers from body
Georg Brandld7413152009-10-11 21:25:26 +0000745 p.write("Some text\n")
746 p.write("some more text\n")
747 sts = p.close()
748 if sts != 0:
Georg Brandl9e4ff752009-12-19 17:57:51 +0000749 print("Sendmail exit status", sts)
Georg Brandld7413152009-10-11 21:25:26 +0000750
751
752How do I avoid blocking in the connect() method of a socket?
753------------------------------------------------------------
754
Antoine Pitrou70957212011-02-05 11:24:15 +0000755The :mod:`select` module is commonly used to help with asynchronous I/O on
756sockets.
Georg Brandld7413152009-10-11 21:25:26 +0000757
758To prevent the TCP connect from blocking, you can set the socket to non-blocking
759mode. Then when you do the ``connect()``, you will either connect immediately
760(unlikely) or get an exception that contains the error number as ``.errno``.
761``errno.EINPROGRESS`` indicates that the connection is in progress, but hasn't
762finished yet. Different OSes will return different values, so you're going to
763have to check what's returned on your system.
764
765You can use the ``connect_ex()`` method to avoid creating an exception. It will
766just return the errno value. To poll, you can call ``connect_ex()`` again later
Georg Brandl9e4ff752009-12-19 17:57:51 +0000767-- ``0`` or ``errno.EISCONN`` indicate that you're connected -- or you can pass this
Georg Brandld7413152009-10-11 21:25:26 +0000768socket to select to check if it's writable.
769
Antoine Pitrou70957212011-02-05 11:24:15 +0000770.. note::
771 The :mod:`asyncore` module presents a framework-like approach to the problem
772 of writing non-blocking networking code.
773 The third-party `Twisted <http://twistedmatrix.com/>`_ library is
774 a popular and feature-rich alternative.
775
Georg Brandld7413152009-10-11 21:25:26 +0000776
777Databases
778=========
779
780Are there any interfaces to database packages in Python?
781--------------------------------------------------------
782
783Yes.
784
Georg Brandld404fa62009-10-13 16:55:12 +0000785Interfaces to disk-based hashes such as :mod:`DBM <dbm.ndbm>` and :mod:`GDBM
786<dbm.gnu>` are also included with standard Python. There is also the
787:mod:`sqlite3` module, which provides a lightweight disk-based relational
788database.
Georg Brandld7413152009-10-11 21:25:26 +0000789
790Support for most relational databases is available. See the
791`DatabaseProgramming wiki page
792<http://wiki.python.org/moin/DatabaseProgramming>`_ for details.
793
794
795How do you implement persistent objects in Python?
796--------------------------------------------------
797
798The :mod:`pickle` library module solves this in a very general way (though you
799still can't store things like open files, sockets or windows), and the
800:mod:`shelve` library module uses pickle and (g)dbm to create persistent
Georg Brandld404fa62009-10-13 16:55:12 +0000801mappings containing arbitrary Python objects.
Georg Brandld7413152009-10-11 21:25:26 +0000802
Georg Brandld7413152009-10-11 21:25:26 +0000803
Georg Brandld7413152009-10-11 21:25:26 +0000804Mathematics and Numerics
805========================
806
807How do I generate random numbers in Python?
808-------------------------------------------
809
810The standard module :mod:`random` implements a random number generator. Usage
811is simple::
812
813 import random
814 random.random()
815
816This returns a random floating point number in the range [0, 1).
817
818There are also many other specialized generators in this module, such as:
819
820* ``randrange(a, b)`` chooses an integer in the range [a, b).
821* ``uniform(a, b)`` chooses a floating point number in the range [a, b).
822* ``normalvariate(mean, sdev)`` samples the normal (Gaussian) distribution.
823
824Some higher-level functions operate on sequences directly, such as:
825
826* ``choice(S)`` chooses random element from a given sequence
827* ``shuffle(L)`` shuffles a list in-place, i.e. permutes it randomly
828
829There's also a ``Random`` class you can instantiate to create independent
830multiple random number generators.