summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/faq%2Flibrary.html
blob: a62e9d0f31b72f2bfb87bbaf3494e72fda3d98e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
 <h1>Library and Extension FAQ</h1>   <ul> <li>
<p><a class="reference internal" href="#general-library-questions" id="id2">General Library Questions</a></p> <ul> <li><a class="reference internal" href="#how-do-i-find-a-module-or-application-to-perform-task-x" id="id3">How do I find a module or application to perform task X?</a></li> <li><a class="reference internal" href="#where-is-the-math-py-socket-py-regex-py-etc-source-file" id="id4">Where is the math.py (socket.py, regex.py, etc.) source file?</a></li> <li><a class="reference internal" href="#how-do-i-make-a-python-script-executable-on-unix" id="id5">How do I make a Python script executable on Unix?</a></li> <li><a class="reference internal" href="#is-there-a-curses-termcap-package-for-python" id="id6">Is there a curses/termcap package for Python?</a></li> <li><a class="reference internal" href="#is-there-an-equivalent-to-c-s-onexit-in-python" id="id7">Is there an equivalent to C’s onexit() in Python?</a></li> <li><a class="reference internal" href="#why-don-t-my-signal-handlers-work" id="id8">Why don’t my signal handlers work?</a></li> </ul> </li> <li>
<p><a class="reference internal" href="#common-tasks" id="id9">Common tasks</a></p> <ul> <li><a class="reference internal" href="#how-do-i-test-a-python-program-or-component" id="id10">How do I test a Python program or component?</a></li> <li><a class="reference internal" href="#how-do-i-create-documentation-from-doc-strings" id="id11">How do I create documentation from doc strings?</a></li> <li><a class="reference internal" href="#how-do-i-get-a-single-keypress-at-a-time" id="id12">How do I get a single keypress at a time?</a></li> </ul> </li> <li>
<p><a class="reference internal" href="#threads" id="id13">Threads</a></p> <ul> <li><a class="reference internal" href="#how-do-i-program-using-threads" id="id14">How do I program using threads?</a></li> <li><a class="reference internal" href="#none-of-my-threads-seem-to-run-why" id="id15">None of my threads seem to run: why?</a></li> <li><a class="reference internal" href="#how-do-i-parcel-out-work-among-a-bunch-of-worker-threads" id="id16">How do I parcel out work among a bunch of worker threads?</a></li> <li><a class="reference internal" href="#what-kinds-of-global-value-mutation-are-thread-safe" id="id17">What kinds of global value mutation are thread-safe?</a></li> <li><a class="reference internal" href="#can-t-we-get-rid-of-the-global-interpreter-lock" id="id18">Can’t we get rid of the Global Interpreter Lock?</a></li> </ul> </li> <li>
<p><a class="reference internal" href="#input-and-output" id="id19">Input and Output</a></p> <ul> <li><a class="reference internal" href="#how-do-i-delete-a-file-and-other-file-questions" id="id20">How do I delete a file? (And other file questions…)</a></li> <li><a class="reference internal" href="#how-do-i-copy-a-file" id="id21">How do I copy a file?</a></li> <li><a class="reference internal" href="#how-do-i-read-or-write-binary-data" id="id22">How do I read (or write) binary data?</a></li> <li><a class="reference internal" href="#i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why" id="id23">I can’t seem to use os.read() on a pipe created with os.popen(); why?</a></li> <li><a class="reference internal" href="#how-do-i-access-the-serial-rs232-port" id="id24">How do I access the serial (RS232) port?</a></li> <li><a class="reference internal" href="#why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it" id="id25">Why doesn’t closing sys.stdout (stdin, stderr) really close it?</a></li> </ul> </li> <li>
<p><a class="reference internal" href="#network-internet-programming" id="id26">Network/Internet Programming</a></p> <ul> <li><a class="reference internal" href="#what-www-tools-are-there-for-python" id="id27">What WWW tools are there for Python?</a></li> <li><a class="reference internal" href="#how-can-i-mimic-cgi-form-submission-method-post" id="id28">How can I mimic CGI form submission (METHOD=POST)?</a></li> <li><a class="reference internal" href="#what-module-should-i-use-to-help-with-generating-html" id="id29">What module should I use to help with generating HTML?</a></li> <li><a class="reference internal" href="#how-do-i-send-mail-from-a-python-script" id="id30">How do I send mail from a Python script?</a></li> <li><a class="reference internal" href="#how-do-i-avoid-blocking-in-the-connect-method-of-a-socket" id="id31">How do I avoid blocking in the connect() method of a socket?</a></li> </ul> </li> <li>
<p><a class="reference internal" href="#databases" id="id32">Databases</a></p> <ul> <li><a class="reference internal" href="#are-there-any-interfaces-to-database-packages-in-python" id="id33">Are there any interfaces to database packages in Python?</a></li> <li><a class="reference internal" href="#how-do-you-implement-persistent-objects-in-python" id="id34">How do you implement persistent objects in Python?</a></li> </ul> </li> <li>
<p><a class="reference internal" href="#mathematics-and-numerics" id="id35">Mathematics and Numerics</a></p> <ul> <li><a class="reference internal" href="#how-do-i-generate-random-numbers-in-python" id="id36">How do I generate random numbers in Python?</a></li> </ul> </li> </ul>
<ul class="simple">  </ul>  <section id="general-library-questions"> <h2>General Library Questions</h2> <section id="how-do-i-find-a-module-or-application-to-perform-task-x"> <h3>How do I find a module or application to perform task X?</h3> <p>Check <a class="reference internal" href="../library/index#library-index"><span class="std std-ref">the Library Reference</span></a> to see if there’s a relevant standard library module. (Eventually you’ll learn what’s in the standard library and will be able to skip this step.)</p> <p>For third-party packages, search the <a class="reference external" href="https://pypi.org">Python Package Index</a> or try <a class="reference external" href="https://www.google.com">Google</a> or another web search engine. Searching for “Python” plus a keyword or two for your topic of interest will usually find something helpful.</p> </section> <section id="where-is-the-math-py-socket-py-regex-py-etc-source-file"> <h3>Where is the math.py (socket.py, regex.py, etc.) source file?</h3> <p>If you can’t find a source file for a module it may be a built-in or dynamically loaded module implemented in C, C++ or other compiled language. In this case you may not have the source file or it may be something like <code>mathmodule.c</code>, somewhere in a C source directory (not on the Python Path).</p> <p>There are (at least) three kinds of modules in Python:</p> <ol class="arabic"> <li>modules written in Python (.py);</li> <li>modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);</li> <li>
<p>modules written in C and linked with the interpreter; to get a list of these, type:</p> <pre data-language="python">import sys
print(sys.builtin_module_names)
</pre> </li> </ol> </section> <section id="how-do-i-make-a-python-script-executable-on-unix"> <h3>How do I make a Python script executable on Unix?</h3> <p>You need to do two things: the script file’s mode must be executable and the first line must begin with <code>#!</code> followed by the path of the Python interpreter.</p> <p>The first is done by executing <code>chmod +x scriptfile</code> or perhaps <code>chmod 755
scriptfile</code>.</p> <p>The second can be done in a number of ways. The most straightforward way is to write</p> <pre data-language="python">#!/usr/local/bin/python
</pre> <p>as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform.</p> <p>If you would like the script to be independent of where the Python interpreter lives, you can use the <strong class="program">env</strong> program. Almost all Unix variants support the following, assuming the Python interpreter is in a directory on the user’s <span class="target" id="index-0"></span><code>PATH</code>:</p> <pre data-language="python">#!/usr/bin/env python
</pre> <p><em>Don’t</em> do this for CGI scripts. The <span class="target" id="index-1"></span><code>PATH</code> variable for CGI scripts is often very minimal, so you need to use the actual absolute pathname of the interpreter.</p> <p>Occasionally, a user’s environment is so full that the <strong class="program">/usr/bin/env</strong> program fails; or there’s no env program at all. In that case, you can try the following hack (due to Alex Rezinsky):</p> <pre data-language="sh">#! /bin/sh
""":"
exec python $0 ${1+"$@"}
"""
</pre> <p>The minor disadvantage is that this defines the script’s __doc__ string. However, you can fix that by adding</p> <pre data-language="python">__doc__ = """...Whatever..."""
</pre> </section> <section id="is-there-a-curses-termcap-package-for-python"> <h3>Is there a curses/termcap package for Python?</h3> <p>For Unix variants: The standard Python source distribution comes with a curses module in the <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Modules">Modules</a> subdirectory, though it’s not compiled by default. (Note that this is not available in the Windows distribution – there is no curses module for Windows.)</p> <p>The <a class="reference internal" href="../library/curses#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code>curses</code></a> module supports basic curses features as well as many additional functions from ncurses and SYSV curses such as colour, alternative character set support, pads, and mouse support. This means the module isn’t compatible with operating systems that only have BSD curses, but there don’t seem to be any currently maintained OSes that fall into this category.</p> </section> <section id="is-there-an-equivalent-to-c-s-onexit-in-python"> <h3>Is there an equivalent to C’s onexit() in Python?</h3> <p>The <a class="reference internal" href="../library/atexit#module-atexit" title="atexit: Register and execute cleanup functions."><code>atexit</code></a> module provides a register function that is similar to C’s <code>onexit()</code>.</p> </section> <section id="why-don-t-my-signal-handlers-work"> <h3>Why don’t my signal handlers work?</h3> <p>The most common problem is that the signal handler is declared with the wrong argument list. It is called as</p> <pre data-language="python">handler(signum, frame)
</pre> <p>so it should be declared with two parameters:</p> <pre data-language="python">def handler(signum, frame):
    ...
