17db96d56Sopenharmony_ci:tocdepth: 2
27db96d56Sopenharmony_ci
37db96d56Sopenharmony_ci=========================
47db96d56Sopenharmony_ciLibrary and Extension FAQ
57db96d56Sopenharmony_ci=========================
67db96d56Sopenharmony_ci
77db96d56Sopenharmony_ci.. only:: html
87db96d56Sopenharmony_ci
97db96d56Sopenharmony_ci   .. contents::
107db96d56Sopenharmony_ci
117db96d56Sopenharmony_ciGeneral Library Questions
127db96d56Sopenharmony_ci=========================
137db96d56Sopenharmony_ci
147db96d56Sopenharmony_ciHow do I find a module or application to perform task X?
157db96d56Sopenharmony_ci--------------------------------------------------------
167db96d56Sopenharmony_ci
177db96d56Sopenharmony_ciCheck :ref:`the Library Reference <library-index>` to see if there's a relevant
187db96d56Sopenharmony_cistandard library module.  (Eventually you'll learn what's in the standard
197db96d56Sopenharmony_cilibrary and will be able to skip this step.)
207db96d56Sopenharmony_ci
217db96d56Sopenharmony_ciFor third-party packages, search the `Python Package Index
227db96d56Sopenharmony_ci<https://pypi.org>`_ or try `Google <https://www.google.com>`_ or
237db96d56Sopenharmony_cianother web search engine.  Searching for "Python" plus a keyword or two for
247db96d56Sopenharmony_ciyour topic of interest will usually find something helpful.
257db96d56Sopenharmony_ci
267db96d56Sopenharmony_ci
277db96d56Sopenharmony_ciWhere is the math.py (socket.py, regex.py, etc.) source file?
287db96d56Sopenharmony_ci-------------------------------------------------------------
297db96d56Sopenharmony_ci
307db96d56Sopenharmony_ciIf you can't find a source file for a module it may be a built-in or
317db96d56Sopenharmony_cidynamically loaded module implemented in C, C++ or other compiled language.
327db96d56Sopenharmony_ciIn this case you may not have the source file or it may be something like
337db96d56Sopenharmony_ci:file:`mathmodule.c`, somewhere in a C source directory (not on the Python Path).
347db96d56Sopenharmony_ci
357db96d56Sopenharmony_ciThere are (at least) three kinds of modules in Python:
367db96d56Sopenharmony_ci
377db96d56Sopenharmony_ci1) modules written in Python (.py);
387db96d56Sopenharmony_ci2) modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
397db96d56Sopenharmony_ci3) modules written in C and linked with the interpreter; to get a list of these,
407db96d56Sopenharmony_ci   type::
417db96d56Sopenharmony_ci
427db96d56Sopenharmony_ci      import sys
437db96d56Sopenharmony_ci      print(sys.builtin_module_names)
447db96d56Sopenharmony_ci
457db96d56Sopenharmony_ci
467db96d56Sopenharmony_ciHow do I make a Python script executable on Unix?
477db96d56Sopenharmony_ci-------------------------------------------------
487db96d56Sopenharmony_ci
497db96d56Sopenharmony_ciYou need to do two things: the script file's mode must be executable and the
507db96d56Sopenharmony_cifirst line must begin with ``#!`` followed by the path of the Python
517db96d56Sopenharmony_ciinterpreter.
527db96d56Sopenharmony_ci
537db96d56Sopenharmony_ciThe first is done by executing ``chmod +x scriptfile`` or perhaps ``chmod 755
547db96d56Sopenharmony_ciscriptfile``.
557db96d56Sopenharmony_ci
567db96d56Sopenharmony_ciThe second can be done in a number of ways.  The most straightforward way is to
577db96d56Sopenharmony_ciwrite ::
587db96d56Sopenharmony_ci
597db96d56Sopenharmony_ci  #!/usr/local/bin/python
607db96d56Sopenharmony_ci
617db96d56Sopenharmony_cias the very first line of your file, using the pathname for where the Python
627db96d56Sopenharmony_ciinterpreter is installed on your platform.
637db96d56Sopenharmony_ci
647db96d56Sopenharmony_ciIf you would like the script to be independent of where the Python interpreter
657db96d56Sopenharmony_cilives, you can use the :program:`env` program.  Almost all Unix variants support
667db96d56Sopenharmony_cithe following, assuming the Python interpreter is in a directory on the user's
677db96d56Sopenharmony_ci:envvar:`PATH`::
687db96d56Sopenharmony_ci
697db96d56Sopenharmony_ci  #!/usr/bin/env python
707db96d56Sopenharmony_ci
717db96d56Sopenharmony_ci*Don't* do this for CGI scripts.  The :envvar:`PATH` variable for CGI scripts is
727db96d56Sopenharmony_cioften very minimal, so you need to use the actual absolute pathname of the
737db96d56Sopenharmony_ciinterpreter.
747db96d56Sopenharmony_ci
757db96d56Sopenharmony_ciOccasionally, a user's environment is so full that the :program:`/usr/bin/env`
767db96d56Sopenharmony_ciprogram fails; or there's no env program at all.  In that case, you can try the
777db96d56Sopenharmony_cifollowing hack (due to Alex Rezinsky):
787db96d56Sopenharmony_ci
797db96d56Sopenharmony_ci.. code-block:: sh
807db96d56Sopenharmony_ci
817db96d56Sopenharmony_ci   #! /bin/sh
827db96d56Sopenharmony_ci   """:"
837db96d56Sopenharmony_ci   exec python $0 ${1+"$@"}
847db96d56Sopenharmony_ci   """
857db96d56Sopenharmony_ci
867db96d56Sopenharmony_ciThe minor disadvantage is that this defines the script's __doc__ string.
877db96d56Sopenharmony_ciHowever, you can fix that by adding ::
887db96d56Sopenharmony_ci
897db96d56Sopenharmony_ci   __doc__ = """...Whatever..."""
907db96d56Sopenharmony_ci
917db96d56Sopenharmony_ci
927db96d56Sopenharmony_ci
937db96d56Sopenharmony_ciIs there a curses/termcap package for Python?
947db96d56Sopenharmony_ci---------------------------------------------
957db96d56Sopenharmony_ci
967db96d56Sopenharmony_ci.. XXX curses *is* built by default, isn't it?
977db96d56Sopenharmony_ci
987db96d56Sopenharmony_ciFor Unix variants: The standard Python source distribution comes with a curses
997db96d56Sopenharmony_cimodule in the :source:`Modules` subdirectory, though it's not compiled by default.
1007db96d56Sopenharmony_ci(Note that this is not available in the Windows distribution -- there is no
1017db96d56Sopenharmony_cicurses module for Windows.)
1027db96d56Sopenharmony_ci
1037db96d56Sopenharmony_ciThe :mod:`curses` module supports basic curses features as well as many additional
1047db96d56Sopenharmony_cifunctions from ncurses and SYSV curses such as colour, alternative character set
1057db96d56Sopenharmony_cisupport, pads, and mouse support. This means the module isn't compatible with
1067db96d56Sopenharmony_cioperating systems that only have BSD curses, but there don't seem to be any
1077db96d56Sopenharmony_cicurrently maintained OSes that fall into this category.
1087db96d56Sopenharmony_ci
1097db96d56Sopenharmony_ci
1107db96d56Sopenharmony_ciIs there an equivalent to C's onexit() in Python?
1117db96d56Sopenharmony_ci-------------------------------------------------
1127db96d56Sopenharmony_ci
1137db96d56Sopenharmony_ciThe :mod:`atexit` module provides a register function that is similar to C's
1147db96d56Sopenharmony_ci:c:func:`onexit`.
1157db96d56Sopenharmony_ci
1167db96d56Sopenharmony_ci
1177db96d56Sopenharmony_ciWhy don't my signal handlers work?
1187db96d56Sopenharmony_ci----------------------------------
1197db96d56Sopenharmony_ci
1207db96d56Sopenharmony_ciThe most common problem is that the signal handler is declared with the wrong
1217db96d56Sopenharmony_ciargument list.  It is called as ::
1227db96d56Sopenharmony_ci
1237db96d56Sopenharmony_ci   handler(signum, frame)
1247db96d56Sopenharmony_ci
1257db96d56Sopenharmony_ciso it should be declared with two parameters::
1267db96d56Sopenharmony_ci
1277db96d56Sopenharmony_ci   def handler(signum, frame):
1287db96d56Sopenharmony_ci       ...
1297db96d56Sopenharmony_ci
1307db96d56Sopenharmony_ci
1317db96d56Sopenharmony_ciCommon tasks
1327db96d56Sopenharmony_ci============
1337db96d56Sopenharmony_ci
1347db96d56Sopenharmony_ciHow do I test a Python program or component?
1357db96d56Sopenharmony_ci--------------------------------------------
1367db96d56Sopenharmony_ci
1377db96d56Sopenharmony_ciPython comes with two testing frameworks.  The :mod:`doctest` module finds
1387db96d56Sopenharmony_ciexamples in the docstrings for a module and runs them, comparing the output with
1397db96d56Sopenharmony_cithe expected output given in the docstring.
1407db96d56Sopenharmony_ci
1417db96d56Sopenharmony_ciThe :mod:`unittest` module is a fancier testing framework modelled on Java and
1427db96d56Sopenharmony_ciSmalltalk testing frameworks.
1437db96d56Sopenharmony_ci
1447db96d56Sopenharmony_ciTo make testing easier, you should use good modular design in your program.
1457db96d56Sopenharmony_ciYour program should have almost all functionality
1467db96d56Sopenharmony_ciencapsulated in either functions or class methods -- and this sometimes has the
1477db96d56Sopenharmony_cisurprising and delightful effect of making the program run faster (because local
1487db96d56Sopenharmony_civariable accesses are faster than global accesses).  Furthermore the program
1497db96d56Sopenharmony_cishould avoid depending on mutating global variables, since this makes testing
1507db96d56Sopenharmony_cimuch more difficult to do.
1517db96d56Sopenharmony_ci
1527db96d56Sopenharmony_ciThe "global main logic" of your program may be as simple as ::
1537db96d56Sopenharmony_ci
1547db96d56Sopenharmony_ci   if __name__ == "__main__":
1557db96d56Sopenharmony_ci       main_logic()
1567db96d56Sopenharmony_ci
1577db96d56Sopenharmony_ciat the bottom of the main module of your program.
1587db96d56Sopenharmony_ci
1597db96d56Sopenharmony_ciOnce your program is organized as a tractable collection of function and class
1607db96d56Sopenharmony_cibehaviours, you should write test functions that exercise the behaviours.  A
1617db96d56Sopenharmony_citest suite that automates a sequence of tests can be associated with each module.
1627db96d56Sopenharmony_ciThis sounds like a lot of work, but since Python is so terse and flexible it's
1637db96d56Sopenharmony_cisurprisingly easy.  You can make coding much more pleasant and fun by writing
1647db96d56Sopenharmony_ciyour test functions in parallel with the "production code", since this makes it
1657db96d56Sopenharmony_cieasy to find bugs and even design flaws earlier.
1667db96d56Sopenharmony_ci
1677db96d56Sopenharmony_ci"Support modules" that are not intended to be the main module of a program may
1687db96d56Sopenharmony_ciinclude a self-test of the module. ::
1697db96d56Sopenharmony_ci
1707db96d56Sopenharmony_ci   if __name__ == "__main__":
1717db96d56Sopenharmony_ci       self_test()
1727db96d56Sopenharmony_ci
1737db96d56Sopenharmony_ciEven programs that interact with complex external interfaces may be tested when
1747db96d56Sopenharmony_cithe external interfaces are unavailable by using "fake" interfaces implemented
1757db96d56Sopenharmony_ciin Python.
1767db96d56Sopenharmony_ci
1777db96d56Sopenharmony_ci
1787db96d56Sopenharmony_ciHow do I create documentation from doc strings?
1797db96d56Sopenharmony_ci-----------------------------------------------
1807db96d56Sopenharmony_ci
1817db96d56Sopenharmony_ciThe :mod:`pydoc` module can create HTML from the doc strings in your Python
1827db96d56Sopenharmony_cisource code.  An alternative for creating API documentation purely from
1837db96d56Sopenharmony_cidocstrings is `epydoc <https://epydoc.sourceforge.net/>`_.  `Sphinx
1847db96d56Sopenharmony_ci<https://www.sphinx-doc.org>`_ can also include docstring content.
1857db96d56Sopenharmony_ci
1867db96d56Sopenharmony_ci
1877db96d56Sopenharmony_ciHow do I get a single keypress at a time?
1887db96d56Sopenharmony_ci-----------------------------------------
1897db96d56Sopenharmony_ci
1907db96d56Sopenharmony_ciFor Unix variants there are several solutions.  It's straightforward to do this
1917db96d56Sopenharmony_ciusing curses, but curses is a fairly large module to learn.
1927db96d56Sopenharmony_ci
1937db96d56Sopenharmony_ci.. XXX this doesn't work out of the box, some IO expert needs to check why
1947db96d56Sopenharmony_ci
1957db96d56Sopenharmony_ci   Here's a solution without curses::
1967db96d56Sopenharmony_ci
1977db96d56Sopenharmony_ci   import termios, fcntl, sys, os
1987db96d56Sopenharmony_ci   fd = sys.stdin.fileno()
1997db96d56Sopenharmony_ci
2007db96d56Sopenharmony_ci   oldterm = termios.tcgetattr(fd)
2017db96d56Sopenharmony_ci   newattr = termios.tcgetattr(fd)
2027db96d56Sopenharmony_ci   newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
2037db96d56Sopenharmony_ci   termios.tcsetattr(fd, termios.TCSANOW, newattr)
2047db96d56Sopenharmony_ci
2057db96d56Sopenharmony_ci   oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
2067db96d56Sopenharmony_ci   fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
2077db96d56Sopenharmony_ci
2087db96d56Sopenharmony_ci   try:
2097db96d56Sopenharmony_ci       while True:
2107db96d56Sopenharmony_ci           try:
2117db96d56Sopenharmony_ci               c = sys.stdin.read(1)
2127db96d56Sopenharmony_ci               print("Got character", repr(c))
2137db96d56Sopenharmony_ci           except OSError:
2147db96d56Sopenharmony_ci               pass
2157db96d56Sopenharmony_ci   finally:
2167db96d56Sopenharmony_ci       termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
2177db96d56Sopenharmony_ci       fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
2187db96d56Sopenharmony_ci
2197db96d56Sopenharmony_ci   You need the :mod:`termios` and the :mod:`fcntl` module for any of this to
2207db96d56Sopenharmony_ci   work, and I've only tried it on Linux, though it should work elsewhere.  In
2217db96d56Sopenharmony_ci   this code, characters are read and printed one at a time.
2227db96d56Sopenharmony_ci
2237db96d56Sopenharmony_ci   :func:`termios.tcsetattr` turns off stdin's echoing and disables canonical
2247db96d56Sopenharmony_ci   mode.  :func:`fcntl.fnctl` is used to obtain stdin's file descriptor flags
2257db96d56Sopenharmony_ci   and modify them for non-blocking mode.  Since reading stdin when it is empty
2267db96d56Sopenharmony_ci   results in an :exc:`OSError`, this error is caught and ignored.
2277db96d56Sopenharmony_ci
2287db96d56Sopenharmony_ci   .. versionchanged:: 3.3
2297db96d56Sopenharmony_ci      *sys.stdin.read* used to raise :exc:`IOError`. Starting from Python 3.3
2307db96d56Sopenharmony_ci      :exc:`IOError` is alias for :exc:`OSError`.
2317db96d56Sopenharmony_ci
2327db96d56Sopenharmony_ci
2337db96d56Sopenharmony_ciThreads
2347db96d56Sopenharmony_ci=======
2357db96d56Sopenharmony_ci
2367db96d56Sopenharmony_ciHow do I program using threads?
2377db96d56Sopenharmony_ci-------------------------------
2387db96d56Sopenharmony_ci
2397db96d56Sopenharmony_ciBe sure to use the :mod:`threading` module and not the :mod:`_thread` module.
2407db96d56Sopenharmony_ciThe :mod:`threading` module builds convenient abstractions on top of the
2417db96d56Sopenharmony_cilow-level primitives provided by the :mod:`_thread` module.
2427db96d56Sopenharmony_ci
2437db96d56Sopenharmony_ci
2447db96d56Sopenharmony_ciNone of my threads seem to run: why?
2457db96d56Sopenharmony_ci------------------------------------
2467db96d56Sopenharmony_ci
2477db96d56Sopenharmony_ciAs soon as the main thread exits, all threads are killed.  Your main thread is
2487db96d56Sopenharmony_cirunning too quickly, giving the threads no time to do any work.
2497db96d56Sopenharmony_ci
2507db96d56Sopenharmony_ciA simple fix is to add a sleep to the end of the program that's long enough for
2517db96d56Sopenharmony_ciall the threads to finish::
2527db96d56Sopenharmony_ci
2537db96d56Sopenharmony_ci   import threading, time
2547db96d56Sopenharmony_ci
2557db96d56Sopenharmony_ci   def thread_task(name, n):
2567db96d56Sopenharmony_ci       for i in range(n):
2577db96d56Sopenharmony_ci           print(name, i)
2587db96d56Sopenharmony_ci
2597db96d56Sopenharmony_ci   for i in range(10):
2607db96d56Sopenharmony_ci       T = threading.Thread(target=thread_task, args=(str(i), i))
2617db96d56Sopenharmony_ci       T.start()
2627db96d56Sopenharmony_ci
2637db96d56Sopenharmony_ci   time.sleep(10)  # <---------------------------!
2647db96d56Sopenharmony_ci
2657db96d56Sopenharmony_ciBut now (on many platforms) the threads don't run in parallel, but appear to run
2667db96d56Sopenharmony_cisequentially, one at a time!  The reason is that the OS thread scheduler doesn't
2677db96d56Sopenharmony_cistart a new thread until the previous thread is blocked.
2687db96d56Sopenharmony_ci
2697db96d56Sopenharmony_ciA simple fix is to add a tiny sleep to the start of the run function::
2707db96d56Sopenharmony_ci
2717db96d56Sopenharmony_ci   def thread_task(name, n):
2727db96d56Sopenharmony_ci       time.sleep(0.001)  # <--------------------!
2737db96d56Sopenharmony_ci       for i in range(n):
2747db96d56Sopenharmony_ci           print(name, i)
2757db96d56Sopenharmony_ci
2767db96d56Sopenharmony_ci   for i in range(10):
2777db96d56Sopenharmony_ci       T = threading.Thread(target=thread_task, args=(str(i), i))
2787db96d56Sopenharmony_ci       T.start()
2797db96d56Sopenharmony_ci
2807db96d56Sopenharmony_ci   time.sleep(10)
2817db96d56Sopenharmony_ci
2827db96d56Sopenharmony_ciInstead of trying to guess a good delay value for :func:`time.sleep`,
2837db96d56Sopenharmony_ciit's better to use some kind of semaphore mechanism.  One idea is to use the
2847db96d56Sopenharmony_ci:mod:`queue` module to create a queue object, let each thread append a token to
2857db96d56Sopenharmony_cithe queue when it finishes, and let the main thread read as many tokens from the
2867db96d56Sopenharmony_ciqueue as there are threads.
2877db96d56Sopenharmony_ci
2887db96d56Sopenharmony_ci
2897db96d56Sopenharmony_ciHow do I parcel out work among a bunch of worker threads?
2907db96d56Sopenharmony_ci---------------------------------------------------------
2917db96d56Sopenharmony_ci
2927db96d56Sopenharmony_ciThe easiest way is to use the :mod:`concurrent.futures` module,
2937db96d56Sopenharmony_ciespecially the :mod:`~concurrent.futures.ThreadPoolExecutor` class.
2947db96d56Sopenharmony_ci
2957db96d56Sopenharmony_ciOr, if you want fine control over the dispatching algorithm, you can write
2967db96d56Sopenharmony_ciyour own logic manually.  Use the :mod:`queue` module to create a queue
2977db96d56Sopenharmony_cicontaining a list of jobs.  The :class:`~queue.Queue` class maintains a
2987db96d56Sopenharmony_cilist of objects and has a ``.put(obj)`` method that adds items to the queue and
2997db96d56Sopenharmony_cia ``.get()`` method to return them.  The class will take care of the locking
3007db96d56Sopenharmony_cinecessary to ensure that each job is handed out exactly once.
3017db96d56Sopenharmony_ci
3027db96d56Sopenharmony_ciHere's a trivial example::
3037db96d56Sopenharmony_ci
3047db96d56Sopenharmony_ci   import threading, queue, time
3057db96d56Sopenharmony_ci
3067db96d56Sopenharmony_ci   # The worker thread gets jobs off the queue.  When the queue is empty, it
3077db96d56Sopenharmony_ci   # assumes there will be no more work and exits.
3087db96d56Sopenharmony_ci   # (Realistically workers will run until terminated.)
3097db96d56Sopenharmony_ci   def worker():
3107db96d56Sopenharmony_ci       print('Running worker')
3117db96d56Sopenharmony_ci       time.sleep(0.1)
3127db96d56Sopenharmony_ci       while True:
3137db96d56Sopenharmony_ci           try:
3147db96d56Sopenharmony_ci               arg = q.get(block=False)
3157db96d56Sopenharmony_ci           except queue.Empty:
3167db96d56Sopenharmony_ci               print('Worker', threading.current_thread(), end=' ')
3177db96d56Sopenharmony_ci               print('queue empty')
3187db96d56Sopenharmony_ci               break
3197db96d56Sopenharmony_ci           else:
3207db96d56Sopenharmony_ci               print('Worker', threading.current_thread(), end=' ')
3217db96d56Sopenharmony_ci               print('running with argument', arg)
3227db96d56Sopenharmony_ci               time.sleep(0.5)
3237db96d56Sopenharmony_ci
3247db96d56Sopenharmony_ci   # Create queue
3257db96d56Sopenharmony_ci   q = queue.Queue()
3267db96d56Sopenharmony_ci
3277db96d56Sopenharmony_ci   # Start a pool of 5 workers
3287db96d56Sopenharmony_ci   for i in range(5):
3297db96d56Sopenharmony_ci       t = threading.Thread(target=worker, name='worker %i' % (i+1))
3307db96d56Sopenharmony_ci       t.start()
3317db96d56Sopenharmony_ci
3327db96d56Sopenharmony_ci   # Begin adding work to the queue
3337db96d56Sopenharmony_ci   for i in range(50):
3347db96d56Sopenharmony_ci       q.put(i)
3357db96d56Sopenharmony_ci
3367db96d56Sopenharmony_ci   # Give threads time to run
3377db96d56Sopenharmony_ci   print('Main thread sleeping')
3387db96d56Sopenharmony_ci   time.sleep(5)
3397db96d56Sopenharmony_ci
3407db96d56Sopenharmony_ciWhen run, this will produce the following output:
3417db96d56Sopenharmony_ci
3427db96d56Sopenharmony_ci.. code-block:: none
3437db96d56Sopenharmony_ci
3447db96d56Sopenharmony_ci   Running worker
3457db96d56Sopenharmony_ci   Running worker
3467db96d56Sopenharmony_ci   Running worker
3477db96d56Sopenharmony_ci   Running worker
3487db96d56Sopenharmony_ci   Running worker
3497db96d56Sopenharmony_ci   Main thread sleeping
3507db96d56Sopenharmony_ci   Worker <Thread(worker 1, started 130283832797456)> running with argument 0
3517db96d56Sopenharmony_ci   Worker <Thread(worker 2, started 130283824404752)> running with argument 1
3527db96d56Sopenharmony_ci   Worker <Thread(worker 3, started 130283816012048)> running with argument 2
3537db96d56Sopenharmony_ci   Worker <Thread(worker 4, started 130283807619344)> running with argument 3
3547db96d56Sopenharmony_ci   Worker <Thread(worker 5, started 130283799226640)> running with argument 4
3557db96d56Sopenharmony_ci   Worker <Thread(worker 1, started 130283832797456)> running with argument 5
3567db96d56Sopenharmony_ci   ...
3577db96d56Sopenharmony_ci
3587db96d56Sopenharmony_ciConsult the module's documentation for more details; the :class:`~queue.Queue`
3597db96d56Sopenharmony_ciclass provides a featureful interface.
3607db96d56Sopenharmony_ci
3617db96d56Sopenharmony_ci
3627db96d56Sopenharmony_ciWhat kinds of global value mutation are thread-safe?
3637db96d56Sopenharmony_ci----------------------------------------------------
3647db96d56Sopenharmony_ci
3657db96d56Sopenharmony_ciA :term:`global interpreter lock` (GIL) is used internally to ensure that only one
3667db96d56Sopenharmony_cithread runs in the Python VM at a time.  In general, Python offers to switch
3677db96d56Sopenharmony_ciamong threads only between bytecode instructions; how frequently it switches can
3687db96d56Sopenharmony_cibe set via :func:`sys.setswitchinterval`.  Each bytecode instruction and
3697db96d56Sopenharmony_citherefore all the C implementation code reached from each instruction is
3707db96d56Sopenharmony_citherefore atomic from the point of view of a Python program.
3717db96d56Sopenharmony_ci
3727db96d56Sopenharmony_ciIn theory, this means an exact accounting requires an exact understanding of the
3737db96d56Sopenharmony_ciPVM bytecode implementation.  In practice, it means that operations on shared
3747db96d56Sopenharmony_civariables of built-in data types (ints, lists, dicts, etc) that "look atomic"
3757db96d56Sopenharmony_cireally are.
3767db96d56Sopenharmony_ci
3777db96d56Sopenharmony_ciFor example, the following operations are all atomic (L, L1, L2 are lists, D,
3787db96d56Sopenharmony_ciD1, D2 are dicts, x, y are objects, i, j are ints)::
3797db96d56Sopenharmony_ci
3807db96d56Sopenharmony_ci   L.append(x)
3817db96d56Sopenharmony_ci   L1.extend(L2)
3827db96d56Sopenharmony_ci   x = L[i]
3837db96d56Sopenharmony_ci   x = L.pop()
3847db96d56Sopenharmony_ci   L1[i:j] = L2
3857db96d56Sopenharmony_ci   L.sort()
3867db96d56Sopenharmony_ci   x = y
3877db96d56Sopenharmony_ci   x.field = y
3887db96d56Sopenharmony_ci   D[x] = y
3897db96d56Sopenharmony_ci   D1.update(D2)
3907db96d56Sopenharmony_ci   D.keys()
3917db96d56Sopenharmony_ci
3927db96d56Sopenharmony_ciThese aren't::
3937db96d56Sopenharmony_ci
3947db96d56Sopenharmony_ci   i = i+1
3957db96d56Sopenharmony_ci   L.append(L[-1])
3967db96d56Sopenharmony_ci   L[i] = L[j]
3977db96d56Sopenharmony_ci   D[x] = D[x] + 1
3987db96d56Sopenharmony_ci
3997db96d56Sopenharmony_ciOperations that replace other objects may invoke those other objects'
4007db96d56Sopenharmony_ci:meth:`__del__` method when their reference count reaches zero, and that can
4017db96d56Sopenharmony_ciaffect things.  This is especially true for the mass updates to dictionaries and
4027db96d56Sopenharmony_cilists.  When in doubt, use a mutex!
4037db96d56Sopenharmony_ci
4047db96d56Sopenharmony_ci
4057db96d56Sopenharmony_ciCan't we get rid of the Global Interpreter Lock?
4067db96d56Sopenharmony_ci------------------------------------------------
4077db96d56Sopenharmony_ci
4087db96d56Sopenharmony_ci.. XXX link to dbeazley's talk about GIL?
4097db96d56Sopenharmony_ci
4107db96d56Sopenharmony_ciThe :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's
4117db96d56Sopenharmony_cideployment on high-end multiprocessor server machines, because a multi-threaded
4127db96d56Sopenharmony_ciPython program effectively only uses one CPU, due to the insistence that
4137db96d56Sopenharmony_ci(almost) all Python code can only run while the GIL is held.
4147db96d56Sopenharmony_ci
4157db96d56Sopenharmony_ciBack in the days of Python 1.5, Greg Stein actually implemented a comprehensive
4167db96d56Sopenharmony_cipatch set (the "free threading" patches) that removed the GIL and replaced it
4177db96d56Sopenharmony_ciwith fine-grained locking.  Adam Olsen recently did a similar experiment
4187db96d56Sopenharmony_ciin his `python-safethread <https://code.google.com/archive/p/python-safethread>`_
4197db96d56Sopenharmony_ciproject.  Unfortunately, both experiments exhibited a sharp drop in single-thread
4207db96d56Sopenharmony_ciperformance (at least 30% slower), due to the amount of fine-grained locking
4217db96d56Sopenharmony_cinecessary to compensate for the removal of the GIL.
4227db96d56Sopenharmony_ci
4237db96d56Sopenharmony_ciThis doesn't mean that you can't make good use of Python on multi-CPU machines!
4247db96d56Sopenharmony_ciYou just have to be creative with dividing the work up between multiple
4257db96d56Sopenharmony_ci*processes* rather than multiple *threads*.  The
4267db96d56Sopenharmony_ci:class:`~concurrent.futures.ProcessPoolExecutor` class in the new
4277db96d56Sopenharmony_ci:mod:`concurrent.futures` module provides an easy way of doing so; the
4287db96d56Sopenharmony_ci:mod:`multiprocessing` module provides a lower-level API in case you want
4297db96d56Sopenharmony_cimore control over dispatching of tasks.
4307db96d56Sopenharmony_ci
4317db96d56Sopenharmony_ciJudicious use of C extensions will also help; if you use a C extension to
4327db96d56Sopenharmony_ciperform a time-consuming task, the extension can release the GIL while the
4337db96d56Sopenharmony_cithread of execution is in the C code and allow other threads to get some work
4347db96d56Sopenharmony_cidone.  Some standard library modules such as :mod:`zlib` and :mod:`hashlib`
4357db96d56Sopenharmony_cialready do this.
4367db96d56Sopenharmony_ci
4377db96d56Sopenharmony_ciIt has been suggested that the GIL should be a per-interpreter-state lock rather
4387db96d56Sopenharmony_cithan truly global; interpreters then wouldn't be able to share objects.
4397db96d56Sopenharmony_ciUnfortunately, this isn't likely to happen either.  It would be a tremendous
4407db96d56Sopenharmony_ciamount of work, because many object implementations currently have global state.
4417db96d56Sopenharmony_ciFor example, small integers and short strings are cached; these caches would
4427db96d56Sopenharmony_cihave to be moved to the interpreter state.  Other object types have their own
4437db96d56Sopenharmony_cifree list; these free lists would have to be moved to the interpreter state.
4447db96d56Sopenharmony_ciAnd so on.
4457db96d56Sopenharmony_ci
4467db96d56Sopenharmony_ciAnd I doubt that it can even be done in finite time, because the same problem
4477db96d56Sopenharmony_ciexists for 3rd party extensions.  It is likely that 3rd party extensions are
4487db96d56Sopenharmony_cibeing written at a faster rate than you can convert them to store all their
4497db96d56Sopenharmony_ciglobal state in the interpreter state.
4507db96d56Sopenharmony_ci
4517db96d56Sopenharmony_ciAnd finally, once you have multiple interpreters not sharing any state, what
4527db96d56Sopenharmony_cihave you gained over running each interpreter in a separate process?
4537db96d56Sopenharmony_ci
4547db96d56Sopenharmony_ci
4557db96d56Sopenharmony_ciInput and Output
4567db96d56Sopenharmony_ci================
4577db96d56Sopenharmony_ci
4587db96d56Sopenharmony_ciHow do I delete a file? (And other file questions...)
4597db96d56Sopenharmony_ci-----------------------------------------------------
4607db96d56Sopenharmony_ci
4617db96d56Sopenharmony_ciUse ``os.remove(filename)`` or ``os.unlink(filename)``; for documentation, see
4627db96d56Sopenharmony_cithe :mod:`os` module.  The two functions are identical; :func:`~os.unlink` is simply
4637db96d56Sopenharmony_cithe name of the Unix system call for this function.
4647db96d56Sopenharmony_ci
4657db96d56Sopenharmony_ciTo remove a directory, use :func:`os.rmdir`; use :func:`os.mkdir` to create one.
4667db96d56Sopenharmony_ci``os.makedirs(path)`` will create any intermediate directories in ``path`` that
4677db96d56Sopenharmony_cidon't exist. ``os.removedirs(path)`` will remove intermediate directories as
4687db96d56Sopenharmony_cilong as they're empty; if you want to delete an entire directory tree and its
4697db96d56Sopenharmony_cicontents, use :func:`shutil.rmtree`.
4707db96d56Sopenharmony_ci
4717db96d56Sopenharmony_ciTo rename a file, use ``os.rename(old_path, new_path)``.
4727db96d56Sopenharmony_ci
4737db96d56Sopenharmony_ciTo truncate a file, open it using ``f = open(filename, "rb+")``, and use
4747db96d56Sopenharmony_ci``f.truncate(offset)``; offset defaults to the current seek position.  There's
4757db96d56Sopenharmony_cialso ``os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where
4767db96d56Sopenharmony_ci*fd* is the file descriptor (a small integer).
4777db96d56Sopenharmony_ci
4787db96d56Sopenharmony_ciThe :mod:`shutil` module also contains a number of functions to work on files
4797db96d56Sopenharmony_ciincluding :func:`~shutil.copyfile`, :func:`~shutil.copytree`, and
4807db96d56Sopenharmony_ci:func:`~shutil.rmtree`.
4817db96d56Sopenharmony_ci
4827db96d56Sopenharmony_ci
4837db96d56Sopenharmony_ciHow do I copy a file?
4847db96d56Sopenharmony_ci---------------------
4857db96d56Sopenharmony_ci
4867db96d56Sopenharmony_ciThe :mod:`shutil` module contains a :func:`~shutil.copyfile` function.
4877db96d56Sopenharmony_ciNote that on Windows NTFS volumes, it does not copy
4887db96d56Sopenharmony_ci`alternate data streams
4897db96d56Sopenharmony_ci<https://en.wikipedia.org/wiki/NTFS#Alternate_data_stream_(ADS)>`_
4907db96d56Sopenharmony_cinor `resource forks <https://en.wikipedia.org/wiki/Resource_fork>`__
4917db96d56Sopenharmony_cion macOS HFS+ volumes, though both are now rarely used.
4927db96d56Sopenharmony_ciIt also doesn't copy file permissions and metadata, though using
4937db96d56Sopenharmony_ci:func:`shutil.copy2` instead will preserve most (though not all) of it.
4947db96d56Sopenharmony_ci
4957db96d56Sopenharmony_ci
4967db96d56Sopenharmony_ciHow do I read (or write) binary data?
4977db96d56Sopenharmony_ci-------------------------------------
4987db96d56Sopenharmony_ci
4997db96d56Sopenharmony_ciTo read or write complex binary data formats, it's best to use the :mod:`struct`
5007db96d56Sopenharmony_cimodule.  It allows you to take a string containing binary data (usually numbers)
5017db96d56Sopenharmony_ciand convert it to Python objects; and vice versa.
5027db96d56Sopenharmony_ci
5037db96d56Sopenharmony_ciFor example, the following code reads two 2-byte integers and one 4-byte integer
5047db96d56Sopenharmony_ciin big-endian format from a file::
5057db96d56Sopenharmony_ci
5067db96d56Sopenharmony_ci   import struct
5077db96d56Sopenharmony_ci
5087db96d56Sopenharmony_ci   with open(filename, "rb") as f:
5097db96d56Sopenharmony_ci       s = f.read(8)
5107db96d56Sopenharmony_ci       x, y, z = struct.unpack(">hhl", s)
5117db96d56Sopenharmony_ci
5127db96d56Sopenharmony_ciThe '>' in the format string forces big-endian data; the letter 'h' reads one
5137db96d56Sopenharmony_ci"short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the
5147db96d56Sopenharmony_cistring.
5157db96d56Sopenharmony_ci
5167db96d56Sopenharmony_ciFor data that is more regular (e.g. a homogeneous list of ints or floats),
5177db96d56Sopenharmony_ciyou can also use the :mod:`array` module.
5187db96d56Sopenharmony_ci
5197db96d56Sopenharmony_ci.. note::
5207db96d56Sopenharmony_ci
5217db96d56Sopenharmony_ci   To read and write binary data, it is mandatory to open the file in
5227db96d56Sopenharmony_ci   binary mode (here, passing ``"rb"`` to :func:`open`).  If you use
5237db96d56Sopenharmony_ci   ``"r"`` instead (the default), the file will be open in text mode
5247db96d56Sopenharmony_ci   and ``f.read()`` will return :class:`str` objects rather than
5257db96d56Sopenharmony_ci   :class:`bytes` objects.
5267db96d56Sopenharmony_ci
5277db96d56Sopenharmony_ci
5287db96d56Sopenharmony_ciI can't seem to use os.read() on a pipe created with os.popen(); why?
5297db96d56Sopenharmony_ci---------------------------------------------------------------------
5307db96d56Sopenharmony_ci
5317db96d56Sopenharmony_ci:func:`os.read` is a low-level function which takes a file descriptor, a small
5327db96d56Sopenharmony_ciinteger representing the opened file.  :func:`os.popen` creates a high-level
5337db96d56Sopenharmony_cifile object, the same type returned by the built-in :func:`open` function.
5347db96d56Sopenharmony_ciThus, to read *n* bytes from a pipe *p* created with :func:`os.popen`, you need to
5357db96d56Sopenharmony_ciuse ``p.read(n)``.
5367db96d56Sopenharmony_ci
5377db96d56Sopenharmony_ci
5387db96d56Sopenharmony_ci.. XXX update to use subprocess. See the :ref:`subprocess-replacements` section.
5397db96d56Sopenharmony_ci
5407db96d56Sopenharmony_ci   How do I run a subprocess with pipes connected to both input and output?
5417db96d56Sopenharmony_ci   ------------------------------------------------------------------------
5427db96d56Sopenharmony_ci
5437db96d56Sopenharmony_ci   Use the :mod:`popen2` module.  For example::
5447db96d56Sopenharmony_ci
5457db96d56Sopenharmony_ci      import popen2
5467db96d56Sopenharmony_ci      fromchild, tochild = popen2.popen2("command")
5477db96d56Sopenharmony_ci      tochild.write("input\n")
5487db96d56Sopenharmony_ci      tochild.flush()
5497db96d56Sopenharmony_ci      output = fromchild.readline()
5507db96d56Sopenharmony_ci
5517db96d56Sopenharmony_ci   Warning: in general it is unwise to do this because you can easily cause a
5527db96d56Sopenharmony_ci   deadlock where your process is blocked waiting for output from the child
5537db96d56Sopenharmony_ci   while the child is blocked waiting for input from you.  This can be caused
5547db96d56Sopenharmony_ci   by the parent expecting the child to output more text than it does or
5557db96d56Sopenharmony_ci   by data being stuck in stdio buffers due to lack of flushing.
5567db96d56Sopenharmony_ci   The Python parent can of course explicitly flush the data it sends to the
5577db96d56Sopenharmony_ci   child before it reads any output, but if the child is a naive C program it
5587db96d56Sopenharmony_ci   may have been written to never explicitly flush its output, even if it is
5597db96d56Sopenharmony_ci   interactive, since flushing is normally automatic.
5607db96d56Sopenharmony_ci
5617db96d56Sopenharmony_ci   Note that a deadlock is also possible if you use :func:`popen3` to read
5627db96d56Sopenharmony_ci   stdout and stderr. If one of the two is too large for the internal buffer
5637db96d56Sopenharmony_ci   (increasing the buffer size does not help) and you ``read()`` the other one
5647db96d56Sopenharmony_ci   first, there is a deadlock, too.
5657db96d56Sopenharmony_ci
5667db96d56Sopenharmony_ci   Note on a bug in popen2: unless your program calls ``wait()`` or
5677db96d56Sopenharmony_ci   ``waitpid()``, finished child processes are never removed, and eventually
5687db96d56Sopenharmony_ci   calls to popen2 will fail because of a limit on the number of child
5697db96d56Sopenharmony_ci   processes.  Calling :func:`os.waitpid` with the :data:`os.WNOHANG` option can
5707db96d56Sopenharmony_ci   prevent this; a good place to insert such a call would be before calling
5717db96d56Sopenharmony_ci   ``popen2`` again.
5727db96d56Sopenharmony_ci
5737db96d56Sopenharmony_ci   In many cases, all you really need is to run some data through a command and
5747db96d56Sopenharmony_ci   get the result back.  Unless the amount of data is very large, the easiest
5757db96d56Sopenharmony_ci   way to do this is to write it to a temporary file and run the command with
5767db96d56Sopenharmony_ci   that temporary file as input.  The standard module :mod:`tempfile` exports a
5777db96d56Sopenharmony_ci   :func:`~tempfile.mktemp` function to generate unique temporary file names. ::
5787db96d56Sopenharmony_ci
5797db96d56Sopenharmony_ci      import tempfile
5807db96d56Sopenharmony_ci      import os
5817db96d56Sopenharmony_ci
5827db96d56Sopenharmony_ci      class Popen3:
5837db96d56Sopenharmony_ci          """
5847db96d56Sopenharmony_ci          This is a deadlock-safe version of popen that returns
5857db96d56Sopenharmony_ci          an object with errorlevel, out (a string) and err (a string).
5867db96d56Sopenharmony_ci          (capturestderr may not work under windows.)
5877db96d56Sopenharmony_ci          Example: print(Popen3('grep spam','\n\nhere spam\n\n').out)
5887db96d56Sopenharmony_ci          """
5897db96d56Sopenharmony_ci          def __init__(self,command,input=None,capturestderr=None):
5907db96d56Sopenharmony_ci              outfile=tempfile.mktemp()
5917db96d56Sopenharmony_ci              command="( %s ) > %s" % (command,outfile)
5927db96d56Sopenharmony_ci              if input:
5937db96d56Sopenharmony_ci                  infile=tempfile.mktemp()
5947db96d56Sopenharmony_ci                  open(infile,"w").write(input)
5957db96d56Sopenharmony_ci                  command=command+" <"+infile
5967db96d56Sopenharmony_ci              if capturestderr:
5977db96d56Sopenharmony_ci                  errfile=tempfile.mktemp()
5987db96d56Sopenharmony_ci                  command=command+" 2>"+errfile
5997db96d56Sopenharmony_ci              self.errorlevel=os.system(command) >> 8
6007db96d56Sopenharmony_ci              self.out=open(outfile,"r").read()
6017db96d56Sopenharmony_ci              os.remove(outfile)
6027db96d56Sopenharmony_ci              if input:
6037db96d56Sopenharmony_ci                  os.remove(infile)
6047db96d56Sopenharmony_ci              if capturestderr:
6057db96d56Sopenharmony_ci                  self.err=open(errfile,"r").read()
6067db96d56Sopenharmony_ci                  os.remove(errfile)
6077db96d56Sopenharmony_ci
6087db96d56Sopenharmony_ci   Note that many interactive programs (e.g. vi) don't work well with pipes
6097db96d56Sopenharmony_ci   substituted for standard input and output.  You will have to use pseudo ttys
6107db96d56Sopenharmony_ci   ("ptys") instead of pipes. Or you can use a Python interface to Don Libes'
6117db96d56Sopenharmony_ci   "expect" library.  A Python extension that interfaces to expect is called
6127db96d56Sopenharmony_ci   "expy" and available from https://expectpy.sourceforge.net.  A pure Python
6137db96d56Sopenharmony_ci   solution that works like expect is `pexpect
6147db96d56Sopenharmony_ci   <https://pypi.org/project/pexpect/>`_.
6157db96d56Sopenharmony_ci
6167db96d56Sopenharmony_ci
6177db96d56Sopenharmony_ciHow do I access the serial (RS232) port?
6187db96d56Sopenharmony_ci----------------------------------------
6197db96d56Sopenharmony_ci
6207db96d56Sopenharmony_ciFor Win32, OSX, Linux, BSD, Jython, IronPython:
6217db96d56Sopenharmony_ci
6227db96d56Sopenharmony_ci   https://pypi.org/project/pyserial/
6237db96d56Sopenharmony_ci
6247db96d56Sopenharmony_ciFor Unix, see a Usenet post by Mitch Chapman:
6257db96d56Sopenharmony_ci
6267db96d56Sopenharmony_ci   https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com
6277db96d56Sopenharmony_ci
6287db96d56Sopenharmony_ci
6297db96d56Sopenharmony_ciWhy doesn't closing sys.stdout (stdin, stderr) really close it?
6307db96d56Sopenharmony_ci---------------------------------------------------------------
6317db96d56Sopenharmony_ci
6327db96d56Sopenharmony_ciPython :term:`file objects <file object>` are a high-level layer of
6337db96d56Sopenharmony_ciabstraction on low-level C file descriptors.
6347db96d56Sopenharmony_ci
6357db96d56Sopenharmony_ciFor most file objects you create in Python via the built-in :func:`open`
6367db96d56Sopenharmony_cifunction, ``f.close()`` marks the Python file object as being closed from
6377db96d56Sopenharmony_ciPython's point of view, and also arranges to close the underlying C file
6387db96d56Sopenharmony_cidescriptor.  This also happens automatically in ``f``'s destructor, when
6397db96d56Sopenharmony_ci``f`` becomes garbage.
6407db96d56Sopenharmony_ci
6417db96d56Sopenharmony_ciBut stdin, stdout and stderr are treated specially by Python, because of the
6427db96d56Sopenharmony_cispecial status also given to them by C.  Running ``sys.stdout.close()`` marks
6437db96d56Sopenharmony_cithe Python-level file object as being closed, but does *not* close the
6447db96d56Sopenharmony_ciassociated C file descriptor.
6457db96d56Sopenharmony_ci
6467db96d56Sopenharmony_ciTo close the underlying C file descriptor for one of these three, you should
6477db96d56Sopenharmony_cifirst be sure that's what you really want to do (e.g., you may confuse
6487db96d56Sopenharmony_ciextension modules trying to do I/O).  If it is, use :func:`os.close`::
6497db96d56Sopenharmony_ci
6507db96d56Sopenharmony_ci   os.close(stdin.fileno())
6517db96d56Sopenharmony_ci   os.close(stdout.fileno())
6527db96d56Sopenharmony_ci   os.close(stderr.fileno())
6537db96d56Sopenharmony_ci
6547db96d56Sopenharmony_ciOr you can use the numeric constants 0, 1 and 2, respectively.
6557db96d56Sopenharmony_ci
6567db96d56Sopenharmony_ci
6577db96d56Sopenharmony_ciNetwork/Internet Programming
6587db96d56Sopenharmony_ci============================
6597db96d56Sopenharmony_ci
6607db96d56Sopenharmony_ciWhat WWW tools are there for Python?
6617db96d56Sopenharmony_ci------------------------------------
6627db96d56Sopenharmony_ci
6637db96d56Sopenharmony_ciSee the chapters titled :ref:`internet` and :ref:`netdata` in the Library
6647db96d56Sopenharmony_ciReference Manual.  Python has many modules that will help you build server-side
6657db96d56Sopenharmony_ciand client-side web systems.
6667db96d56Sopenharmony_ci
6677db96d56Sopenharmony_ci.. XXX check if wiki page is still up to date
6687db96d56Sopenharmony_ci
6697db96d56Sopenharmony_ciA summary of available frameworks is maintained by Paul Boddie at
6707db96d56Sopenharmony_cihttps://wiki.python.org/moin/WebProgramming\ .
6717db96d56Sopenharmony_ci
6727db96d56Sopenharmony_ciCameron Laird maintains a useful set of pages about Python web technologies at
6737db96d56Sopenharmony_cihttps://web.archive.org/web/20210224183619/http://phaseit.net/claird/comp.lang.python/web_python.
6747db96d56Sopenharmony_ci
6757db96d56Sopenharmony_ci
6767db96d56Sopenharmony_ciHow can I mimic CGI form submission (METHOD=POST)?
6777db96d56Sopenharmony_ci--------------------------------------------------
6787db96d56Sopenharmony_ci
6797db96d56Sopenharmony_ciI would like to retrieve web pages that are the result of POSTing a form. Is
6807db96d56Sopenharmony_cithere existing code that would let me do this easily?
6817db96d56Sopenharmony_ci
6827db96d56Sopenharmony_ciYes. Here's a simple example that uses :mod:`urllib.request`::
6837db96d56Sopenharmony_ci
6847db96d56Sopenharmony_ci   #!/usr/local/bin/python
6857db96d56Sopenharmony_ci
6867db96d56Sopenharmony_ci   import urllib.request
6877db96d56Sopenharmony_ci
6887db96d56Sopenharmony_ci   # build the query string
6897db96d56Sopenharmony_ci   qs = "First=Josephine&MI=Q&Last=Public"
6907db96d56Sopenharmony_ci
6917db96d56Sopenharmony_ci   # connect and send the server a path
6927db96d56Sopenharmony_ci   req = urllib.request.urlopen('http://www.some-server.out-there'
6937db96d56Sopenharmony_ci                                '/cgi-bin/some-cgi-script', data=qs)
6947db96d56Sopenharmony_ci   with req:
6957db96d56Sopenharmony_ci       msg, hdrs = req.read(), req.info()
6967db96d56Sopenharmony_ci
6977db96d56Sopenharmony_ciNote that in general for percent-encoded POST operations, query strings must be
6987db96d56Sopenharmony_ciquoted using :func:`urllib.parse.urlencode`.  For example, to send
6997db96d56Sopenharmony_ci``name=Guy Steele, Jr.``::
7007db96d56Sopenharmony_ci
7017db96d56Sopenharmony_ci   >>> import urllib.parse
7027db96d56Sopenharmony_ci   >>> urllib.parse.urlencode({'name': 'Guy Steele, Jr.'})
7037db96d56Sopenharmony_ci   'name=Guy+Steele%2C+Jr.'
7047db96d56Sopenharmony_ci
7057db96d56Sopenharmony_ci.. seealso:: :ref:`urllib-howto` for extensive examples.
7067db96d56Sopenharmony_ci
7077db96d56Sopenharmony_ci
7087db96d56Sopenharmony_ciWhat module should I use to help with generating HTML?
7097db96d56Sopenharmony_ci------------------------------------------------------
7107db96d56Sopenharmony_ci
7117db96d56Sopenharmony_ci.. XXX add modern template languages
7127db96d56Sopenharmony_ci
7137db96d56Sopenharmony_ciYou can find a collection of useful links on the `Web Programming wiki page
7147db96d56Sopenharmony_ci<https://wiki.python.org/moin/WebProgramming>`_.
7157db96d56Sopenharmony_ci
7167db96d56Sopenharmony_ci
7177db96d56Sopenharmony_ciHow do I send mail from a Python script?
7187db96d56Sopenharmony_ci----------------------------------------
7197db96d56Sopenharmony_ci
7207db96d56Sopenharmony_ciUse the standard library module :mod:`smtplib`.
7217db96d56Sopenharmony_ci
7227db96d56Sopenharmony_ciHere's a very simple interactive mail sender that uses it.  This method will
7237db96d56Sopenharmony_ciwork on any host that supports an SMTP listener. ::
7247db96d56Sopenharmony_ci
7257db96d56Sopenharmony_ci   import sys, smtplib
7267db96d56Sopenharmony_ci
7277db96d56Sopenharmony_ci   fromaddr = input("From: ")
7287db96d56Sopenharmony_ci   toaddrs  = input("To: ").split(',')
7297db96d56Sopenharmony_ci   print("Enter message, end with ^D:")
7307db96d56Sopenharmony_ci   msg = ''
7317db96d56Sopenharmony_ci   while True:
7327db96d56Sopenharmony_ci       line = sys.stdin.readline()
7337db96d56Sopenharmony_ci       if not line:
7347db96d56Sopenharmony_ci           break
7357db96d56Sopenharmony_ci       msg += line
7367db96d56Sopenharmony_ci
7377db96d56Sopenharmony_ci   # The actual mail send
7387db96d56Sopenharmony_ci   server = smtplib.SMTP('localhost')
7397db96d56Sopenharmony_ci   server.sendmail(fromaddr, toaddrs, msg)
7407db96d56Sopenharmony_ci   server.quit()
7417db96d56Sopenharmony_ci
7427db96d56Sopenharmony_ciA Unix-only alternative uses sendmail.  The location of the sendmail program
7437db96d56Sopenharmony_civaries between systems; sometimes it is ``/usr/lib/sendmail``, sometimes
7447db96d56Sopenharmony_ci``/usr/sbin/sendmail``.  The sendmail manual page will help you out.  Here's
7457db96d56Sopenharmony_cisome sample code::
7467db96d56Sopenharmony_ci
7477db96d56Sopenharmony_ci   import os
7487db96d56Sopenharmony_ci
7497db96d56Sopenharmony_ci   SENDMAIL = "/usr/sbin/sendmail"  # sendmail location
7507db96d56Sopenharmony_ci   p = os.popen("%s -t -i" % SENDMAIL, "w")
7517db96d56Sopenharmony_ci   p.write("To: receiver@example.com\n")
7527db96d56Sopenharmony_ci   p.write("Subject: test\n")
7537db96d56Sopenharmony_ci   p.write("\n")  # blank line separating headers from body
7547db96d56Sopenharmony_ci   p.write("Some text\n")
7557db96d56Sopenharmony_ci   p.write("some more text\n")
7567db96d56Sopenharmony_ci   sts = p.close()
7577db96d56Sopenharmony_ci   if sts != 0:
7587db96d56Sopenharmony_ci       print("Sendmail exit status", sts)
7597db96d56Sopenharmony_ci
7607db96d56Sopenharmony_ci
7617db96d56Sopenharmony_ciHow do I avoid blocking in the connect() method of a socket?
7627db96d56Sopenharmony_ci------------------------------------------------------------
7637db96d56Sopenharmony_ci
7647db96d56Sopenharmony_ciThe :mod:`select` module is commonly used to help with asynchronous I/O on
7657db96d56Sopenharmony_cisockets.
7667db96d56Sopenharmony_ci
7677db96d56Sopenharmony_ciTo prevent the TCP connect from blocking, you can set the socket to non-blocking
7687db96d56Sopenharmony_cimode.  Then when you do the :meth:`socket.connect`, you will either connect immediately
7697db96d56Sopenharmony_ci(unlikely) or get an exception that contains the error number as ``.errno``.
7707db96d56Sopenharmony_ci``errno.EINPROGRESS`` indicates that the connection is in progress, but hasn't
7717db96d56Sopenharmony_cifinished yet.  Different OSes will return different values, so you're going to
7727db96d56Sopenharmony_cihave to check what's returned on your system.
7737db96d56Sopenharmony_ci
7747db96d56Sopenharmony_ciYou can use the :meth:`socket.connect_ex` method to avoid creating an exception.  It will
7757db96d56Sopenharmony_cijust return the errno value.  To poll, you can call :meth:`socket.connect_ex` again later
7767db96d56Sopenharmony_ci-- ``0`` or ``errno.EISCONN`` indicate that you're connected -- or you can pass this
7777db96d56Sopenharmony_cisocket to :meth:`select.select` to check if it's writable.
7787db96d56Sopenharmony_ci
7797db96d56Sopenharmony_ci.. note::
7807db96d56Sopenharmony_ci   The :mod:`asyncio` module provides a general purpose single-threaded and
7817db96d56Sopenharmony_ci   concurrent asynchronous library, which can be used for writing non-blocking
7827db96d56Sopenharmony_ci   network code.
7837db96d56Sopenharmony_ci   The third-party `Twisted <https://twisted.org/>`_ library is
7847db96d56Sopenharmony_ci   a popular and feature-rich alternative.
7857db96d56Sopenharmony_ci
7867db96d56Sopenharmony_ci
7877db96d56Sopenharmony_ciDatabases
7887db96d56Sopenharmony_ci=========
7897db96d56Sopenharmony_ci
7907db96d56Sopenharmony_ciAre there any interfaces to database packages in Python?
7917db96d56Sopenharmony_ci--------------------------------------------------------
7927db96d56Sopenharmony_ci
7937db96d56Sopenharmony_ciYes.
7947db96d56Sopenharmony_ci
7957db96d56Sopenharmony_ciInterfaces to disk-based hashes such as :mod:`DBM <dbm.ndbm>` and :mod:`GDBM
7967db96d56Sopenharmony_ci<dbm.gnu>` are also included with standard Python.  There is also the
7977db96d56Sopenharmony_ci:mod:`sqlite3` module, which provides a lightweight disk-based relational
7987db96d56Sopenharmony_cidatabase.
7997db96d56Sopenharmony_ci
8007db96d56Sopenharmony_ciSupport for most relational databases is available.  See the
8017db96d56Sopenharmony_ci`DatabaseProgramming wiki page
8027db96d56Sopenharmony_ci<https://wiki.python.org/moin/DatabaseProgramming>`_ for details.
8037db96d56Sopenharmony_ci
8047db96d56Sopenharmony_ci
8057db96d56Sopenharmony_ciHow do you implement persistent objects in Python?
8067db96d56Sopenharmony_ci--------------------------------------------------
8077db96d56Sopenharmony_ci
8087db96d56Sopenharmony_ciThe :mod:`pickle` library module solves this in a very general way (though you
8097db96d56Sopenharmony_cistill can't store things like open files, sockets or windows), and the
8107db96d56Sopenharmony_ci:mod:`shelve` library module uses pickle and (g)dbm to create persistent
8117db96d56Sopenharmony_cimappings containing arbitrary Python objects.
8127db96d56Sopenharmony_ci
8137db96d56Sopenharmony_ci
8147db96d56Sopenharmony_ciMathematics and Numerics
8157db96d56Sopenharmony_ci========================
8167db96d56Sopenharmony_ci
8177db96d56Sopenharmony_ciHow do I generate random numbers in Python?
8187db96d56Sopenharmony_ci-------------------------------------------
8197db96d56Sopenharmony_ci
8207db96d56Sopenharmony_ciThe standard module :mod:`random` implements a random number generator.  Usage
8217db96d56Sopenharmony_ciis simple::
8227db96d56Sopenharmony_ci
8237db96d56Sopenharmony_ci   import random
8247db96d56Sopenharmony_ci   random.random()
8257db96d56Sopenharmony_ci
8267db96d56Sopenharmony_ciThis returns a random floating point number in the range [0, 1).
8277db96d56Sopenharmony_ci
8287db96d56Sopenharmony_ciThere are also many other specialized generators in this module, such as:
8297db96d56Sopenharmony_ci
8307db96d56Sopenharmony_ci* ``randrange(a, b)`` chooses an integer in the range [a, b).
8317db96d56Sopenharmony_ci* ``uniform(a, b)`` chooses a floating point number in the range [a, b).
8327db96d56Sopenharmony_ci* ``normalvariate(mean, sdev)`` samples the normal (Gaussian) distribution.
8337db96d56Sopenharmony_ci
8347db96d56Sopenharmony_ciSome higher-level functions operate on sequences directly, such as:
8357db96d56Sopenharmony_ci
8367db96d56Sopenharmony_ci* ``choice(S)`` chooses a random element from a given sequence.
8377db96d56Sopenharmony_ci* ``shuffle(L)`` shuffles a list in-place, i.e. permutes it randomly.
8387db96d56Sopenharmony_ci
8397db96d56Sopenharmony_ciThere's also a ``Random`` class you can instantiate to create independent
8407db96d56Sopenharmony_cimultiple random number generators.
841