blob: 8bd774bdce207d6282afd421b420d37cab7456f1 [file] [log] [blame]
Georg Brandld7413152009-10-11 21:25:26 +00001:tocdepth: 2
2
3=========================
4Library and Extension FAQ
5=========================
6
Georg Brandl44ea77b2013-03-28 13:28:44 +01007.. only:: html
8
9 .. contents::
Georg Brandld7413152009-10-11 21:25:26 +000010
11General Library Questions
12=========================
13
14How do I find a module or application to perform task X?
15--------------------------------------------------------
16
17Check :ref:`the Library Reference <library-index>` to see if there's a relevant
18standard library module. (Eventually you'll learn what's in the standard
Ezio Melottib35480e2012-05-13 20:14:04 +030019library and will be able to skip this step.)
Georg Brandld7413152009-10-11 21:25:26 +000020
Georg Brandl495f7b52009-10-27 15:28:25 +000021For third-party packages, search the `Python Package Index
22<http://pypi.python.org/pypi>`_ or try `Google <http://www.google.com>`_ or
23another Web search engine. Searching for "Python" plus a keyword or two for
24your topic of interest will usually find something helpful.
Georg Brandld7413152009-10-11 21:25:26 +000025
26
27Where is the math.py (socket.py, regex.py, etc.) source file?
28-------------------------------------------------------------
29
Georg Brandlc4a55fc2010-02-06 18:46:57 +000030If you can't find a source file for a module it may be a built-in or
31dynamically loaded module implemented in C, C++ or other compiled language.
32In this case you may not have the source file or it may be something like
Ezio Melottib35480e2012-05-13 20:14:04 +030033:file:`mathmodule.c`, somewhere in a C source directory (not on the Python Path).
Georg Brandld7413152009-10-11 21:25:26 +000034
35There are (at least) three kinds of modules in Python:
36
371) modules written in Python (.py);
382) modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
393) modules written in C and linked with the interpreter; to get a list of these,
40 type::
41
42 import sys
Georg Brandl9e4ff752009-12-19 17:57:51 +000043 print(sys.builtin_module_names)
Georg Brandld7413152009-10-11 21:25:26 +000044
45
46How do I make a Python script executable on Unix?
47-------------------------------------------------
48
49You need to do two things: the script file's mode must be executable and the
50first line must begin with ``#!`` followed by the path of the Python
51interpreter.
52
53The first is done by executing ``chmod +x scriptfile`` or perhaps ``chmod 755
54scriptfile``.
55
56The second can be done in a number of ways. The most straightforward way is to
57write ::
58
59 #!/usr/local/bin/python
60
61as the very first line of your file, using the pathname for where the Python
62interpreter is installed on your platform.
63
64If you would like the script to be independent of where the Python interpreter
Ezio Melottib35480e2012-05-13 20:14:04 +030065lives, you can use the :program:`env` program. Almost all Unix variants support
66the following, assuming the Python interpreter is in a directory on the user's
67:envvar:`PATH`::
Georg Brandld7413152009-10-11 21:25:26 +000068
69 #!/usr/bin/env python
70
Ezio Melottib35480e2012-05-13 20:14:04 +030071*Don't* do this for CGI scripts. The :envvar:`PATH` variable for CGI scripts is
72often very minimal, so you need to use the actual absolute pathname of the
Georg Brandld7413152009-10-11 21:25:26 +000073interpreter.
74
Ezio Melottib35480e2012-05-13 20:14:04 +030075Occasionally, a user's environment is so full that the :program:`/usr/bin/env`
76program fails; or there's no env program at all. In that case, you can try the
Georg Brandld7413152009-10-11 21:25:26 +000077following hack (due to Alex Rezinsky)::
78
79 #! /bin/sh
80 """:"
81 exec python $0 ${1+"$@"}
82 """
83
84The minor disadvantage is that this defines the script's __doc__ string.
85However, you can fix that by adding ::
86
87 __doc__ = """...Whatever..."""
88
89
90
91Is there a curses/termcap package for Python?
92---------------------------------------------
93
94.. XXX curses *is* built by default, isn't it?
95
96For Unix variants: The standard Python source distribution comes with a curses
Ezio Melottib35480e2012-05-13 20:14:04 +030097module in the :source:`Modules` subdirectory, though it's not compiled by default.
98(Note that this is not available in the Windows distribution -- there is no
99curses module for Windows.)
Georg Brandld7413152009-10-11 21:25:26 +0000100
Ezio Melottib35480e2012-05-13 20:14:04 +0300101The :mod:`curses` module supports basic curses features as well as many additional
Georg Brandld7413152009-10-11 21:25:26 +0000102functions from ncurses and SYSV curses such as colour, alternative character set
103support, pads, and mouse support. This means the module isn't compatible with
104operating systems that only have BSD curses, but there don't seem to be any
105currently maintained OSes that fall into this category.
106
107For Windows: use `the consolelib module
108<http://effbot.org/zone/console-index.htm>`_.
109
110
111Is there an equivalent to C's onexit() in Python?
112-------------------------------------------------
113
114The :mod:`atexit` module provides a register function that is similar to C's
Ezio Melottib35480e2012-05-13 20:14:04 +0300115:c:func:`onexit`.
Georg Brandld7413152009-10-11 21:25:26 +0000116
117
118Why don't my signal handlers work?
119----------------------------------
120
121The most common problem is that the signal handler is declared with the wrong
122argument list. It is called as ::
123
124 handler(signum, frame)
125
126so it should be declared with two arguments::
127
128 def handler(signum, frame):
129 ...
130
131
132Common tasks
133============
134
135How do I test a Python program or component?
136--------------------------------------------
137
138Python comes with two testing frameworks. The :mod:`doctest` module finds
139examples in the docstrings for a module and runs them, comparing the output with
140the expected output given in the docstring.
141
142The :mod:`unittest` module is a fancier testing framework modelled on Java and
143Smalltalk testing frameworks.
144
Ezio Melottib35480e2012-05-13 20:14:04 +0300145To make testing easier, you should use good modular design in your program.
146Your program should have almost all functionality
Georg Brandld7413152009-10-11 21:25:26 +0000147encapsulated in either functions or class methods -- and this sometimes has the
148surprising and delightful effect of making the program run faster (because local
149variable accesses are faster than global accesses). Furthermore the program
150should avoid depending on mutating global variables, since this makes testing
151much more difficult to do.
152
153The "global main logic" of your program may be as simple as ::
154
155 if __name__ == "__main__":
156 main_logic()
157
158at the bottom of the main module of your program.
159
160Once your program is organized as a tractable collection of functions and class
161behaviours you should write test functions that exercise the behaviours. A test
Ezio Melottib35480e2012-05-13 20:14:04 +0300162suite that automates a sequence of tests can be associated with each module.
Georg Brandld7413152009-10-11 21:25:26 +0000163This sounds like a lot of work, but since Python is so terse and flexible it's
164surprisingly easy. You can make coding much more pleasant and fun by writing
165your test functions in parallel with the "production code", since this makes it
166easy to find bugs and even design flaws earlier.
167
168"Support modules" that are not intended to be the main module of a program may
169include a self-test of the module. ::
170
171 if __name__ == "__main__":
172 self_test()
173
174Even programs that interact with complex external interfaces may be tested when
175the external interfaces are unavailable by using "fake" interfaces implemented
176in Python.
177
178
179How do I create documentation from doc strings?
180-----------------------------------------------
181
Georg Brandld7413152009-10-11 21:25:26 +0000182The :mod:`pydoc` module can create HTML from the doc strings in your Python
Georg Brandl495f7b52009-10-27 15:28:25 +0000183source code. An alternative for creating API documentation purely from
184docstrings is `epydoc <http://epydoc.sf.net/>`_. `Sphinx
185<http://sphinx.pocoo.org>`_ can also include docstring content.
Georg Brandld7413152009-10-11 21:25:26 +0000186
187
188How do I get a single keypress at a time?
189-----------------------------------------
190
Ezio Melottib35480e2012-05-13 20:14:04 +0300191For Unix variants there are several solutions. It's straightforward to do this
Georg Brandl9e4ff752009-12-19 17:57:51 +0000192using curses, but curses is a fairly large module to learn.
193
194.. XXX this doesn't work out of the box, some IO expert needs to check why
195
196 Here's a solution without curses::
Georg Brandld7413152009-10-11 21:25:26 +0000197
198 import termios, fcntl, sys, os
199 fd = sys.stdin.fileno()
200
201 oldterm = termios.tcgetattr(fd)
202 newattr = termios.tcgetattr(fd)
203 newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
204 termios.tcsetattr(fd, termios.TCSANOW, newattr)
205
206 oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
207 fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
208
209 try:
Georg Brandl9e4ff752009-12-19 17:57:51 +0000210 while True:
Georg Brandld7413152009-10-11 21:25:26 +0000211 try:
212 c = sys.stdin.read(1)
Georg Brandl9e4ff752009-12-19 17:57:51 +0000213 print("Got character", repr(c))
Andrew Svetlov5f11a002012-12-18 23:16:44 +0200214 except OSError:
Georg Brandl9e4ff752009-12-19 17:57:51 +0000215 pass
Georg Brandld7413152009-10-11 21:25:26 +0000216 finally:
217 termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
218 fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
219
Georg Brandl9e4ff752009-12-19 17:57:51 +0000220 You need the :mod:`termios` and the :mod:`fcntl` module for any of this to
221 work, and I've only tried it on Linux, though it should work elsewhere. In
222 this code, characters are read and printed one at a time.
Georg Brandld7413152009-10-11 21:25:26 +0000223
Georg Brandl9e4ff752009-12-19 17:57:51 +0000224 :func:`termios.tcsetattr` turns off stdin's echoing and disables canonical
225 mode. :func:`fcntl.fnctl` is used to obtain stdin's file descriptor flags
226 and modify them for non-blocking mode. Since reading stdin when it is empty
Andrew Svetlov5f11a002012-12-18 23:16:44 +0200227 results in an :exc:`OSError`, this error is caught and ignored.
Georg Brandld7413152009-10-11 21:25:26 +0000228
Andrew Svetlov8a045cb2012-12-19 13:45:30 +0200229 .. versionchanged:: 3.3
230 *sys.stdin.read* used to raise :exc:`IOError`. Starting from Python 3.3
231 :exc:`IOError` is alias for :exc:`OSError`.
232
Georg Brandld7413152009-10-11 21:25:26 +0000233
234Threads
235=======
236
237How do I program using threads?
238-------------------------------
239
Georg Brandld404fa62009-10-13 16:55:12 +0000240Be sure to use the :mod:`threading` module and not the :mod:`_thread` module.
Georg Brandld7413152009-10-11 21:25:26 +0000241The :mod:`threading` module builds convenient abstractions on top of the
Georg Brandld404fa62009-10-13 16:55:12 +0000242low-level primitives provided by the :mod:`_thread` module.
Georg Brandld7413152009-10-11 21:25:26 +0000243
244Aahz has a set of slides from his threading tutorial that are helpful; see
Georg Brandl495f7b52009-10-27 15:28:25 +0000245http://www.pythoncraft.com/OSCON2001/.
Georg Brandld7413152009-10-11 21:25:26 +0000246
247
248None of my threads seem to run: why?
249------------------------------------
250
251As soon as the main thread exits, all threads are killed. Your main thread is
252running too quickly, giving the threads no time to do any work.
253
254A simple fix is to add a sleep to the end of the program that's long enough for
255all the threads to finish::
256
257 import threading, time
258
259 def thread_task(name, n):
Georg Brandl9e4ff752009-12-19 17:57:51 +0000260 for i in range(n): print(name, i)
Georg Brandld7413152009-10-11 21:25:26 +0000261
262 for i in range(10):
263 T = threading.Thread(target=thread_task, args=(str(i), i))
264 T.start()
265
Georg Brandl9e4ff752009-12-19 17:57:51 +0000266 time.sleep(10) # <---------------------------!
Georg Brandld7413152009-10-11 21:25:26 +0000267
268But now (on many platforms) the threads don't run in parallel, but appear to run
269sequentially, one at a time! The reason is that the OS thread scheduler doesn't
270start a new thread until the previous thread is blocked.
271
272A simple fix is to add a tiny sleep to the start of the run function::
273
274 def thread_task(name, n):
Georg Brandl9e4ff752009-12-19 17:57:51 +0000275 time.sleep(0.001) # <--------------------!
276 for i in range(n): print(name, i)
Georg Brandld7413152009-10-11 21:25:26 +0000277
278 for i in range(10):
279 T = threading.Thread(target=thread_task, args=(str(i), i))
280 T.start()
281
282 time.sleep(10)
283
Ezio Melottib35480e2012-05-13 20:14:04 +0300284Instead of trying to guess a good delay value for :func:`time.sleep`,
Georg Brandld7413152009-10-11 21:25:26 +0000285it's better to use some kind of semaphore mechanism. One idea is to use the
Georg Brandld404fa62009-10-13 16:55:12 +0000286:mod:`queue` module to create a queue object, let each thread append a token to
Georg Brandld7413152009-10-11 21:25:26 +0000287the queue when it finishes, and let the main thread read as many tokens from the
288queue as there are threads.
289
290
291How do I parcel out work among a bunch of worker threads?
292---------------------------------------------------------
293
Antoine Pitrou11480b62011-02-05 11:18:34 +0000294The easiest way is to use the new :mod:`concurrent.futures` module,
295especially the :mod:`~concurrent.futures.ThreadPoolExecutor` class.
296
297Or, if you want fine control over the dispatching algorithm, you can write
298your own logic manually. Use the :mod:`queue` module to create a queue
299containing a list of jobs. The :class:`~queue.Queue` class maintains a
Ezio Melottib35480e2012-05-13 20:14:04 +0300300list of objects and has a ``.put(obj)`` method that adds items to the queue and
301a ``.get()`` method to return them. The class will take care of the locking
302necessary to ensure that each job is handed out exactly once.
Georg Brandld7413152009-10-11 21:25:26 +0000303
304Here's a trivial example::
305
Georg Brandl9e4ff752009-12-19 17:57:51 +0000306 import threading, queue, time
Georg Brandld7413152009-10-11 21:25:26 +0000307
308 # The worker thread gets jobs off the queue. When the queue is empty, it
309 # assumes there will be no more work and exits.
310 # (Realistically workers will run until terminated.)
Ezio Melottib35480e2012-05-13 20:14:04 +0300311 def worker():
Georg Brandl9e4ff752009-12-19 17:57:51 +0000312 print('Running worker')
Georg Brandld7413152009-10-11 21:25:26 +0000313 time.sleep(0.1)
314 while True:
315 try:
316 arg = q.get(block=False)
Georg Brandl9e4ff752009-12-19 17:57:51 +0000317 except queue.Empty:
318 print('Worker', threading.currentThread(), end=' ')
319 print('queue empty')
Georg Brandld7413152009-10-11 21:25:26 +0000320 break
321 else:
Georg Brandl9e4ff752009-12-19 17:57:51 +0000322 print('Worker', threading.currentThread(), end=' ')
323 print('running with argument', arg)
Georg Brandld7413152009-10-11 21:25:26 +0000324 time.sleep(0.5)
325
326 # Create queue
Georg Brandl9e4ff752009-12-19 17:57:51 +0000327 q = queue.Queue()
Georg Brandld7413152009-10-11 21:25:26 +0000328
329 # Start a pool of 5 workers
330 for i in range(5):
331 t = threading.Thread(target=worker, name='worker %i' % (i+1))
332 t.start()
333
334 # Begin adding work to the queue
335 for i in range(50):
336 q.put(i)
337
338 # Give threads time to run
Georg Brandl9e4ff752009-12-19 17:57:51 +0000339 print('Main thread sleeping')
Georg Brandld7413152009-10-11 21:25:26 +0000340 time.sleep(5)
341
Ezio Melottib35480e2012-05-13 20:14:04 +0300342When run, this will produce the following output:
343
344.. code-block:: none
Georg Brandld7413152009-10-11 21:25:26 +0000345
346 Running worker
347 Running worker
348 Running worker
349 Running worker
350 Running worker
351 Main thread sleeping
Georg Brandl9e4ff752009-12-19 17:57:51 +0000352 Worker <Thread(worker 1, started 130283832797456)> running with argument 0
353 Worker <Thread(worker 2, started 130283824404752)> running with argument 1
354 Worker <Thread(worker 3, started 130283816012048)> running with argument 2
355 Worker <Thread(worker 4, started 130283807619344)> running with argument 3
356 Worker <Thread(worker 5, started 130283799226640)> running with argument 4
357 Worker <Thread(worker 1, started 130283832797456)> running with argument 5
Georg Brandld7413152009-10-11 21:25:26 +0000358 ...
359
Georg Brandl3539afd2012-05-30 22:03:20 +0200360Consult the module's documentation for more details; the :class:`~queue.Queue`
Ezio Melottib35480e2012-05-13 20:14:04 +0300361class provides a featureful interface.
Georg Brandld7413152009-10-11 21:25:26 +0000362
363
364What kinds of global value mutation are thread-safe?
365----------------------------------------------------
366
Antoine Pitrou11480b62011-02-05 11:18:34 +0000367A :term:`global interpreter lock` (GIL) is used internally to ensure that only one
Georg Brandld7413152009-10-11 21:25:26 +0000368thread runs in the Python VM at a time. In general, Python offers to switch
369among threads only between bytecode instructions; how frequently it switches can
Georg Brandl9e4ff752009-12-19 17:57:51 +0000370be set via :func:`sys.setswitchinterval`. Each bytecode instruction and
Georg Brandld7413152009-10-11 21:25:26 +0000371therefore all the C implementation code reached from each instruction is
372therefore atomic from the point of view of a Python program.
373
374In theory, this means an exact accounting requires an exact understanding of the
375PVM bytecode implementation. In practice, it means that operations on shared
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000376variables of built-in data types (ints, lists, dicts, etc) that "look atomic"
Georg Brandld7413152009-10-11 21:25:26 +0000377really are.
378
379For example, the following operations are all atomic (L, L1, L2 are lists, D,
380D1, D2 are dicts, x, y are objects, i, j are ints)::
381
382 L.append(x)
383 L1.extend(L2)
384 x = L[i]
385 x = L.pop()
386 L1[i:j] = L2
387 L.sort()
388 x = y
389 x.field = y
390 D[x] = y
391 D1.update(D2)
392 D.keys()
393
394These aren't::
395
396 i = i+1
397 L.append(L[-1])
398 L[i] = L[j]
399 D[x] = D[x] + 1
400
401Operations that replace other objects may invoke those other objects'
402:meth:`__del__` method when their reference count reaches zero, and that can
403affect things. This is especially true for the mass updates to dictionaries and
404lists. When in doubt, use a mutex!
405
406
407Can't we get rid of the Global Interpreter Lock?
408------------------------------------------------
409
Georg Brandl495f7b52009-10-27 15:28:25 +0000410.. XXX link to dbeazley's talk about GIL?
Georg Brandld7413152009-10-11 21:25:26 +0000411
Antoine Pitrou11480b62011-02-05 11:18:34 +0000412The :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's
Georg Brandld7413152009-10-11 21:25:26 +0000413deployment on high-end multiprocessor server machines, because a multi-threaded
414Python program effectively only uses one CPU, due to the insistence that
415(almost) all Python code can only run while the GIL is held.
416
417Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive
418patch set (the "free threading" patches) that removed the GIL and replaced it
Antoine Pitrou11480b62011-02-05 11:18:34 +0000419with fine-grained locking. Adam Olsen recently did a similar experiment
420in his `python-safethread <http://code.google.com/p/python-safethread/>`_
421project. Unfortunately, both experiments exhibited a sharp drop in single-thread
422performance (at least 30% slower), due to the amount of fine-grained locking
423necessary to compensate for the removal of the GIL.
Georg Brandld7413152009-10-11 21:25:26 +0000424
425This doesn't mean that you can't make good use of Python on multi-CPU machines!
426You just have to be creative with dividing the work up between multiple
Antoine Pitrou11480b62011-02-05 11:18:34 +0000427*processes* rather than multiple *threads*. The
428:class:`~concurrent.futures.ProcessPoolExecutor` class in the new
429:mod:`concurrent.futures` module provides an easy way of doing so; the
430:mod:`multiprocessing` module provides a lower-level API in case you want
431more control over dispatching of tasks.
432
433Judicious use of C extensions will also help; if you use a C extension to
434perform a time-consuming task, the extension can release the GIL while the
435thread of execution is in the C code and allow other threads to get some work
436done. Some standard library modules such as :mod:`zlib` and :mod:`hashlib`
437already do this.
Georg Brandld7413152009-10-11 21:25:26 +0000438
439It has been suggested that the GIL should be a per-interpreter-state lock rather
440than truly global; interpreters then wouldn't be able to share objects.
441Unfortunately, this isn't likely to happen either. It would be a tremendous
442amount of work, because many object implementations currently have global state.
443For example, small integers and short strings are cached; these caches would
444have to be moved to the interpreter state. Other object types have their own
445free list; these free lists would have to be moved to the interpreter state.
446And so on.
447
448And I doubt that it can even be done in finite time, because the same problem
449exists for 3rd party extensions. It is likely that 3rd party extensions are
450being written at a faster rate than you can convert them to store all their
451global state in the interpreter state.
452
453And finally, once you have multiple interpreters not sharing any state, what
454have you gained over running each interpreter in a separate process?
455
456
457Input and Output
458================
459
460How do I delete a file? (And other file questions...)
461-----------------------------------------------------
462
463Use ``os.remove(filename)`` or ``os.unlink(filename)``; for documentation, see
Georg Brandl9e4ff752009-12-19 17:57:51 +0000464the :mod:`os` module. The two functions are identical; :func:`~os.unlink` is simply
Georg Brandld7413152009-10-11 21:25:26 +0000465the name of the Unix system call for this function.
466
467To remove a directory, use :func:`os.rmdir`; use :func:`os.mkdir` to create one.
468``os.makedirs(path)`` will create any intermediate directories in ``path`` that
469don't exist. ``os.removedirs(path)`` will remove intermediate directories as
470long as they're empty; if you want to delete an entire directory tree and its
471contents, use :func:`shutil.rmtree`.
472
473To rename a file, use ``os.rename(old_path, new_path)``.
474
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000475To truncate a file, open it using ``f = open(filename, "rb+")``, and use
Georg Brandld7413152009-10-11 21:25:26 +0000476``f.truncate(offset)``; offset defaults to the current seek position. There's
Georg Brandl682d7e02010-10-06 10:26:05 +0000477also ``os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where
Ezio Melottib35480e2012-05-13 20:14:04 +0300478*fd* is the file descriptor (a small integer).
Georg Brandld7413152009-10-11 21:25:26 +0000479
480The :mod:`shutil` module also contains a number of functions to work on files
481including :func:`~shutil.copyfile`, :func:`~shutil.copytree`, and
482:func:`~shutil.rmtree`.
483
484
485How do I copy a file?
486---------------------
487
488The :mod:`shutil` module contains a :func:`~shutil.copyfile` function. Note
489that on MacOS 9 it doesn't copy the resource fork and Finder info.
490
491
492How do I read (or write) binary data?
493-------------------------------------
494
495To read or write complex binary data formats, it's best to use the :mod:`struct`
496module. It allows you to take a string containing binary data (usually numbers)
497and convert it to Python objects; and vice versa.
498
499For example, the following code reads two 2-byte integers and one 4-byte integer
500in big-endian format from a file::
501
502 import struct
503
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000504 with open(filename, "rb") as f:
505 s = f.read(8)
506 x, y, z = struct.unpack(">hhl", s)
Georg Brandld7413152009-10-11 21:25:26 +0000507
508The '>' in the format string forces big-endian data; the letter 'h' reads one
509"short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the
510string.
511
Ezio Melottib35480e2012-05-13 20:14:04 +0300512For data that is more regular (e.g. a homogeneous list of ints or floats),
Georg Brandld7413152009-10-11 21:25:26 +0000513you can also use the :mod:`array` module.
514
Ezio Melottib35480e2012-05-13 20:14:04 +0300515.. note::
516 To read and write binary data, it is mandatory to open the file in
517 binary mode (here, passing ``"rb"`` to :func:`open`). If you use
518 ``"r"`` instead (the default), the file will be open in text mode
519 and ``f.read()`` will return :class:`str` objects rather than
520 :class:`bytes` objects.
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000521
Georg Brandld7413152009-10-11 21:25:26 +0000522
523I can't seem to use os.read() on a pipe created with os.popen(); why?
524---------------------------------------------------------------------
525
526:func:`os.read` is a low-level function which takes a file descriptor, a small
527integer representing the opened file. :func:`os.popen` creates a high-level
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000528file object, the same type returned by the built-in :func:`open` function.
Ezio Melottib35480e2012-05-13 20:14:04 +0300529Thus, to read *n* bytes from a pipe *p* created with :func:`os.popen`, you need to
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000530use ``p.read(n)``.
Georg Brandld7413152009-10-11 21:25:26 +0000531
532
Georg Brandl9e4ff752009-12-19 17:57:51 +0000533.. XXX update to use subprocess. See the :ref:`subprocess-replacements` section.
Georg Brandld7413152009-10-11 21:25:26 +0000534
Georg Brandl9e4ff752009-12-19 17:57:51 +0000535 How do I run a subprocess with pipes connected to both input and output?
536 ------------------------------------------------------------------------
Georg Brandld7413152009-10-11 21:25:26 +0000537
Georg Brandl9e4ff752009-12-19 17:57:51 +0000538 Use the :mod:`popen2` module. For example::
Georg Brandld7413152009-10-11 21:25:26 +0000539
Georg Brandl9e4ff752009-12-19 17:57:51 +0000540 import popen2
541 fromchild, tochild = popen2.popen2("command")
542 tochild.write("input\n")
543 tochild.flush()
544 output = fromchild.readline()
Georg Brandld7413152009-10-11 21:25:26 +0000545
Georg Brandl9e4ff752009-12-19 17:57:51 +0000546 Warning: in general it is unwise to do this because you can easily cause a
547 deadlock where your process is blocked waiting for output from the child
548 while the child is blocked waiting for input from you. This can be caused
Ezio Melottib35480e2012-05-13 20:14:04 +0300549 by the parent expecting the child to output more text than it does or
550 by data being stuck in stdio buffers due to lack of flushing.
Georg Brandl9e4ff752009-12-19 17:57:51 +0000551 The Python parent can of course explicitly flush the data it sends to the
552 child before it reads any output, but if the child is a naive C program it
553 may have been written to never explicitly flush its output, even if it is
554 interactive, since flushing is normally automatic.
Georg Brandld7413152009-10-11 21:25:26 +0000555
Georg Brandl9e4ff752009-12-19 17:57:51 +0000556 Note that a deadlock is also possible if you use :func:`popen3` to read
557 stdout and stderr. If one of the two is too large for the internal buffer
558 (increasing the buffer size does not help) and you ``read()`` the other one
559 first, there is a deadlock, too.
Georg Brandld7413152009-10-11 21:25:26 +0000560
Georg Brandl9e4ff752009-12-19 17:57:51 +0000561 Note on a bug in popen2: unless your program calls ``wait()`` or
562 ``waitpid()``, finished child processes are never removed, and eventually
563 calls to popen2 will fail because of a limit on the number of child
564 processes. Calling :func:`os.waitpid` with the :data:`os.WNOHANG` option can
565 prevent this; a good place to insert such a call would be before calling
566 ``popen2`` again.
Georg Brandld7413152009-10-11 21:25:26 +0000567
Georg Brandl9e4ff752009-12-19 17:57:51 +0000568 In many cases, all you really need is to run some data through a command and
569 get the result back. Unless the amount of data is very large, the easiest
570 way to do this is to write it to a temporary file and run the command with
571 that temporary file as input. The standard module :mod:`tempfile` exports a
Ezio Melottib35480e2012-05-13 20:14:04 +0300572 :func:`~tempfile.mktemp` function to generate unique temporary file names. ::
Georg Brandld7413152009-10-11 21:25:26 +0000573
Georg Brandl9e4ff752009-12-19 17:57:51 +0000574 import tempfile
575 import os
Georg Brandld7413152009-10-11 21:25:26 +0000576
Georg Brandl9e4ff752009-12-19 17:57:51 +0000577 class Popen3:
578 """
579 This is a deadlock-safe version of popen that returns
580 an object with errorlevel, out (a string) and err (a string).
581 (capturestderr may not work under windows.)
582 Example: print(Popen3('grep spam','\n\nhere spam\n\n').out)
583 """
584 def __init__(self,command,input=None,capturestderr=None):
585 outfile=tempfile.mktemp()
586 command="( %s ) > %s" % (command,outfile)
587 if input:
588 infile=tempfile.mktemp()
589 open(infile,"w").write(input)
590 command=command+" <"+infile
591 if capturestderr:
592 errfile=tempfile.mktemp()
593 command=command+" 2>"+errfile
594 self.errorlevel=os.system(command) >> 8
595 self.out=open(outfile,"r").read()
596 os.remove(outfile)
597 if input:
598 os.remove(infile)
599 if capturestderr:
600 self.err=open(errfile,"r").read()
601 os.remove(errfile)
Georg Brandld7413152009-10-11 21:25:26 +0000602
Georg Brandl9e4ff752009-12-19 17:57:51 +0000603 Note that many interactive programs (e.g. vi) don't work well with pipes
604 substituted for standard input and output. You will have to use pseudo ttys
605 ("ptys") instead of pipes. Or you can use a Python interface to Don Libes'
606 "expect" library. A Python extension that interfaces to expect is called
607 "expy" and available from http://expectpy.sourceforge.net. A pure Python
608 solution that works like expect is `pexpect
609 <http://pypi.python.org/pypi/pexpect/>`_.
Georg Brandld7413152009-10-11 21:25:26 +0000610
611
612How do I access the serial (RS232) port?
613----------------------------------------
614
615For Win32, POSIX (Linux, BSD, etc.), Jython:
616
617 http://pyserial.sourceforge.net
618
619For Unix, see a Usenet post by Mitch Chapman:
620
621 http://groups.google.com/groups?selm=34A04430.CF9@ohioee.com
622
623
624Why doesn't closing sys.stdout (stdin, stderr) really close it?
625---------------------------------------------------------------
626
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000627Python :term:`file objects <file object>` are a high-level layer of
628abstraction on low-level C file descriptors.
Georg Brandld7413152009-10-11 21:25:26 +0000629
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000630For most file objects you create in Python via the built-in :func:`open`
631function, ``f.close()`` marks the Python file object as being closed from
632Python's point of view, and also arranges to close the underlying C file
633descriptor. This also happens automatically in ``f``'s destructor, when
634``f`` becomes garbage.
Georg Brandld7413152009-10-11 21:25:26 +0000635
636But stdin, stdout and stderr are treated specially by Python, because of the
637special status also given to them by C. Running ``sys.stdout.close()`` marks
638the Python-level file object as being closed, but does *not* close the
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000639associated C file descriptor.
Georg Brandld7413152009-10-11 21:25:26 +0000640
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000641To close the underlying C file descriptor for one of these three, you should
642first be sure that's what you really want to do (e.g., you may confuse
643extension modules trying to do I/O). If it is, use :func:`os.close`::
Georg Brandld7413152009-10-11 21:25:26 +0000644
Antoine Pitrou6a11a982010-09-15 10:08:31 +0000645 os.close(stdin.fileno())
646 os.close(stdout.fileno())
647 os.close(stderr.fileno())
648
649Or you can use the numeric constants 0, 1 and 2, respectively.
Georg Brandld7413152009-10-11 21:25:26 +0000650
651
652Network/Internet Programming
653============================
654
655What WWW tools are there for Python?
656------------------------------------
657
658See the chapters titled :ref:`internet` and :ref:`netdata` in the Library
659Reference Manual. Python has many modules that will help you build server-side
660and client-side web systems.
661
662.. XXX check if wiki page is still up to date
663
664A summary of available frameworks is maintained by Paul Boddie at
665http://wiki.python.org/moin/WebProgramming .
666
667Cameron Laird maintains a useful set of pages about Python web technologies at
668http://phaseit.net/claird/comp.lang.python/web_python.
669
670
671How can I mimic CGI form submission (METHOD=POST)?
672--------------------------------------------------
673
674I would like to retrieve web pages that are the result of POSTing a form. Is
675there existing code that would let me do this easily?
676
Georg Brandl9e4ff752009-12-19 17:57:51 +0000677Yes. Here's a simple example that uses urllib.request::
Georg Brandld7413152009-10-11 21:25:26 +0000678
679 #!/usr/local/bin/python
680
Georg Brandl9e4ff752009-12-19 17:57:51 +0000681 import urllib.request
Georg Brandld7413152009-10-11 21:25:26 +0000682
683 ### build the query string
684 qs = "First=Josephine&MI=Q&Last=Public"
685
686 ### connect and send the server a path
Georg Brandl9e4ff752009-12-19 17:57:51 +0000687 req = urllib.request.urlopen('http://www.some-server.out-there'
688 '/cgi-bin/some-cgi-script', data=qs)
689 msg, hdrs = req.read(), req.info()
Georg Brandld7413152009-10-11 21:25:26 +0000690
Georg Brandl54ebb782010-08-14 15:48:49 +0000691Note that in general for percent-encoded POST operations, query strings must be
Ezio Melottib35480e2012-05-13 20:14:04 +0300692quoted using :func:`urllib.parse.urlencode`. For example, to send
693``name=Guy Steele, Jr.``::
Georg Brandld7413152009-10-11 21:25:26 +0000694
Georg Brandl9e4ff752009-12-19 17:57:51 +0000695 >>> import urllib.parse
696 >>> urllib.parse.urlencode({'name': 'Guy Steele, Jr.'})
697 'name=Guy+Steele%2C+Jr.'
698
699.. seealso:: :ref:`urllib-howto` for extensive examples.
Georg Brandld7413152009-10-11 21:25:26 +0000700
701
702What module should I use to help with generating HTML?
703------------------------------------------------------
704
705.. XXX add modern template languages
706
Ezio Melottib35480e2012-05-13 20:14:04 +0300707You can find a collection of useful links on the `Web Programming wiki page
708<http://wiki.python.org/moin/WebProgramming>`_.
Georg Brandld7413152009-10-11 21:25:26 +0000709
710
711How do I send mail from a Python script?
712----------------------------------------
713
714Use the standard library module :mod:`smtplib`.
715
716Here's a very simple interactive mail sender that uses it. This method will
717work on any host that supports an SMTP listener. ::
718
719 import sys, smtplib
720
Georg Brandl9e4ff752009-12-19 17:57:51 +0000721 fromaddr = input("From: ")
722 toaddrs = input("To: ").split(',')
723 print("Enter message, end with ^D:")
Georg Brandld7413152009-10-11 21:25:26 +0000724 msg = ''
725 while True:
726 line = sys.stdin.readline()
727 if not line:
728 break
729 msg += line
730
731 # The actual mail send
732 server = smtplib.SMTP('localhost')
733 server.sendmail(fromaddr, toaddrs, msg)
734 server.quit()
735
736A Unix-only alternative uses sendmail. The location of the sendmail program
Ezio Melottib35480e2012-05-13 20:14:04 +0300737varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes
Georg Brandld7413152009-10-11 21:25:26 +0000738``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's
739some sample code::
740
Georg Brandl9e4ff752009-12-19 17:57:51 +0000741 SENDMAIL = "/usr/sbin/sendmail" # sendmail location
Georg Brandld7413152009-10-11 21:25:26 +0000742 import os
743 p = os.popen("%s -t -i" % SENDMAIL, "w")
744 p.write("To: receiver@example.com\n")
745 p.write("Subject: test\n")
Georg Brandl9e4ff752009-12-19 17:57:51 +0000746 p.write("\n") # blank line separating headers from body
Georg Brandld7413152009-10-11 21:25:26 +0000747 p.write("Some text\n")
748 p.write("some more text\n")
749 sts = p.close()
750 if sts != 0:
Georg Brandl9e4ff752009-12-19 17:57:51 +0000751 print("Sendmail exit status", sts)
Georg Brandld7413152009-10-11 21:25:26 +0000752
753
754How do I avoid blocking in the connect() method of a socket?
755------------------------------------------------------------
756
Antoine Pitrou70957212011-02-05 11:24:15 +0000757The :mod:`select` module is commonly used to help with asynchronous I/O on
758sockets.
Georg Brandld7413152009-10-11 21:25:26 +0000759
760To prevent the TCP connect from blocking, you can set the socket to non-blocking
761mode. Then when you do the ``connect()``, you will either connect immediately
762(unlikely) or get an exception that contains the error number as ``.errno``.
763``errno.EINPROGRESS`` indicates that the connection is in progress, but hasn't
764finished yet. Different OSes will return different values, so you're going to
765have to check what's returned on your system.
766
767You can use the ``connect_ex()`` method to avoid creating an exception. It will
768just return the errno value. To poll, you can call ``connect_ex()`` again later
Georg Brandl9e4ff752009-12-19 17:57:51 +0000769-- ``0`` or ``errno.EISCONN`` indicate that you're connected -- or you can pass this
Georg Brandld7413152009-10-11 21:25:26 +0000770socket to select to check if it's writable.
771
Antoine Pitrou70957212011-02-05 11:24:15 +0000772.. note::
773 The :mod:`asyncore` module presents a framework-like approach to the problem
774 of writing non-blocking networking code.
775 The third-party `Twisted <http://twistedmatrix.com/>`_ library is
776 a popular and feature-rich alternative.
777
Georg Brandld7413152009-10-11 21:25:26 +0000778
779Databases
780=========
781
782Are there any interfaces to database packages in Python?
783--------------------------------------------------------
784
785Yes.
786
Georg Brandld404fa62009-10-13 16:55:12 +0000787Interfaces to disk-based hashes such as :mod:`DBM <dbm.ndbm>` and :mod:`GDBM
788<dbm.gnu>` are also included with standard Python. There is also the
789:mod:`sqlite3` module, which provides a lightweight disk-based relational
790database.
Georg Brandld7413152009-10-11 21:25:26 +0000791
792Support for most relational databases is available. See the
793`DatabaseProgramming wiki page
794<http://wiki.python.org/moin/DatabaseProgramming>`_ for details.
795
796
797How do you implement persistent objects in Python?
798--------------------------------------------------
799
800The :mod:`pickle` library module solves this in a very general way (though you
801still can't store things like open files, sockets or windows), and the
802:mod:`shelve` library module uses pickle and (g)dbm to create persistent
Georg Brandld404fa62009-10-13 16:55:12 +0000803mappings containing arbitrary Python objects.
Georg Brandld7413152009-10-11 21:25:26 +0000804
Georg Brandld7413152009-10-11 21:25:26 +0000805
Georg Brandld7413152009-10-11 21:25:26 +0000806Mathematics and Numerics
807========================
808
809How do I generate random numbers in Python?
810-------------------------------------------
811
812The standard module :mod:`random` implements a random number generator. Usage
813is simple::
814
815 import random
816 random.random()
817
818This returns a random floating point number in the range [0, 1).
819
820There are also many other specialized generators in this module, such as:
821
822* ``randrange(a, b)`` chooses an integer in the range [a, b).
823* ``uniform(a, b)`` chooses a floating point number in the range [a, b).
824* ``normalvariate(mean, sdev)`` samples the normal (Gaussian) distribution.
825
826Some higher-level functions operate on sequences directly, such as:
827
828* ``choice(S)`` chooses random element from a given sequence
829* ``shuffle(L)`` shuffles a list in-place, i.e. permutes it randomly
830
831There's also a ``Random`` class you can instantiate to create independent
832multiple random number generators.