</pre> </section> </section> <section id="common-tasks"> <h2>Common tasks</h2> <section id="how-do-i-test-a-python-program-or-component"> <h3>How do I test a Python program or component?</h3> <p>Python comes with two testing frameworks. The <a class="reference internal" href="../library/doctest#module-doctest" title="doctest: Test pieces of code within docstrings."><code>doctest</code></a> module finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring.</p> <p>The <a class="reference internal" href="../library/unittest#module-unittest" title="unittest: Unit testing framework for Python."><code>unittest</code></a> module is a fancier testing framework modelled on Java and Smalltalk testing frameworks.</p> <p>To make testing easier, you should use good modular design in your program. Your program should have almost all functionality encapsulated in either functions or class methods – and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do.</p> <p>The “global main logic” of your program may be as simple as</p> <pre data-language="python">if __name__ == "__main__":
    main_logic()
</pre> <p>at the bottom of the main module of your program.</p> <p>Once your program is organized as a tractable collection of function and class behaviours, you should write test functions that exercise the behaviours. A test 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’s surprisingly easy. You can make coding much more pleasant and fun by writing your test functions in parallel with the “production code”, since this makes it easy to find bugs and even design flaws earlier.</p> <p>“Support modules” that are not intended to be the main module of a program may include a self-test of the module.</p> <pre data-language="python">if __name__ == "__main__":
    self_test()
