2009-10-11 18:25:26 -03:00
|
|
|
:tocdepth: 2
|
|
|
|
|
|
|
|
=========================
|
|
|
|
Library and Extension FAQ
|
|
|
|
=========================
|
|
|
|
|
2013-03-28 09:28:44 -03:00
|
|
|
.. only:: html
|
|
|
|
|
|
|
|
.. contents::
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
General Library Questions
|
|
|
|
=========================
|
|
|
|
|
|
|
|
How do I find a module or application to perform task X?
|
|
|
|
--------------------------------------------------------
|
|
|
|
|
|
|
|
Check :ref:`the Library Reference <library-index>` to see if there's a relevant
|
|
|
|
standard library module. (Eventually you'll learn what's in the standard
|
2012-05-13 14:14:04 -03:00
|
|
|
library and will be able to skip this step.)
|
2009-10-11 18:25:26 -03:00
|
|
|
|
Merged revisions 75365,75394,75402-75403,75418,75459,75484,75592-75596,75600,75602-75607,75610-75613,75616-75617,75623,75627,75640,75647,75696,75795 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r75365 | georg.brandl | 2009-10-11 22:16:16 +0200 (So, 11 Okt 2009) | 1 line
Fix broken links found by "make linkcheck". scipy.org seems to be done right now, so I could not verify links going there.
........
r75394 | georg.brandl | 2009-10-13 20:10:59 +0200 (Di, 13 Okt 2009) | 1 line
Fix markup.
........
r75402 | georg.brandl | 2009-10-14 17:51:48 +0200 (Mi, 14 Okt 2009) | 1 line
#7125: fix typo.
........
r75403 | georg.brandl | 2009-10-14 17:57:46 +0200 (Mi, 14 Okt 2009) | 1 line
#7126: os.environ changes *do* take effect in subprocesses started with os.system().
........
r75418 | georg.brandl | 2009-10-14 20:48:32 +0200 (Mi, 14 Okt 2009) | 1 line
#7116: str.join() takes an iterable.
........
r75459 | georg.brandl | 2009-10-17 10:57:43 +0200 (Sa, 17 Okt 2009) | 1 line
Fix refleaks in _ctypes PyCSimpleType_New, which fixes the refleak seen in test___all__.
........
r75484 | georg.brandl | 2009-10-18 09:58:12 +0200 (So, 18 Okt 2009) | 1 line
Fix missing word.
........
r75592 | georg.brandl | 2009-10-22 09:05:48 +0200 (Do, 22 Okt 2009) | 1 line
Fix punctuation.
........
r75593 | georg.brandl | 2009-10-22 09:06:49 +0200 (Do, 22 Okt 2009) | 1 line
Revert unintended change.
........
r75594 | georg.brandl | 2009-10-22 09:56:02 +0200 (Do, 22 Okt 2009) | 1 line
Fix markup.
........
r75595 | georg.brandl | 2009-10-22 09:56:56 +0200 (Do, 22 Okt 2009) | 1 line
Fix duplicate target.
........
r75596 | georg.brandl | 2009-10-22 10:05:04 +0200 (Do, 22 Okt 2009) | 1 line
Add a new directive marking up implementation details and start using it.
........
r75600 | georg.brandl | 2009-10-22 13:01:46 +0200 (Do, 22 Okt 2009) | 1 line
Make it more robust.
........
r75602 | georg.brandl | 2009-10-22 13:28:06 +0200 (Do, 22 Okt 2009) | 1 line
Document new directive.
........
r75603 | georg.brandl | 2009-10-22 13:28:23 +0200 (Do, 22 Okt 2009) | 1 line
Allow short form with text as argument.
........
r75604 | georg.brandl | 2009-10-22 13:36:50 +0200 (Do, 22 Okt 2009) | 1 line
Fix stylesheet for multi-paragraph impl-details.
........
r75605 | georg.brandl | 2009-10-22 13:48:10 +0200 (Do, 22 Okt 2009) | 1 line
Use "impl-detail" directive where applicable.
........
r75606 | georg.brandl | 2009-10-22 17:00:06 +0200 (Do, 22 Okt 2009) | 1 line
#6324: membership test tries iteration via __iter__.
........
r75607 | georg.brandl | 2009-10-22 17:04:09 +0200 (Do, 22 Okt 2009) | 1 line
#7088: document new functions in signal as Unix-only.
........
r75610 | georg.brandl | 2009-10-22 17:27:24 +0200 (Do, 22 Okt 2009) | 1 line
Reorder __slots__ fine print and add a clarification.
........
r75611 | georg.brandl | 2009-10-22 17:42:32 +0200 (Do, 22 Okt 2009) | 1 line
#7035: improve docs of the various <method>_errors() functions, and give them docstrings.
........
r75612 | georg.brandl | 2009-10-22 17:52:15 +0200 (Do, 22 Okt 2009) | 1 line
#7156: document curses as Unix-only.
........
r75613 | georg.brandl | 2009-10-22 17:54:35 +0200 (Do, 22 Okt 2009) | 1 line
#6977: getopt does not support optional option arguments.
........
r75616 | georg.brandl | 2009-10-22 18:17:05 +0200 (Do, 22 Okt 2009) | 1 line
Add proper references.
........
r75617 | georg.brandl | 2009-10-22 18:20:55 +0200 (Do, 22 Okt 2009) | 1 line
Make printout margin important.
........
r75623 | georg.brandl | 2009-10-23 10:14:44 +0200 (Fr, 23 Okt 2009) | 1 line
#7188: fix optionxform() docs.
........
r75627 | fred.drake | 2009-10-23 15:04:51 +0200 (Fr, 23 Okt 2009) | 2 lines
add further note about what's passed to optionxform
........
r75640 | neil.schemenauer | 2009-10-23 21:58:17 +0200 (Fr, 23 Okt 2009) | 2 lines
Improve some docstrings in the 'warnings' module.
........
r75647 | georg.brandl | 2009-10-24 12:04:19 +0200 (Sa, 24 Okt 2009) | 1 line
Fix markup.
........
r75696 | georg.brandl | 2009-10-25 21:25:43 +0100 (So, 25 Okt 2009) | 1 line
Fix a demo.
........
r75795 | georg.brandl | 2009-10-27 16:10:22 +0100 (Di, 27 Okt 2009) | 1 line
Fix a strange mis-edit.
........
2009-10-27 12:28:25 -03:00
|
|
|
For third-party packages, search the `Python Package Index
|
2018-05-15 15:58:35 -03:00
|
|
|
<https://pypi.org>`_ or try `Google <https://www.google.com>`_ or
|
2021-07-26 19:11:55 -03:00
|
|
|
another web search engine. Searching for "Python" plus a keyword or two for
|
Merged revisions 75365,75394,75402-75403,75418,75459,75484,75592-75596,75600,75602-75607,75610-75613,75616-75617,75623,75627,75640,75647,75696,75795 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r75365 | georg.brandl | 2009-10-11 22:16:16 +0200 (So, 11 Okt 2009) | 1 line
Fix broken links found by "make linkcheck". scipy.org seems to be done right now, so I could not verify links going there.
........
r75394 | georg.brandl | 2009-10-13 20:10:59 +0200 (Di, 13 Okt 2009) | 1 line
Fix markup.
........
r75402 | georg.brandl | 2009-10-14 17:51:48 +0200 (Mi, 14 Okt 2009) | 1 line
#7125: fix typo.
........
r75403 | georg.brandl | 2009-10-14 17:57:46 +0200 (Mi, 14 Okt 2009) | 1 line
#7126: os.environ changes *do* take effect in subprocesses started with os.system().
........
r75418 | georg.brandl | 2009-10-14 20:48:32 +0200 (Mi, 14 Okt 2009) | 1 line
#7116: str.join() takes an iterable.
........
r75459 | georg.brandl | 2009-10-17 10:57:43 +0200 (Sa, 17 Okt 2009) | 1 line
Fix refleaks in _ctypes PyCSimpleType_New, which fixes the refleak seen in test___all__.
........
r75484 | georg.brandl | 2009-10-18 09:58:12 +0200 (So, 18 Okt 2009) | 1 line
Fix missing word.
........
r75592 | georg.brandl | 2009-10-22 09:05:48 +0200 (Do, 22 Okt 2009) | 1 line
Fix punctuation.
........
r75593 | georg.brandl | 2009-10-22 09:06:49 +0200 (Do, 22 Okt 2009) | 1 line
Revert unintended change.
........
r75594 | georg.brandl | 2009-10-22 09:56:02 +0200 (Do, 22 Okt 2009) | 1 line
Fix markup.
........
r75595 | georg.brandl | 2009-10-22 09:56:56 +0200 (Do, 22 Okt 2009) | 1 line
Fix duplicate target.
........
r75596 | georg.brandl | 2009-10-22 10:05:04 +0200 (Do, 22 Okt 2009) | 1 line
Add a new directive marking up implementation details and start using it.
........
r75600 | georg.brandl | 2009-10-22 13:01:46 +0200 (Do, 22 Okt 2009) | 1 line
Make it more robust.
........
r75602 | georg.brandl | 2009-10-22 13:28:06 +0200 (Do, 22 Okt 2009) | 1 line
Document new directive.
........
r75603 | georg.brandl | 2009-10-22 13:28:23 +0200 (Do, 22 Okt 2009) | 1 line
Allow short form with text as argument.
........
r75604 | georg.brandl | 2009-10-22 13:36:50 +0200 (Do, 22 Okt 2009) | 1 line
Fix stylesheet for multi-paragraph impl-details.
........
r75605 | georg.brandl | 2009-10-22 13:48:10 +0200 (Do, 22 Okt 2009) | 1 line
Use "impl-detail" directive where applicable.
........
r75606 | georg.brandl | 2009-10-22 17:00:06 +0200 (Do, 22 Okt 2009) | 1 line
#6324: membership test tries iteration via __iter__.
........
r75607 | georg.brandl | 2009-10-22 17:04:09 +0200 (Do, 22 Okt 2009) | 1 line
#7088: document new functions in signal as Unix-only.
........
r75610 | georg.brandl | 2009-10-22 17:27:24 +0200 (Do, 22 Okt 2009) | 1 line
Reorder __slots__ fine print and add a clarification.
........
r75611 | georg.brandl | 2009-10-22 17:42:32 +0200 (Do, 22 Okt 2009) | 1 line
#7035: improve docs of the various <method>_errors() functions, and give them docstrings.
........
r75612 | georg.brandl | 2009-10-22 17:52:15 +0200 (Do, 22 Okt 2009) | 1 line
#7156: document curses as Unix-only.
........
r75613 | georg.brandl | 2009-10-22 17:54:35 +0200 (Do, 22 Okt 2009) | 1 line
#6977: getopt does not support optional option arguments.
........
r75616 | georg.brandl | 2009-10-22 18:17:05 +0200 (Do, 22 Okt 2009) | 1 line
Add proper references.
........
r75617 | georg.brandl | 2009-10-22 18:20:55 +0200 (Do, 22 Okt 2009) | 1 line
Make printout margin important.
........
r75623 | georg.brandl | 2009-10-23 10:14:44 +0200 (Fr, 23 Okt 2009) | 1 line
#7188: fix optionxform() docs.
........
r75627 | fred.drake | 2009-10-23 15:04:51 +0200 (Fr, 23 Okt 2009) | 2 lines
add further note about what's passed to optionxform
........
r75640 | neil.schemenauer | 2009-10-23 21:58:17 +0200 (Fr, 23 Okt 2009) | 2 lines
Improve some docstrings in the 'warnings' module.
........
r75647 | georg.brandl | 2009-10-24 12:04:19 +0200 (Sa, 24 Okt 2009) | 1 line
Fix markup.
........
r75696 | georg.brandl | 2009-10-25 21:25:43 +0100 (So, 25 Okt 2009) | 1 line
Fix a demo.
........
r75795 | georg.brandl | 2009-10-27 16:10:22 +0100 (Di, 27 Okt 2009) | 1 line
Fix a strange mis-edit.
........
2009-10-27 12:28:25 -03:00
|
|
|
your topic of interest will usually find something helpful.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
Where is the math.py (socket.py, regex.py, etc.) source file?
|
|
|
|
-------------------------------------------------------------
|
|
|
|
|
2010-02-06 14:46:57 -04:00
|
|
|
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
|
2012-05-13 14:14:04 -03:00
|
|
|
:file:`mathmodule.c`, somewhere in a C source directory (not on the Python Path).
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
There are (at least) three kinds of modules in Python:
|
|
|
|
|
|
|
|
1) modules written in Python (.py);
|
|
|
|
2) modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
|
|
|
|
3) modules written in C and linked with the interpreter; to get a list of these,
|
|
|
|
type::
|
|
|
|
|
|
|
|
import sys
|
2009-12-19 13:57:51 -04:00
|
|
|
print(sys.builtin_module_names)
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
How do I make a Python script executable on Unix?
|
|
|
|
-------------------------------------------------
|
|
|
|
|
|
|
|
You need to do two things: the script file's mode must be executable and the
|
|
|
|
first line must begin with ``#!`` followed by the path of the Python
|
|
|
|
interpreter.
|
|
|
|
|
|
|
|
The first is done by executing ``chmod +x scriptfile`` or perhaps ``chmod 755
|
|
|
|
scriptfile``.
|
|
|
|
|
|
|
|
The second can be done in a number of ways. The most straightforward way is to
|
|
|
|
write ::
|
|
|
|
|
|
|
|
#!/usr/local/bin/python
|
|
|
|
|
|
|
|
as the very first line of your file, using the pathname for where the Python
|
|
|
|
interpreter is installed on your platform.
|
|
|
|
|
|
|
|
If you would like the script to be independent of where the Python interpreter
|
2012-05-13 14:14:04 -03:00
|
|
|
lives, you can use the :program:`env` program. Almost all Unix variants support
|
|
|
|
the following, assuming the Python interpreter is in a directory on the user's
|
|
|
|
:envvar:`PATH`::
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
#!/usr/bin/env python
|
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
*Don't* do this for CGI scripts. The :envvar:`PATH` variable for CGI scripts is
|
|
|
|
often very minimal, so you need to use the actual absolute pathname of the
|
2009-10-11 18:25:26 -03:00
|
|
|
interpreter.
|
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
Occasionally, a user's environment is so full that the :program:`/usr/bin/env`
|
|
|
|
program fails; or there's no env program at all. In that case, you can try the
|
2018-04-08 13:18:04 -03:00
|
|
|
following hack (due to Alex Rezinsky):
|
|
|
|
|
|
|
|
.. code-block:: sh
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
#! /bin/sh
|
|
|
|
""":"
|
|
|
|
exec python $0 ${1+"$@"}
|
|
|
|
"""
|
|
|
|
|
|
|
|
The minor disadvantage is that this defines the script's __doc__ string.
|
|
|
|
However, you can fix that by adding ::
|
|
|
|
|
|
|
|
__doc__ = """...Whatever..."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Is there a curses/termcap package for Python?
|
|
|
|
---------------------------------------------
|
|
|
|
|
|
|
|
.. XXX curses *is* built by default, isn't it?
|
|
|
|
|
|
|
|
For Unix variants: The standard Python source distribution comes with a curses
|
2012-05-13 14:14:04 -03:00
|
|
|
module in the :source:`Modules` 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.)
|
2009-10-11 18:25:26 -03:00
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
The :mod:`curses` module supports basic curses features as well as many additional
|
2009-10-11 18:25:26 -03:00
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
|
|
Is there an equivalent to C's onexit() in Python?
|
|
|
|
-------------------------------------------------
|
|
|
|
|
|
|
|
The :mod:`atexit` module provides a register function that is similar to C's
|
2023-08-20 16:01:13 -03:00
|
|
|
:c:func:`!onexit`.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
Why don't my signal handlers work?
|
|
|
|
----------------------------------
|
|
|
|
|
|
|
|
The most common problem is that the signal handler is declared with the wrong
|
|
|
|
argument list. It is called as ::
|
|
|
|
|
|
|
|
handler(signum, frame)
|
|
|
|
|
2019-09-09 12:00:44 -03:00
|
|
|
so it should be declared with two parameters::
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
def handler(signum, frame):
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
|
|
Common tasks
|
|
|
|
============
|
|
|
|
|
|
|
|
How do I test a Python program or component?
|
|
|
|
--------------------------------------------
|
|
|
|
|
|
|
|
Python comes with two testing frameworks. The :mod:`doctest` module finds
|
|
|
|
examples in the docstrings for a module and runs them, comparing the output with
|
|
|
|
the expected output given in the docstring.
|
|
|
|
|
|
|
|
The :mod:`unittest` module is a fancier testing framework modelled on Java and
|
|
|
|
Smalltalk testing frameworks.
|
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
To make testing easier, you should use good modular design in your program.
|
|
|
|
Your program should have almost all functionality
|
2009-10-11 18:25:26 -03:00
|
|
|
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.
|
|
|
|
|
|
|
|
The "global main logic" of your program may be as simple as ::
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main_logic()
|
|
|
|
|
|
|
|
at the bottom of the main module of your program.
|
|
|
|
|
2019-09-09 12:00:44 -03:00
|
|
|
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.
|
2009-10-11 18:25:26 -03:00
|
|
|
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.
|
|
|
|
|
|
|
|
"Support modules" that are not intended to be the main module of a program may
|
|
|
|
include a self-test of the module. ::
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
self_test()
|
|
|
|
|
|
|
|
Even programs that interact with complex external interfaces may be tested when
|
|
|
|
the external interfaces are unavailable by using "fake" interfaces implemented
|
|
|
|
in Python.
|
|
|
|
|
|
|
|
|
|
|
|
How do I create documentation from doc strings?
|
|
|
|
-----------------------------------------------
|
|
|
|
|
|
|
|
The :mod:`pydoc` module can create HTML from the doc strings in your Python
|
Merged revisions 75365,75394,75402-75403,75418,75459,75484,75592-75596,75600,75602-75607,75610-75613,75616-75617,75623,75627,75640,75647,75696,75795 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r75365 | georg.brandl | 2009-10-11 22:16:16 +0200 (So, 11 Okt 2009) | 1 line
Fix broken links found by "make linkcheck". scipy.org seems to be done right now, so I could not verify links going there.
........
r75394 | georg.brandl | 2009-10-13 20:10:59 +0200 (Di, 13 Okt 2009) | 1 line
Fix markup.
........
r75402 | georg.brandl | 2009-10-14 17:51:48 +0200 (Mi, 14 Okt 2009) | 1 line
#7125: fix typo.
........
r75403 | georg.brandl | 2009-10-14 17:57:46 +0200 (Mi, 14 Okt 2009) | 1 line
#7126: os.environ changes *do* take effect in subprocesses started with os.system().
........
r75418 | georg.brandl | 2009-10-14 20:48:32 +0200 (Mi, 14 Okt 2009) | 1 line
#7116: str.join() takes an iterable.
........
r75459 | georg.brandl | 2009-10-17 10:57:43 +0200 (Sa, 17 Okt 2009) | 1 line
Fix refleaks in _ctypes PyCSimpleType_New, which fixes the refleak seen in test___all__.
........
r75484 | georg.brandl | 2009-10-18 09:58:12 +0200 (So, 18 Okt 2009) | 1 line
Fix missing word.
........
r75592 | georg.brandl | 2009-10-22 09:05:48 +0200 (Do, 22 Okt 2009) | 1 line
Fix punctuation.
........
r75593 | georg.brandl | 2009-10-22 09:06:49 +0200 (Do, 22 Okt 2009) | 1 line
Revert unintended change.
........
r75594 | georg.brandl | 2009-10-22 09:56:02 +0200 (Do, 22 Okt 2009) | 1 line
Fix markup.
........
r75595 | georg.brandl | 2009-10-22 09:56:56 +0200 (Do, 22 Okt 2009) | 1 line
Fix duplicate target.
........
r75596 | georg.brandl | 2009-10-22 10:05:04 +0200 (Do, 22 Okt 2009) | 1 line
Add a new directive marking up implementation details and start using it.
........
r75600 | georg.brandl | 2009-10-22 13:01:46 +0200 (Do, 22 Okt 2009) | 1 line
Make it more robust.
........
r75602 | georg.brandl | 2009-10-22 13:28:06 +0200 (Do, 22 Okt 2009) | 1 line
Document new directive.
........
r75603 | georg.brandl | 2009-10-22 13:28:23 +0200 (Do, 22 Okt 2009) | 1 line
Allow short form with text as argument.
........
r75604 | georg.brandl | 2009-10-22 13:36:50 +0200 (Do, 22 Okt 2009) | 1 line
Fix stylesheet for multi-paragraph impl-details.
........
r75605 | georg.brandl | 2009-10-22 13:48:10 +0200 (Do, 22 Okt 2009) | 1 line
Use "impl-detail" directive where applicable.
........
r75606 | georg.brandl | 2009-10-22 17:00:06 +0200 (Do, 22 Okt 2009) | 1 line
#6324: membership test tries iteration via __iter__.
........
r75607 | georg.brandl | 2009-10-22 17:04:09 +0200 (Do, 22 Okt 2009) | 1 line
#7088: document new functions in signal as Unix-only.
........
r75610 | georg.brandl | 2009-10-22 17:27:24 +0200 (Do, 22 Okt 2009) | 1 line
Reorder __slots__ fine print and add a clarification.
........
r75611 | georg.brandl | 2009-10-22 17:42:32 +0200 (Do, 22 Okt 2009) | 1 line
#7035: improve docs of the various <method>_errors() functions, and give them docstrings.
........
r75612 | georg.brandl | 2009-10-22 17:52:15 +0200 (Do, 22 Okt 2009) | 1 line
#7156: document curses as Unix-only.
........
r75613 | georg.brandl | 2009-10-22 17:54:35 +0200 (Do, 22 Okt 2009) | 1 line
#6977: getopt does not support optional option arguments.
........
r75616 | georg.brandl | 2009-10-22 18:17:05 +0200 (Do, 22 Okt 2009) | 1 line
Add proper references.
........
r75617 | georg.brandl | 2009-10-22 18:20:55 +0200 (Do, 22 Okt 2009) | 1 line
Make printout margin important.
........
r75623 | georg.brandl | 2009-10-23 10:14:44 +0200 (Fr, 23 Okt 2009) | 1 line
#7188: fix optionxform() docs.
........
r75627 | fred.drake | 2009-10-23 15:04:51 +0200 (Fr, 23 Okt 2009) | 2 lines
add further note about what's passed to optionxform
........
r75640 | neil.schemenauer | 2009-10-23 21:58:17 +0200 (Fr, 23 Okt 2009) | 2 lines
Improve some docstrings in the 'warnings' module.
........
r75647 | georg.brandl | 2009-10-24 12:04:19 +0200 (Sa, 24 Okt 2009) | 1 line
Fix markup.
........
r75696 | georg.brandl | 2009-10-25 21:25:43 +0100 (So, 25 Okt 2009) | 1 line
Fix a demo.
........
r75795 | georg.brandl | 2009-10-27 16:10:22 +0100 (Di, 27 Okt 2009) | 1 line
Fix a strange mis-edit.
........
2009-10-27 12:28:25 -03:00
|
|
|
source code. An alternative for creating API documentation purely from
|
2022-09-27 08:08:11 -03:00
|
|
|
docstrings is `epydoc <https://epydoc.sourceforge.net/>`_. `Sphinx
|
2022-09-24 08:38:53 -03:00
|
|
|
<https://www.sphinx-doc.org>`_ can also include docstring content.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
How do I get a single keypress at a time?
|
|
|
|
-----------------------------------------
|
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
For Unix variants there are several solutions. It's straightforward to do this
|
2009-12-19 13:57:51 -04:00
|
|
|
using curses, but curses is a fairly large module to learn.
|
|
|
|
|
|
|
|
.. XXX this doesn't work out of the box, some IO expert needs to check why
|
|
|
|
|
|
|
|
Here's a solution without curses::
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
import termios, fcntl, sys, os
|
|
|
|
fd = sys.stdin.fileno()
|
|
|
|
|
|
|
|
oldterm = termios.tcgetattr(fd)
|
|
|
|
newattr = termios.tcgetattr(fd)
|
|
|
|
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
|
|
|
|
termios.tcsetattr(fd, termios.TCSANOW, newattr)
|
|
|
|
|
|
|
|
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
|
|
|
|
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
|
|
|
|
|
|
|
|
try:
|
2009-12-19 13:57:51 -04:00
|
|
|
while True:
|
2009-10-11 18:25:26 -03:00
|
|
|
try:
|
|
|
|
c = sys.stdin.read(1)
|
2009-12-19 13:57:51 -04:00
|
|
|
print("Got character", repr(c))
|
2012-12-18 17:16:44 -04:00
|
|
|
except OSError:
|
2009-12-19 13:57:51 -04:00
|
|
|
pass
|
2009-10-11 18:25:26 -03:00
|
|
|
finally:
|
|
|
|
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
|
|
|
|
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
|
|
|
|
|
2009-12-19 13:57:51 -04:00
|
|
|
You need the :mod:`termios` and the :mod:`fcntl` module for any of this to
|
|
|
|
work, and I've only tried it on Linux, though it should work elsewhere. In
|
|
|
|
this code, characters are read and printed one at a time.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
2009-12-19 13:57:51 -04:00
|
|
|
:func:`termios.tcsetattr` turns off stdin's echoing and disables canonical
|
|
|
|
mode. :func:`fcntl.fnctl` is used to obtain stdin's file descriptor flags
|
|
|
|
and modify them for non-blocking mode. Since reading stdin when it is empty
|
2012-12-18 17:16:44 -04:00
|
|
|
results in an :exc:`OSError`, this error is caught and ignored.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
2012-12-19 07:45:30 -04:00
|
|
|
.. versionchanged:: 3.3
|
|
|
|
*sys.stdin.read* used to raise :exc:`IOError`. Starting from Python 3.3
|
|
|
|
:exc:`IOError` is alias for :exc:`OSError`.
|
|
|
|
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
Threads
|
|
|
|
=======
|
|
|
|
|
|
|
|
How do I program using threads?
|
|
|
|
-------------------------------
|
|
|
|
|
2009-10-13 13:55:12 -03:00
|
|
|
Be sure to use the :mod:`threading` module and not the :mod:`_thread` module.
|
2009-10-11 18:25:26 -03:00
|
|
|
The :mod:`threading` module builds convenient abstractions on top of the
|
2009-10-13 13:55:12 -03:00
|
|
|
low-level primitives provided by the :mod:`_thread` module.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
None of my threads seem to run: why?
|
|
|
|
------------------------------------
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
A simple fix is to add a sleep to the end of the program that's long enough for
|
|
|
|
all the threads to finish::
|
|
|
|
|
|
|
|
import threading, time
|
|
|
|
|
|
|
|
def thread_task(name, n):
|
2016-05-10 06:01:23 -03:00
|
|
|
for i in range(n):
|
|
|
|
print(name, i)
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
for i in range(10):
|
|
|
|
T = threading.Thread(target=thread_task, args=(str(i), i))
|
|
|
|
T.start()
|
|
|
|
|
2009-12-19 13:57:51 -04:00
|
|
|
time.sleep(10) # <---------------------------!
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
A simple fix is to add a tiny sleep to the start of the run function::
|
|
|
|
|
|
|
|
def thread_task(name, n):
|
2009-12-19 13:57:51 -04:00
|
|
|
time.sleep(0.001) # <--------------------!
|
2016-05-10 06:01:23 -03:00
|
|
|
for i in range(n):
|
|
|
|
print(name, i)
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
for i in range(10):
|
|
|
|
T = threading.Thread(target=thread_task, args=(str(i), i))
|
|
|
|
T.start()
|
|
|
|
|
|
|
|
time.sleep(10)
|
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
Instead of trying to guess a good delay value for :func:`time.sleep`,
|
2009-10-11 18:25:26 -03:00
|
|
|
it's better to use some kind of semaphore mechanism. One idea is to use the
|
2009-10-13 13:55:12 -03:00
|
|
|
:mod:`queue` module to create a queue object, let each thread append a token to
|
2009-10-11 18:25:26 -03:00
|
|
|
the queue when it finishes, and let the main thread read as many tokens from the
|
|
|
|
queue as there are threads.
|
|
|
|
|
|
|
|
|
|
|
|
How do I parcel out work among a bunch of worker threads?
|
|
|
|
---------------------------------------------------------
|
|
|
|
|
2019-09-09 12:00:44 -03:00
|
|
|
The easiest way is to use the :mod:`concurrent.futures` module,
|
2011-02-05 07:18:34 -04:00
|
|
|
especially the :mod:`~concurrent.futures.ThreadPoolExecutor` class.
|
|
|
|
|
|
|
|
Or, if you want fine control over the dispatching algorithm, you can write
|
|
|
|
your own logic manually. Use the :mod:`queue` module to create a queue
|
|
|
|
containing a list of jobs. The :class:`~queue.Queue` class maintains a
|
2012-05-13 14:14:04 -03:00
|
|
|
list of objects and has a ``.put(obj)`` method that adds items to the queue and
|
|
|
|
a ``.get()`` method to return them. The class will take care of the locking
|
|
|
|
necessary to ensure that each job is handed out exactly once.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
Here's a trivial example::
|
|
|
|
|
2009-12-19 13:57:51 -04:00
|
|
|
import threading, queue, time
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
# 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.)
|
2012-05-13 14:14:04 -03:00
|
|
|
def worker():
|
2009-12-19 13:57:51 -04:00
|
|
|
print('Running worker')
|
2009-10-11 18:25:26 -03:00
|
|
|
time.sleep(0.1)
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
arg = q.get(block=False)
|
2009-12-19 13:57:51 -04:00
|
|
|
except queue.Empty:
|
2021-04-12 05:42:53 -03:00
|
|
|
print('Worker', threading.current_thread(), end=' ')
|
2009-12-19 13:57:51 -04:00
|
|
|
print('queue empty')
|
2009-10-11 18:25:26 -03:00
|
|
|
break
|
|
|
|
else:
|
2021-04-12 05:42:53 -03:00
|
|
|
print('Worker', threading.current_thread(), end=' ')
|
2009-12-19 13:57:51 -04:00
|
|
|
print('running with argument', arg)
|
2009-10-11 18:25:26 -03:00
|
|
|
time.sleep(0.5)
|
|
|
|
|
|
|
|
# Create queue
|
2009-12-19 13:57:51 -04:00
|
|
|
q = queue.Queue()
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
# 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
|
2009-12-19 13:57:51 -04:00
|
|
|
print('Main thread sleeping')
|
2009-10-11 18:25:26 -03:00
|
|
|
time.sleep(5)
|
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
When run, this will produce the following output:
|
|
|
|
|
|
|
|
.. code-block:: none
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
Running worker
|
|
|
|
Running worker
|
|
|
|
Running worker
|
|
|
|
Running worker
|
|
|
|
Running worker
|
|
|
|
Main thread sleeping
|
2009-12-19 13:57:51 -04:00
|
|
|
Worker <Thread(worker 1, started 130283832797456)> running with argument 0
|
|
|
|
Worker <Thread(worker 2, started 130283824404752)> running with argument 1
|
|
|
|
Worker <Thread(worker 3, started 130283816012048)> running with argument 2
|
|
|
|
Worker <Thread(worker 4, started 130283807619344)> running with argument 3
|
|
|
|
Worker <Thread(worker 5, started 130283799226640)> running with argument 4
|
|
|
|
Worker <Thread(worker 1, started 130283832797456)> running with argument 5
|
2009-10-11 18:25:26 -03:00
|
|
|
...
|
|
|
|
|
2012-05-30 17:03:20 -03:00
|
|
|
Consult the module's documentation for more details; the :class:`~queue.Queue`
|
2012-05-13 14:14:04 -03:00
|
|
|
class provides a featureful interface.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
What kinds of global value mutation are thread-safe?
|
|
|
|
----------------------------------------------------
|
|
|
|
|
2011-02-05 07:18:34 -04:00
|
|
|
A :term:`global interpreter lock` (GIL) is used internally to ensure that only one
|
2009-10-11 18:25:26 -03:00
|
|
|
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
|
2009-12-19 13:57:51 -04:00
|
|
|
be set via :func:`sys.setswitchinterval`. Each bytecode instruction and
|
2009-10-11 18:25:26 -03:00
|
|
|
therefore all the C implementation code reached from each instruction is
|
|
|
|
therefore atomic from the point of view of a Python program.
|
|
|
|
|
|
|
|
In theory, this means an exact accounting requires an exact understanding of the
|
|
|
|
PVM bytecode implementation. In practice, it means that operations on shared
|
2010-02-06 14:46:57 -04:00
|
|
|
variables of built-in data types (ints, lists, dicts, etc) that "look atomic"
|
2009-10-11 18:25:26 -03:00
|
|
|
really are.
|
|
|
|
|
|
|
|
For example, the following operations are all atomic (L, L1, L2 are lists, D,
|
|
|
|
D1, D2 are dicts, x, y are objects, i, j are ints)::
|
|
|
|
|
|
|
|
L.append(x)
|
|
|
|
L1.extend(L2)
|
|
|
|
x = L[i]
|
|
|
|
x = L.pop()
|
|
|
|
L1[i:j] = L2
|
|
|
|
L.sort()
|
|
|
|
x = y
|
|
|
|
x.field = y
|
|
|
|
D[x] = y
|
|
|
|
D1.update(D2)
|
|
|
|
D.keys()
|
|
|
|
|
|
|
|
These aren't::
|
|
|
|
|
|
|
|
i = i+1
|
|
|
|
L.append(L[-1])
|
|
|
|
L[i] = L[j]
|
|
|
|
D[x] = D[x] + 1
|
|
|
|
|
|
|
|
Operations that replace other objects may invoke those other objects'
|
2023-08-20 16:01:13 -03:00
|
|
|
:meth:`~object.__del__` method when their reference count reaches zero, and that can
|
2009-10-11 18:25:26 -03:00
|
|
|
affect things. This is especially true for the mass updates to dictionaries and
|
|
|
|
lists. When in doubt, use a mutex!
|
|
|
|
|
|
|
|
|
|
|
|
Can't we get rid of the Global Interpreter Lock?
|
|
|
|
------------------------------------------------
|
|
|
|
|
2011-02-05 07:18:34 -04:00
|
|
|
The :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's
|
2009-10-11 18:25:26 -03:00
|
|
|
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.
|
|
|
|
|
2024-02-06 11:55:44 -04:00
|
|
|
With the approval of :pep:`703` work is now underway to remove the GIL from the
|
|
|
|
CPython implementation of Python. Initially it will be implemented as an
|
|
|
|
optional compiler flag when building the interpreter, and so separate
|
|
|
|
builds will be available with and without the GIL. Long-term, the hope is
|
|
|
|
to settle on a single build, once the performance implications of removing the
|
|
|
|
GIL are fully understood. Python 3.13 is likely to be the first release
|
|
|
|
containing this work, although it may not be completely functional in this
|
|
|
|
release.
|
|
|
|
|
|
|
|
The current work to remove the GIL is based on a
|
|
|
|
`fork of Python 3.9 with the GIL removed <https://github.com/colesbury/nogil>`_
|
|
|
|
by Sam Gross.
|
|
|
|
Prior to that,
|
|
|
|
in the days of Python 1.5, Greg Stein actually implemented a comprehensive
|
2009-10-11 18:25:26 -03:00
|
|
|
patch set (the "free threading" patches) that removed the GIL and replaced it
|
2024-02-06 11:55:44 -04:00
|
|
|
with fine-grained locking. Adam Olsen did a similar experiment
|
2017-12-06 12:39:33 -04:00
|
|
|
in his `python-safethread <https://code.google.com/archive/p/python-safethread>`_
|
2024-02-06 11:55:44 -04:00
|
|
|
project. Unfortunately, both of these earlier experiments exhibited a sharp
|
|
|
|
drop in single-thread
|
2011-02-05 07:18:34 -04:00
|
|
|
performance (at least 30% slower), due to the amount of fine-grained locking
|
2024-02-06 11:55:44 -04:00
|
|
|
necessary to compensate for the removal of the GIL. The Python 3.9 fork
|
|
|
|
is the first attempt at removing the GIL with an acceptable performance
|
|
|
|
impact.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
2024-02-06 11:55:44 -04:00
|
|
|
The presence of the GIL in current Python releases
|
|
|
|
doesn't mean that you can't make good use of Python on multi-CPU machines!
|
2009-10-11 18:25:26 -03:00
|
|
|
You just have to be creative with dividing the work up between multiple
|
2011-02-05 07:18:34 -04:00
|
|
|
*processes* rather than multiple *threads*. The
|
|
|
|
:class:`~concurrent.futures.ProcessPoolExecutor` class in the new
|
|
|
|
:mod:`concurrent.futures` module provides an easy way of doing so; the
|
|
|
|
:mod:`multiprocessing` module provides a lower-level API in case you want
|
|
|
|
more control over dispatching of tasks.
|
|
|
|
|
|
|
|
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 :mod:`zlib` and :mod:`hashlib`
|
|
|
|
already do this.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
2024-02-06 11:55:44 -04:00
|
|
|
An alternative approach to reducing the impact of the GIL is
|
|
|
|
to make the GIL a per-interpreter-state lock rather than truly global.
|
|
|
|
This was :ref:`first implemented in Python 3.12 <whatsnew312-pep684>` and is
|
|
|
|
available in the C API. A Python interface to it is expected in Python 3.13.
|
|
|
|
The main limitation to it at the moment is likely to be 3rd party extension
|
|
|
|
modules, since these must be written with multiple interpreters in mind in
|
|
|
|
order to be usable, so many older extension modules will not be usable.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
Input and Output
|
|
|
|
================
|
|
|
|
|
|
|
|
How do I delete a file? (And other file questions...)
|
|
|
|
-----------------------------------------------------
|
|
|
|
|
|
|
|
Use ``os.remove(filename)`` or ``os.unlink(filename)``; for documentation, see
|
2009-12-19 13:57:51 -04:00
|
|
|
the :mod:`os` module. The two functions are identical; :func:`~os.unlink` is simply
|
2009-10-11 18:25:26 -03:00
|
|
|
the name of the Unix system call for this function.
|
|
|
|
|
|
|
|
To remove a directory, use :func:`os.rmdir`; use :func:`os.mkdir` to create one.
|
|
|
|
``os.makedirs(path)`` will create any intermediate directories in ``path`` that
|
|
|
|
don't exist. ``os.removedirs(path)`` will remove intermediate directories as
|
|
|
|
long as they're empty; if you want to delete an entire directory tree and its
|
|
|
|
contents, use :func:`shutil.rmtree`.
|
|
|
|
|
|
|
|
To rename a file, use ``os.rename(old_path, new_path)``.
|
|
|
|
|
2010-09-15 07:08:31 -03:00
|
|
|
To truncate a file, open it using ``f = open(filename, "rb+")``, and use
|
2009-10-11 18:25:26 -03:00
|
|
|
``f.truncate(offset)``; offset defaults to the current seek position. There's
|
2010-10-06 07:26:05 -03:00
|
|
|
also ``os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where
|
2012-05-13 14:14:04 -03:00
|
|
|
*fd* is the file descriptor (a small integer).
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
The :mod:`shutil` module also contains a number of functions to work on files
|
|
|
|
including :func:`~shutil.copyfile`, :func:`~shutil.copytree`, and
|
|
|
|
:func:`~shutil.rmtree`.
|
|
|
|
|
|
|
|
|
|
|
|
How do I copy a file?
|
|
|
|
---------------------
|
|
|
|
|
2022-06-09 10:55:06 -03:00
|
|
|
The :mod:`shutil` module contains a :func:`~shutil.copyfile` function.
|
|
|
|
Note that on Windows NTFS volumes, it does not copy
|
|
|
|
`alternate data streams
|
|
|
|
<https://en.wikipedia.org/wiki/NTFS#Alternate_data_stream_(ADS)>`_
|
|
|
|
nor `resource forks <https://en.wikipedia.org/wiki/Resource_fork>`__
|
|
|
|
on macOS HFS+ volumes, though both are now rarely used.
|
|
|
|
It also doesn't copy file permissions and metadata, though using
|
|
|
|
:func:`shutil.copy2` instead will preserve most (though not all) of it.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
How do I read (or write) binary data?
|
|
|
|
-------------------------------------
|
|
|
|
|
|
|
|
To read or write complex binary data formats, it's best to use the :mod:`struct`
|
|
|
|
module. It allows you to take a string containing binary data (usually numbers)
|
|
|
|
and convert it to Python objects; and vice versa.
|
|
|
|
|
|
|
|
For example, the following code reads two 2-byte integers and one 4-byte integer
|
|
|
|
in big-endian format from a file::
|
|
|
|
|
|
|
|
import struct
|
|
|
|
|
2010-09-15 07:08:31 -03:00
|
|
|
with open(filename, "rb") as f:
|
2016-05-10 06:01:23 -03:00
|
|
|
s = f.read(8)
|
|
|
|
x, y, z = struct.unpack(">hhl", s)
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
The '>' in the format string forces big-endian data; the letter 'h' reads one
|
|
|
|
"short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the
|
|
|
|
string.
|
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
For data that is more regular (e.g. a homogeneous list of ints or floats),
|
2009-10-11 18:25:26 -03:00
|
|
|
you can also use the :mod:`array` module.
|
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
.. note::
|
2014-03-16 01:13:56 -03:00
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
To read and write binary data, it is mandatory to open the file in
|
|
|
|
binary mode (here, passing ``"rb"`` to :func:`open`). If you use
|
|
|
|
``"r"`` instead (the default), the file will be open in text mode
|
|
|
|
and ``f.read()`` will return :class:`str` objects rather than
|
|
|
|
:class:`bytes` objects.
|
2010-09-15 07:08:31 -03:00
|
|
|
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
I can't seem to use os.read() on a pipe created with os.popen(); why?
|
|
|
|
---------------------------------------------------------------------
|
|
|
|
|
|
|
|
:func:`os.read` is a low-level function which takes a file descriptor, a small
|
|
|
|
integer representing the opened file. :func:`os.popen` creates a high-level
|
2010-02-06 14:46:57 -04:00
|
|
|
file object, the same type returned by the built-in :func:`open` function.
|
2012-05-13 14:14:04 -03:00
|
|
|
Thus, to read *n* bytes from a pipe *p* created with :func:`os.popen`, you need to
|
2010-02-06 14:46:57 -04:00
|
|
|
use ``p.read(n)``.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
How do I access the serial (RS232) port?
|
|
|
|
----------------------------------------
|
|
|
|
|
2021-11-20 15:56:42 -04:00
|
|
|
For Win32, OSX, Linux, BSD, Jython, IronPython:
|
2009-10-11 18:25:26 -03:00
|
|
|
|
2024-04-15 15:22:00 -03:00
|
|
|
:pypi:`pyserial`
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
For Unix, see a Usenet post by Mitch Chapman:
|
|
|
|
|
2016-02-26 14:37:12 -04:00
|
|
|
https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
Why doesn't closing sys.stdout (stdin, stderr) really close it?
|
|
|
|
---------------------------------------------------------------
|
|
|
|
|
2010-09-15 07:08:31 -03:00
|
|
|
Python :term:`file objects <file object>` are a high-level layer of
|
|
|
|
abstraction on low-level C file descriptors.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
2010-09-15 07:08:31 -03:00
|
|
|
For most file objects you create in Python via the built-in :func:`open`
|
|
|
|
function, ``f.close()`` 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 ``f``'s destructor, when
|
|
|
|
``f`` becomes garbage.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
But stdin, stdout and stderr are treated specially by Python, because of the
|
|
|
|
special status also given to them by C. Running ``sys.stdout.close()`` marks
|
|
|
|
the Python-level file object as being closed, but does *not* close the
|
2010-09-15 07:08:31 -03:00
|
|
|
associated C file descriptor.
|
|
|
|
|
|
|
|
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 :func:`os.close`::
|
2009-10-11 18:25:26 -03:00
|
|
|
|
2010-09-15 07:08:31 -03:00
|
|
|
os.close(stdin.fileno())
|
|
|
|
os.close(stdout.fileno())
|
|
|
|
os.close(stderr.fileno())
|
2009-10-11 18:25:26 -03:00
|
|
|
|
2010-09-15 07:08:31 -03:00
|
|
|
Or you can use the numeric constants 0, 1 and 2, respectively.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
Network/Internet Programming
|
|
|
|
============================
|
|
|
|
|
|
|
|
What WWW tools are there for Python?
|
|
|
|
------------------------------------
|
|
|
|
|
|
|
|
See the chapters titled :ref:`internet` and :ref:`netdata` in the Library
|
|
|
|
Reference Manual. Python has many modules that will help you build server-side
|
|
|
|
and client-side web systems.
|
|
|
|
|
|
|
|
.. XXX check if wiki page is still up to date
|
|
|
|
|
|
|
|
A summary of available frameworks is maintained by Paul Boddie at
|
2014-10-29 04:36:35 -03:00
|
|
|
https://wiki.python.org/moin/WebProgramming\ .
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
What module should I use to help with generating HTML?
|
|
|
|
------------------------------------------------------
|
|
|
|
|
|
|
|
.. XXX add modern template languages
|
|
|
|
|
2012-05-13 14:14:04 -03:00
|
|
|
You can find a collection of useful links on the `Web Programming wiki page
|
2014-10-29 04:36:35 -03:00
|
|
|
<https://wiki.python.org/moin/WebProgramming>`_.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
How do I send mail from a Python script?
|
|
|
|
----------------------------------------
|
|
|
|
|
|
|
|
Use the standard library module :mod:`smtplib`.
|
|
|
|
|
|
|
|
Here's a very simple interactive mail sender that uses it. This method will
|
|
|
|
work on any host that supports an SMTP listener. ::
|
|
|
|
|
|
|
|
import sys, smtplib
|
|
|
|
|
2009-12-19 13:57:51 -04:00
|
|
|
fromaddr = input("From: ")
|
|
|
|
toaddrs = input("To: ").split(',')
|
|
|
|
print("Enter message, end with ^D:")
|
2009-10-11 18:25:26 -03:00
|
|
|
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()
|
|
|
|
|
|
|
|
A Unix-only alternative uses sendmail. The location of the sendmail program
|
2012-05-13 14:14:04 -03:00
|
|
|
varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes
|
2009-10-11 18:25:26 -03:00
|
|
|
``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's
|
|
|
|
some sample code::
|
|
|
|
|
|
|
|
import os
|
2016-05-10 06:01:23 -03:00
|
|
|
|
|
|
|
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
|
2009-10-11 18:25:26 -03:00
|
|
|
p = os.popen("%s -t -i" % SENDMAIL, "w")
|
|
|
|
p.write("To: receiver@example.com\n")
|
|
|
|
p.write("Subject: test\n")
|
2009-12-19 13:57:51 -04:00
|
|
|
p.write("\n") # blank line separating headers from body
|
2009-10-11 18:25:26 -03:00
|
|
|
p.write("Some text\n")
|
|
|
|
p.write("some more text\n")
|
|
|
|
sts = p.close()
|
|
|
|
if sts != 0:
|
2009-12-19 13:57:51 -04:00
|
|
|
print("Sendmail exit status", sts)
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
How do I avoid blocking in the connect() method of a socket?
|
|
|
|
------------------------------------------------------------
|
|
|
|
|
2011-02-05 07:24:15 -04:00
|
|
|
The :mod:`select` module is commonly used to help with asynchronous I/O on
|
|
|
|
sockets.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
To prevent the TCP connect from blocking, you can set the socket to non-blocking
|
2023-08-20 16:01:13 -03:00
|
|
|
mode. Then when you do the :meth:`~socket.socket.connect`,
|
|
|
|
you will either connect immediately
|
2009-10-11 18:25:26 -03:00
|
|
|
(unlikely) or get an exception that contains the error number as ``.errno``.
|
|
|
|
``errno.EINPROGRESS`` 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.
|
|
|
|
|
2023-08-20 16:01:13 -03:00
|
|
|
You can use the :meth:`~socket.socket.connect_ex` method
|
|
|
|
to avoid creating an exception.
|
|
|
|
It will just return the errno value.
|
|
|
|
To poll, you can call :meth:`~socket.socket.connect_ex` again later
|
2009-12-19 13:57:51 -04:00
|
|
|
-- ``0`` or ``errno.EISCONN`` indicate that you're connected -- or you can pass this
|
2019-09-09 12:00:44 -03:00
|
|
|
socket to :meth:`select.select` to check if it's writable.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
2011-02-05 07:24:15 -04:00
|
|
|
.. note::
|
2019-09-09 12:00:44 -03:00
|
|
|
The :mod:`asyncio` module provides a general purpose single-threaded and
|
|
|
|
concurrent asynchronous library, which can be used for writing non-blocking
|
|
|
|
network code.
|
2023-04-22 11:24:47 -03:00
|
|
|
The third-party `Twisted <https://twisted.org/>`_ library is
|
2011-02-05 07:24:15 -04:00
|
|
|
a popular and feature-rich alternative.
|
|
|
|
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
Databases
|
|
|
|
=========
|
|
|
|
|
|
|
|
Are there any interfaces to database packages in Python?
|
|
|
|
--------------------------------------------------------
|
|
|
|
|
|
|
|
Yes.
|
|
|
|
|
2009-10-13 13:55:12 -03:00
|
|
|
Interfaces to disk-based hashes such as :mod:`DBM <dbm.ndbm>` and :mod:`GDBM
|
|
|
|
<dbm.gnu>` are also included with standard Python. There is also the
|
|
|
|
:mod:`sqlite3` module, which provides a lightweight disk-based relational
|
|
|
|
database.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
Support for most relational databases is available. See the
|
|
|
|
`DatabaseProgramming wiki page
|
2014-10-29 04:36:35 -03:00
|
|
|
<https://wiki.python.org/moin/DatabaseProgramming>`_ for details.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
How do you implement persistent objects in Python?
|
|
|
|
--------------------------------------------------
|
|
|
|
|
|
|
|
The :mod:`pickle` library module solves this in a very general way (though you
|
|
|
|
still can't store things like open files, sockets or windows), and the
|
|
|
|
:mod:`shelve` library module uses pickle and (g)dbm to create persistent
|
2009-10-13 13:55:12 -03:00
|
|
|
mappings containing arbitrary Python objects.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
Mathematics and Numerics
|
|
|
|
========================
|
|
|
|
|
|
|
|
How do I generate random numbers in Python?
|
|
|
|
-------------------------------------------
|
|
|
|
|
|
|
|
The standard module :mod:`random` implements a random number generator. Usage
|
|
|
|
is simple::
|
|
|
|
|
|
|
|
import random
|
|
|
|
random.random()
|
|
|
|
|
2024-07-19 05:06:02 -03:00
|
|
|
This returns a random floating-point number in the range [0, 1).
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
There are also many other specialized generators in this module, such as:
|
|
|
|
|
|
|
|
* ``randrange(a, b)`` chooses an integer in the range [a, b).
|
2024-07-19 05:06:02 -03:00
|
|
|
* ``uniform(a, b)`` chooses a floating-point number in the range [a, b).
|
2009-10-11 18:25:26 -03:00
|
|
|
* ``normalvariate(mean, sdev)`` samples the normal (Gaussian) distribution.
|
|
|
|
|
|
|
|
Some higher-level functions operate on sequences directly, such as:
|
|
|
|
|
2019-09-09 12:00:44 -03:00
|
|
|
* ``choice(S)`` chooses a random element from a given sequence.
|
|
|
|
* ``shuffle(L)`` shuffles a list in-place, i.e. permutes it randomly.
|
2009-10-11 18:25:26 -03:00
|
|
|
|
|
|
|
There's also a ``Random`` class you can instantiate to create independent
|
|
|
|
multiple random number generators.
|