</pre> <p>Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using “fake” interfaces implemented in Python.</p> </section> <section id="how-do-i-create-documentation-from-doc-strings"> <h3>How do I create documentation from doc strings?</h3> <p>The <a class="reference internal" href="../library/pydoc#module-pydoc" title="pydoc: Documentation generator and online help system."><code>pydoc</code></a> module can create HTML from the doc strings in your Python source code. An alternative for creating API documentation purely from docstrings is <a class="reference external" href="https://epydoc.sourceforge.net/">epydoc</a>. <a class="reference external" href="https://www.sphinx-doc.org">Sphinx</a> can also include docstring content.</p> </section> <section id="how-do-i-get-a-single-keypress-at-a-time"> <h3>How do I get a single keypress at a time?</h3> <p>For Unix variants there are several solutions. It’s straightforward to do this using curses, but curses is a fairly large module to learn.</p> </section> </section> <section id="threads"> <h2>Threads</h2> <section id="how-do-i-program-using-threads"> <h3>How do I program using threads?</h3> <p>Be sure to use the <a class="reference internal" href="../library/threading#module-threading" title="threading: Thread-based parallelism."><code>threading</code></a> module and not the <a class="reference internal" href="../library/_thread#module-_thread" title="_thread: Low-level threading API."><code>_thread</code></a> module. The <a class="reference internal" href="../library/threading#module-threading" title="threading: Thread-based parallelism."><code>threading</code></a> module builds convenient abstractions on top of the low-level primitives provided by the <a class="reference internal" href="../library/_thread#module-_thread" title="_thread: Low-level threading API."><code>_thread</code></a> module.</p> </section> <section id="none-of-my-threads-seem-to-run-why"> <h3>None of my threads seem to run: why?</h3> <p>As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work.</p> <p>A simple fix is to add a sleep to the end of the program that’s long enough for all the threads to finish:</p> <pre data-language="python">import threading, time

def thread_task(name, n):
    for i in range(n):
        print(name, i)

for i in range(10):
    T = threading.Thread(target=thread_task, args=(str(i), i))
    T.start()

time.sleep(10)  # &lt;---------------------------!
</pre> <p>But now (on many platforms) the threads don’t run in parallel, but appear to run sequentially, one at a time! The reason is that the OS thread scheduler doesn’t start a new thread until the previous thread is blocked.</p> <p>A simple fix is to add a tiny sleep to the start of the run function:</p> <pre data-language="python">def thread_task(name, n):
    time.sleep(0.001)  # &lt;--------------------!
    for i in range(n):
        print(name, i)

for i in range(10):
    T = threading.Thread(target=thread_task, args=(str(i), i))
    T.start()

time.sleep(10)
</pre> <p>Instead of trying to guess a good delay value for <a class="reference internal" href="../library/time#time.sleep" title="time.sleep"><code>time.sleep()</code></a>, it’s better to use some kind of semaphore mechanism. One idea is to use the <a class="reference internal" href="../library/queue#module-queue" title="queue: A synchronized queue class."><code>queue</code></a> module to create a queue object, let each thread append a token to the queue when it finishes, and let the main thread read as many tokens from the queue as there are threads.</p> </section> <section id="how-do-i-parcel-out-work-among-a-bunch-of-worker-threads"> <h3>How do I parcel out work among a bunch of worker threads?</h3> <p>The easiest way is to use the <a class="reference internal" href="../library/concurrent.futures#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code>concurrent.futures</code></a> module, especially the <a class="reference internal" href="../library/concurrent.futures#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code>ThreadPoolExecutor</code></a> class.</p> <p>Or, if you want fine control over the dispatching algorithm, you can write your own logic manually. Use the <a class="reference internal" href="../library/queue#module-queue" title="queue: A synchronized queue class."><code>queue</code></a> module to create a queue containing a list of jobs. The <a class="reference internal" href="../library/queue#queue.Queue" title="queue.Queue"><code>Queue</code></a> class maintains a list of objects and has a <code>.put(obj)</code> method that adds items to the queue and a <code>.get()</code> method to return them. The class will take care of the locking necessary to ensure that each job is handed out exactly once.</p> <p>Here’s a trivial example:</p> <pre data-language="python">import threading, queue, time

# The worker thread gets jobs off the queue.  When the queue is empty, it
# assumes there will be no more work and exits.
# (Realistically workers will run until terminated.)
def worker():
    print('Running worker')
    time.sleep(0.1)
    while True:
        try:
            arg = q.get(block=False)
        except queue.Empty:
            print('Worker', threading.current_thread(), end=' ')
            print('queue empty')
            break
        else:
            print('Worker', threading.current_thread(), end=' ')
            print('running with argument', arg)
            time.sleep(0.5)

# Create queue
q = queue.Queue()

# Start a pool of 5 workers
for i in range(5):
    t = threading.Thread(target=worker, name='worker %i' % (i+1))
    t.start()

# Begin adding work to the queue
for i in range(50):
    q.put(i)

# Give threads time to run
print('Main thread sleeping')
time.sleep(5)
</pre> <p>When run, this will produce the following output:</p> <pre data-language="none">Running worker
Running worker
Running worker
Running worker
Running worker
Main thread sleeping
Worker &lt;Thread(worker 1, started 130283832797456)&gt; running with argument 0
Worker &lt;Thread(worker 2, started 130283824404752)&gt; running with argument 1
Worker &lt;Thread(worker 3, started 130283816012048)&gt; running with argument 2
Worker &lt;Thread(worker 4, started 130283807619344)&gt; running with argument 3
Worker &lt;Thread(worker 5, started 130283799226640)&gt; running with argument 4
Worker &lt;Thread(worker 1, started 130283832797456)&gt; running with argument 5
...
</pre> <p>Consult the module’s documentation for more details; the <a class="reference internal" href="../library/queue#queue.Queue" title="queue.Queue"><code>Queue</code></a> class provides a featureful interface.</p> </section> <section id="what-kinds-of-global-value-mutation-are-thread-safe"> <h3>What kinds of global value mutation are thread-safe?</h3> <p>A <a class="reference internal" href="../glossary#term-global-interpreter-lock"><span class="xref std std-term">global interpreter lock</span></a> (GIL) is used internally to ensure that only one thread runs in the Python VM at a time. In general, Python offers to switch among threads only between bytecode instructions; how frequently it switches can be set via <a class="reference internal" href="../library/sys#sys.setswitchinterval" title="sys.setswitchinterval"><code>sys.setswitchinterval()</code></a>. Each bytecode instruction and therefore all the C implementation code reached from each instruction is therefore atomic from the point of view of a Python program.</p> <p>In theory, this means an exact accounting requires an exact understanding of the PVM bytecode implementation. In practice, it means that operations on shared variables of built-in data types (ints, lists, dicts, etc) that “look atomic” really are.</p> <p>For example, the following operations are all atomic (L, L1, L2 are lists, D, D1, D2 are dicts, x, y are objects, i, j are ints):</p> <pre data-language="python">L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()
</pre> <p>These aren’t:</p> <pre data-language="python">i = i+1
L.append(L[-1])
L[i] = L[j]
D[x] = D[x] + 1
</pre> <p>Operations that replace other objects may invoke those other objects’ <a class="reference internal" href="../reference/datamodel#object.__del__" title="object.__del__"><code>__del__()</code></a> method when their reference count reaches zero, and that can affect things. This is especially true for the mass updates to dictionaries and lists. When in doubt, use a mutex!</p> </section> <section id="can-t-we-get-rid-of-the-global-interpreter-lock"> <h3>Can’t we get rid of the Global Interpreter Lock?</h3> <p>The <a class="reference internal" href="../glossary#term-global-interpreter-lock"><span class="xref std std-term">global interpreter lock</span></a> (GIL) is often seen as a hindrance to Python’s deployment on high-end multiprocessor server machines, because a multi-threaded Python program effectively only uses one CPU, due to the insistence that (almost) all Python code can only run while the GIL is held.</p> <p>Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive patch set (the “free threading” patches) that removed the GIL and replaced it with fine-grained locking. Adam Olsen recently did a similar experiment in his <a class="reference external" href="https://code.google.com/archive/p/python-safethread">python-safethread</a> project. Unfortunately, both experiments exhibited a sharp drop in single-thread performance (at least 30% slower), due to the amount of fine-grained locking necessary to compensate for the removal of the GIL.</p> <p>This doesn’t mean that you can’t make good use of Python on multi-CPU machines! You just have to be creative with dividing the work up between multiple <em>processes</em> rather than multiple <em>threads</em>. The <a class="reference internal" href="../library/concurrent.futures#concurrent.futures.ProcessPoolExecutor" title="concurrent.futures.ProcessPoolExecutor"><code>ProcessPoolExecutor</code></a> class in the new <a class="reference internal" href="../library/concurrent.futures#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code>concurrent.futures</code></a> module provides an easy way of doing so; the <a class="reference internal" href="../library/multiprocessing#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code>multiprocessing</code></a> module provides a lower-level API in case you want more control over dispatching of tasks.</p> <p>Judicious use of C extensions will also help; if you use a C extension to perform a time-consuming task, the extension can release the GIL while the thread of execution is in the C code and allow other threads to get some work done. Some standard library modules such as <a class="reference internal" href="../library/zlib#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code>zlib</code></a> and <a class="reference internal" href="../library/hashlib#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code>hashlib</code></a> already do this.</p> <p>It has been suggested that the GIL should be a per-interpreter-state lock rather than truly global; interpreters then wouldn’t be able to share objects. Unfortunately, this isn’t likely to happen either. It would be a tremendous amount of work, because many object implementations currently have global state. For example, small integers and short strings are cached; these caches would have to be moved to the interpreter state. Other object types have their own free list; these free lists would have to be moved to the interpreter state. And so on.</p> <p>And I doubt that it can even be done in finite time, because the same problem exists for 3rd party extensions. It is likely that 3rd party extensions are being written at a faster rate than you can convert them to store all their global state in the interpreter state.</p> <p>And finally, once you have multiple interpreters not sharing any state, what have you gained over running each interpreter in a separate process?</p> </section> </section> <section id="input-and-output"> <h2>Input and Output</h2> <section id="how-do-i-delete-a-file-and-other-file-questions"> <h3>How do I delete a file? (And other file questions…)</h3> <p>Use <code>os.remove(filename)</code> or <code>os.unlink(filename)</code>; for documentation, see the <a class="reference internal" href="../library/os#module-os" title="os: Miscellaneous operating system interfaces."><code>os</code></a> module. The two functions are identical; <a class="reference internal" href="../library/os#os.unlink" title="os.unlink"><code>unlink()</code></a> is simply the name of the Unix system call for this function.</p> <p>To remove a directory, use <a class="reference internal" href="../library/os#os.rmdir" title="os.rmdir"><code>os.rmdir()</code></a>; use <a class="reference internal" href="../library/os#os.mkdir" title="os.mkdir"><code>os.mkdir()</code></a> to create one. <code>os.makedirs(path)</code> will create any intermediate directories in <code>path</code> that don’t exist. <code>os.removedirs(path)</code> will remove intermediate directories as long as they’re empty; if you want to delete an entire directory tree and its contents, use <a class="reference internal" href="../library/shutil#shutil.rmtree" title="shutil.rmtree"><code>shutil.rmtree()</code></a>.</p> <p>To rename a file, use <code>os.rename(old_path, new_path)</code>.</p> <p>To truncate a file, open it using <code>f = open(filename, "rb+")</code>, and use <code>f.truncate(offset)</code>; offset defaults to the current seek position. There’s also <code>os.ftruncate(fd, offset)</code> for files opened with <a class="reference internal" href="../library/os#os.open" title="os.open"><code>os.open()</code></a>, where <em>fd</em> is the file descriptor (a small integer).</p> <p>The <a class="reference internal" href="../library/shutil#module-shutil" title="shutil: High-level file operations, including copying."><code>shutil</code></a> module also contains a number of functions to work on files including <a class="reference internal" href="../library/shutil#shutil.copyfile" title="shutil.copyfile"><code>copyfile()</code></a>, <a class="reference internal" href="../library/shutil#shutil.copytree" title="shutil.copytree"><code>copytree()</code></a>, and <a class="reference internal" href="../library/shutil#shutil.rmtree" title="shutil.rmtree"><code>rmtree()</code></a>.</p> </section> <section id="how-do-i-copy-a-file"> <h3>How do I copy a file?</h3> <p>The <a class="reference internal" href="../library/shutil#module-shutil" title="shutil: High-level file operations, including copying."><code>shutil</code></a> module contains a <a class="reference internal" href="../library/shutil#shutil.copyfile" title="shutil.copyfile"><code>copyfile()</code></a> function. Note that on Windows NTFS volumes, it does not copy <a class="reference external" href="https://en.wikipedia.org/wiki/NTFS#Alternate_data_stream_(ADS)">alternate data streams</a> nor <a class="reference external" href="https://en.wikipedia.org/wiki/Resource_fork">resource forks</a> on macOS HFS+ volumes, though both are now rarely used. It also doesn’t copy file permissions and metadata, though using <a class="reference internal" href="../library/shutil#shutil.copy2" title="shutil.copy2"><code>shutil.copy2()</code></a> instead will preserve most (though not all) of it.</p> </section> <section id="how-do-i-read-or-write-binary-data"> <h3>How do I read (or write) binary data?</h3> <p>To read or write complex binary data formats, it’s best to use the <a class="reference internal" href="../library/struct#module-struct" title="struct: Interpret bytes as packed binary data."><code>struct</code></a> module. It allows you to take a string containing binary data (usually numbers) and convert it to Python objects; and vice versa.</p> <p>For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file:</p> <pre data-language="python">import struct

with open(filename, "rb") as f:
    s = f.read(8)
    x, y, z = struct.unpack("&gt;hhl", s)
</pre> <p>The ‘&gt;’ in the format string forces big-endian data; the letter ‘h’ reads one “short integer” (2 bytes), and ‘l’ reads one “long integer” (4 bytes) from the string.</p> <p>For data that is more regular (e.g. a homogeneous list of ints or floats), you can also use the <a class="reference internal" href="../library/array#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code>array</code></a> module.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>To read and write binary data, it is mandatory to open the file in binary mode (here, passing <code>"rb"</code> to <a class="reference internal" href="../library/functions#open" title="open"><code>open()</code></a>). If you use <code>"r"</code> instead (the default), the file will be open in text mode and <code>f.read()</code> will return <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a> objects rather than <a class="reference internal" href="../library/stdtypes#bytes" title="bytes"><code>bytes</code></a> objects.</p> </div> </section> <section id="i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why"> <h3>I can’t seem to use os.read() on a pipe created with os.popen(); why?</h3> <p><a class="reference internal" href="../library/os#os.read" title="os.read"><code>os.read()</code></a> is a low-level function which takes a file descriptor, a small integer representing the opened file. <a class="reference internal" href="../library/os#os.popen" title="os.popen"><code>os.popen()</code></a> creates a high-level file object, the same type returned by the built-in <a class="reference internal" href="../library/functions#open" title="open"><code>open()</code></a> function. Thus, to read <em>n</em> bytes from a pipe <em>p</em> created with <a class="reference internal" href="../library/os#os.popen" title="os.popen"><code>os.popen()</code></a>, you need to use <code>p.read(n)</code>.</p> </section> <section id="how-do-i-access-the-serial-rs232-port"> <h3>How do I access the serial (RS232) port?</h3> <p>For Win32, OSX, Linux, BSD, Jython, IronPython:</p>  <p><a class="reference external" href="https://pypi.org/project/pyserial/">https://pypi.org/project/pyserial/</a></p>  <p>For Unix, see a Usenet post by Mitch Chapman:</p>  <p><a class="reference external" href="https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com">https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com</a></p>  </section> <section id="why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it"> <h3>Why doesn’t closing sys.stdout (stdin, stderr) really close it?</h3> <p>Python <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file objects</span></a> are a high-level layer of abstraction on low-level C file descriptors.</p> <p>For most file objects you create in Python via the built-in <a class="reference internal" href="../library/functions#open" title="open"><code>open()</code></a> function, <code>f.close()</code> marks the Python file object as being closed from Python’s point of view, and also arranges to close the underlying C file descriptor. This also happens automatically in <code>f</code>’s destructor, when <code>f</code> becomes garbage.</p> <p>But stdin, stdout and stderr are treated specially by Python, because of the special status also given to them by C. Running <code>sys.stdout.close()</code> marks the Python-level file object as being closed, but does <em>not</em> close the associated C file descriptor.</p> <p>To close the underlying C file descriptor for one of these three, you should first be sure that’s what you really want to do (e.g., you may confuse extension modules trying to do I/O). If it is, use <a class="reference internal" href="../library/os#os.close" title="os.close"><code>os.close()</code></a>:</p> <pre data-language="python">os.close(stdin.fileno())
os.close(stdout.fileno())
os.close(stderr.fileno())
</pre> <p>Or you can use the numeric constants 0, 1 and 2, respectively.</p> </section> </section> <section id="network-internet-programming"> <h2>Network/Internet Programming</h2> <section id="what-www-tools-are-there-for-python"> <h3>What WWW tools are there for Python?</h3> <p>See the chapters titled <a class="reference internal" href="../library/internet#internet"><span class="std std-ref">Internet Protocols and Support</span></a> and <a class="reference internal" href="../library/netdata#netdata"><span class="std std-ref">Internet Data Handling</span></a> in the Library Reference Manual. Python has many modules that will help you build server-side and client-side web systems.</p> <p>A summary of available frameworks is maintained by Paul Boddie at <a class="reference external" href="https://wiki.python.org/moin/WebProgramming">https://wiki.python.org/moin/WebProgramming</a>.</p> <p>Cameron Laird maintains a useful set of pages about Python web technologies at <a class="reference external" href="https://web.archive.org/web/20210224183619/http://phaseit.net/claird/comp.lang.python/web_python">https://web.archive.org/web/20210224183619/http://phaseit.net/claird/comp.lang.python/web_python</a>.</p> </section> <section id="how-can-i-mimic-cgi-form-submission-method-post"> <h3>How can I mimic CGI form submission (METHOD=POST)?</h3> <p>I would like to retrieve web pages that are the result of POSTing a form. Is there existing code that would let me do this easily?</p> <p>Yes. Here’s a simple example that uses <a class="reference internal" href="../library/urllib.request#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code>urllib.request</code></a>:</p> <pre data-language="python">#!/usr/local/bin/python

import urllib.request

# build the query string
qs = "First=Josephine&amp;MI=Q&amp;Last=Public"

# connect and send the server a path
req = urllib.request.urlopen('http://www.some-server.out-there'
                             '/cgi-bin/some-cgi-script', data=qs)
with req:
    msg, hdrs = req.read(), req.info()
</pre> <p>Note that in general for percent-encoded POST operations, query strings must be quoted using <a class="reference internal" href="../library/urllib.parse#urllib.parse.urlencode" title="urllib.parse.urlencode"><code>urllib.parse.urlencode()</code></a>. For example, to send <code>name=Guy Steele, Jr.</code>:</p> <pre data-language="python">&gt;&gt;&gt; import urllib.parse
&gt;&gt;&gt; urllib.parse.urlencode({'name': 'Guy Steele, Jr.'})
'name=Guy+Steele%2C+Jr.'
</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="../howto/urllib2#urllib-howto"><span class="std std-ref">HOWTO Fetch Internet Resources Using The urllib Package</span></a> for extensive examples.</p> </div> </section> <section id="what-module-should-i-use-to-help-with-generating-html"> <h3>What module should I use to help with generating HTML?</h3> <p>You can find a collection of useful links on the <a class="reference external" href="https://wiki.python.org/moin/WebProgramming">Web Programming wiki page</a>.</p> </section> <section id="how-do-i-send-mail-from-a-python-script"> <h3>How do I send mail from a Python script?</h3> <p>Use the standard library module <a class="reference internal" href="../library/smtplib#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code>smtplib</code></a>.</p> <p>Here’s a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener.</p> <pre data-language="python">import sys, smtplib

fromaddr = input("From: ")
toaddrs  = input("To: ").split(',')
print("Enter message, end with ^D:")
msg = ''
while True:
    line = sys.stdin.readline()
    if not line:
        break
    msg += line

# The actual mail send
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
</pre> <p>A Unix-only alternative uses sendmail. The location of the sendmail program varies between systems; sometimes it is <code>/usr/lib/sendmail</code>, sometimes <code>/usr/sbin/sendmail</code>. The sendmail manual page will help you out. Here’s some sample code:</p> <pre data-language="python">import os

SENDMAIL = "/usr/sbin/sendmail"  # sendmail location
p = 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 body
p.write("Some text\n")
p.write("some more text\n")
sts = p.close()
if sts != 0:
    print("Sendmail exit status", sts)
</pre> </section> <section id="how-do-i-avoid-blocking-in-the-connect-method-of-a-socket"> <h3>How do I avoid blocking in the connect() method of a socket?</h3> <p>The <a class="reference internal" href="../library/select#module-select" title="select: Wait for I/O completion on multiple streams."><code>select</code></a> module is commonly used to help with asynchronous I/O on sockets.</p> <p>To prevent the TCP connect from blocking, you can set the socket to non-blocking mode. Then when you do the <a class="reference internal" href="../library/socket#socket.socket.connect" title="socket.socket.connect"><code>connect()</code></a>, you will either connect immediately (unlikely) or get an exception that contains the error number as <code>.errno</code>. <code>errno.EINPROGRESS</code> indicates that the connection is in progress, but hasn’t finished yet. Different OSes will return different values, so you’re going to have to check what’s returned on your system.</p> <p>You can use the <a class="reference internal" href="../library/socket#socket.socket.connect_ex" title="socket.socket.connect_ex"><code>connect_ex()</code></a> method to avoid creating an exception. It will just return the errno value. To poll, you can call <a class="reference internal" href="../library/socket#socket.socket.connect_ex" title="socket.socket.connect_ex"><code>connect_ex()</code></a> again later – <code>0</code> or <code>errno.EISCONN</code> indicate that you’re connected – or you can pass this socket to <a class="reference internal" href="../library/select#select.select" title="select.select"><code>select.select()</code></a> to check if it’s writable.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <a class="reference internal" href="../library/asyncio#module-asyncio" title="asyncio: Asynchronous I/O."><code>asyncio</code></a> module provides a general purpose single-threaded and concurrent asynchronous library, which can be used for writing non-blocking network code. The third-party <a class="reference external" href="https://twisted.org/">Twisted</a> library is a popular and feature-rich alternative.</p> </div> </section> </section> <section id="databases"> <h2>Databases</h2> <section id="are-there-any-interfaces-to-database-packages-in-python"> <h3>Are there any interfaces to database packages in Python?</h3> <p>Yes.</p> <p>Interfaces to disk-based hashes such as <a class="reference internal" href="../library/dbm#module-dbm.ndbm" title='dbm.ndbm: The standard "database" interface, based on ndbm. (Unix)'><code>DBM</code></a> and <a class="reference internal" href="../library/dbm#module-dbm.gnu" title="dbm.gnu: GNU's reinterpretation of dbm. (Unix)"><code>GDBM</code></a> are also included with standard Python. There is also the <a class="reference internal" href="../library/sqlite3#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code>sqlite3</code></a> module, which provides a lightweight disk-based relational database.</p> <p>Support for most relational databases is available. See the <a class="reference external" href="https://wiki.python.org/moin/DatabaseProgramming">DatabaseProgramming wiki page</a> for details.</p> </section> <section id="how-do-you-implement-persistent-objects-in-python"> <h3>How do you implement persistent objects in Python?</h3> <p>The <a class="reference internal" href="../library/pickle#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code>pickle</code></a> library module solves this in a very general way (though you still can’t store things like open files, sockets or windows), and the <a class="reference internal" href="../library/shelve#module-shelve" title="shelve: Python object persistence."><code>shelve</code></a> library module uses pickle and (g)dbm to create persistent mappings containing arbitrary Python objects.</p> </section> </section> <section id="mathematics-and-numerics"> <h2>Mathematics and Numerics</h2> <section id="how-do-i-generate-random-numbers-in-python"> <h3>How do I generate random numbers in Python?</h3> <p>The standard module <a class="reference internal" href="../library/random#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code>random</code></a> implements a random number generator. Usage is simple:</p> <pre data-language="python">import random
random.random()
</pre> <p>This returns a random floating point number in the range [0, 1).</p> <p>There are also many other specialized generators in this module, such as:</p> <ul class="simple"> <li>
<code>randrange(a, b)</code> chooses an integer in the range [a, b).</li> <li>
<code>uniform(a, b)</code> chooses a floating point number in the range [a, b).</li> <li>
<code>normalvariate(mean, sdev)</code> samples the normal (Gaussian) distribution.</li> </ul> <p>Some higher-level functions operate on sequences directly, such as:</p> <ul class="simple"> <li>
<code>choice(S)</code> chooses a random element from a given sequence.</li> <li>
<code>shuffle(L)</code> shuffles a list in-place, i.e. permutes it randomly.</li> </ul> <p>There’s also a <code>Random</code> class you can instantiate to create independent multiple random number generators.</p> </section> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/faq/library.html" class="_attribution-link">https://docs.python.org/3.12/faq/library.html</a>
  </p>
</div>