library.html 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
  6. <meta property="og:title" content="Library and Extension FAQ" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/faq/library.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Contents: Library and Extension FAQ- General Library Questions- How do I find a module or application to perform task X?, Where is the math.py (socket.py, regex.py, etc.) source file?, How do I mak..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Contents: Library and Extension FAQ- General Library Questions- How do I find a module or application to perform task X?, Where is the math.py (socket.py, regex.py, etc.) source file?, How do I mak..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>Library and Extension FAQ &#8212; Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
  21. <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
  22. <script src="../_static/jquery.js"></script>
  23. <script src="../_static/underscore.js"></script>
  24. <script src="../_static/doctools.js"></script>
  25. <script src="../_static/sidebar.js"></script>
  26. <link rel="search" type="application/opensearchdescription+xml"
  27. title="Search within Python 3.12.0 documentation"
  28. href="../_static/opensearch.xml"/>
  29. <link rel="author" title="About these documents" href="../about.html" />
  30. <link rel="index" title="Index" href="../genindex.html" />
  31. <link rel="search" title="Search" href="../search.html" />
  32. <link rel="copyright" title="Copyright" href="../copyright.html" />
  33. <link rel="next" title="Extending/Embedding FAQ" href="extending.html" />
  34. <link rel="prev" title="Design and History FAQ" href="design.html" />
  35. <link rel="canonical" href="https://docs.python.org/3/faq/library.html" />
  36. <style>
  37. @media only screen {
  38. table.full-width-table {
  39. width: 100%;
  40. }
  41. }
  42. </style>
  43. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  44. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  45. <script type="text/javascript" src="../_static/copybutton.js"></script>
  46. <script type="text/javascript" src="../_static/menu.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">Library and Extension FAQ</a><ul>
  86. <li><a class="reference internal" href="#general-library-questions">General Library Questions</a></li>
  87. <li><a class="reference internal" href="#common-tasks">Common tasks</a></li>
  88. <li><a class="reference internal" href="#threads">Threads</a></li>
  89. <li><a class="reference internal" href="#input-and-output">Input and Output</a></li>
  90. <li><a class="reference internal" href="#network-internet-programming">Network/Internet Programming</a></li>
  91. <li><a class="reference internal" href="#databases">Databases</a></li>
  92. <li><a class="reference internal" href="#mathematics-and-numerics">Mathematics and Numerics</a></li>
  93. </ul>
  94. </li>
  95. </ul>
  96. </div>
  97. <div>
  98. <h4>Previous topic</h4>
  99. <p class="topless"><a href="design.html"
  100. title="previous chapter">Design and History FAQ</a></p>
  101. </div>
  102. <div>
  103. <h4>Next topic</h4>
  104. <p class="topless"><a href="extending.html"
  105. title="next chapter">Extending/Embedding FAQ</a></p>
  106. </div>
  107. <div role="note" aria-label="source link">
  108. <h3>This Page</h3>
  109. <ul class="this-page-menu">
  110. <li><a href="../bugs.html">Report a Bug</a></li>
  111. <li>
  112. <a href="https://github.com/python/cpython/blob/main/Doc/faq/library.rst"
  113. rel="nofollow">Show Source
  114. </a>
  115. </li>
  116. </ul>
  117. </div>
  118. </nav>
  119. </div>
  120. </div>
  121. <div class="related" role="navigation" aria-label="related navigation">
  122. <h3>Navigation</h3>
  123. <ul>
  124. <li class="right" style="margin-right: 10px">
  125. <a href="../genindex.html" title="General Index"
  126. accesskey="I">index</a></li>
  127. <li class="right" >
  128. <a href="../py-modindex.html" title="Python Module Index"
  129. >modules</a> |</li>
  130. <li class="right" >
  131. <a href="extending.html" title="Extending/Embedding FAQ"
  132. accesskey="N">next</a> |</li>
  133. <li class="right" >
  134. <a href="design.html" title="Design and History FAQ"
  135. accesskey="P">previous</a> |</li>
  136. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  137. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  138. <li class="switchers">
  139. <div class="language_switcher_placeholder"></div>
  140. <div class="version_switcher_placeholder"></div>
  141. </li>
  142. <li>
  143. </li>
  144. <li id="cpython-language-and-version">
  145. <a href="../index.html">3.12.0 Documentation</a> &#187;
  146. </li>
  147. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li>
  148. <li class="nav-item nav-item-this"><a href="">Library and Extension FAQ</a></li>
  149. <li class="right">
  150. <div class="inline-search" role="search">
  151. <form class="inline-search" action="../search.html" method="get">
  152. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  153. <input type="submit" value="Go" />
  154. </form>
  155. </div>
  156. |
  157. </li>
  158. <li class="right">
  159. <label class="theme-selector-label">
  160. Theme
  161. <select class="theme-selector" oninput="activateTheme(this.value)">
  162. <option value="auto" selected>Auto</option>
  163. <option value="light">Light</option>
  164. <option value="dark">Dark</option>
  165. </select>
  166. </label> |</li>
  167. </ul>
  168. </div>
  169. <div class="document">
  170. <div class="documentwrapper">
  171. <div class="bodywrapper">
  172. <div class="body" role="main">
  173. <section id="library-and-extension-faq">
  174. <h1><a class="toc-backref" href="#id1">Library and Extension FAQ</a><a class="headerlink" href="#library-and-extension-faq" title="Permalink to this headline">¶</a></h1>
  175. <div class="contents topic" id="contents">
  176. <p class="topic-title">Contents</p>
  177. <ul class="simple">
  178. <li><p><a class="reference internal" href="#library-and-extension-faq" id="id1">Library and Extension FAQ</a></p>
  179. <ul>
  180. <li><p><a class="reference internal" href="#general-library-questions" id="id2">General Library Questions</a></p>
  181. <ul>
  182. <li><p><a class="reference internal" href="#how-do-i-find-a-module-or-application-to-perform-task-x" id="id3">How do I find a module or application to perform task X?</a></p></li>
  183. <li><p><a class="reference internal" href="#where-is-the-math-py-socket-py-regex-py-etc-source-file" id="id4">Where is the math.py (socket.py, regex.py, etc.) source file?</a></p></li>
  184. <li><p><a class="reference internal" href="#how-do-i-make-a-python-script-executable-on-unix" id="id5">How do I make a Python script executable on Unix?</a></p></li>
  185. <li><p><a class="reference internal" href="#is-there-a-curses-termcap-package-for-python" id="id6">Is there a curses/termcap package for Python?</a></p></li>
  186. <li><p><a class="reference internal" href="#is-there-an-equivalent-to-c-s-onexit-in-python" id="id7">Is there an equivalent to C’s onexit() in Python?</a></p></li>
  187. <li><p><a class="reference internal" href="#why-don-t-my-signal-handlers-work" id="id8">Why don’t my signal handlers work?</a></p></li>
  188. </ul>
  189. </li>
  190. <li><p><a class="reference internal" href="#common-tasks" id="id9">Common tasks</a></p>
  191. <ul>
  192. <li><p><a class="reference internal" href="#how-do-i-test-a-python-program-or-component" id="id10">How do I test a Python program or component?</a></p></li>
  193. <li><p><a class="reference internal" href="#how-do-i-create-documentation-from-doc-strings" id="id11">How do I create documentation from doc strings?</a></p></li>
  194. <li><p><a class="reference internal" href="#how-do-i-get-a-single-keypress-at-a-time" id="id12">How do I get a single keypress at a time?</a></p></li>
  195. </ul>
  196. </li>
  197. <li><p><a class="reference internal" href="#threads" id="id13">Threads</a></p>
  198. <ul>
  199. <li><p><a class="reference internal" href="#how-do-i-program-using-threads" id="id14">How do I program using threads?</a></p></li>
  200. <li><p><a class="reference internal" href="#none-of-my-threads-seem-to-run-why" id="id15">None of my threads seem to run: why?</a></p></li>
  201. <li><p><a class="reference internal" href="#how-do-i-parcel-out-work-among-a-bunch-of-worker-threads" id="id16">How do I parcel out work among a bunch of worker threads?</a></p></li>
  202. <li><p><a class="reference internal" href="#what-kinds-of-global-value-mutation-are-thread-safe" id="id17">What kinds of global value mutation are thread-safe?</a></p></li>
  203. <li><p><a class="reference internal" href="#can-t-we-get-rid-of-the-global-interpreter-lock" id="id18">Can’t we get rid of the Global Interpreter Lock?</a></p></li>
  204. </ul>
  205. </li>
  206. <li><p><a class="reference internal" href="#input-and-output" id="id19">Input and Output</a></p>
  207. <ul>
  208. <li><p><a class="reference internal" href="#how-do-i-delete-a-file-and-other-file-questions" id="id20">How do I delete a file? (And other file questions…)</a></p></li>
  209. <li><p><a class="reference internal" href="#how-do-i-copy-a-file" id="id21">How do I copy a file?</a></p></li>
  210. <li><p><a class="reference internal" href="#how-do-i-read-or-write-binary-data" id="id22">How do I read (or write) binary data?</a></p></li>
  211. <li><p><a class="reference internal" href="#i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why" id="id23">I can’t seem to use os.read() on a pipe created with os.popen(); why?</a></p></li>
  212. <li><p><a class="reference internal" href="#how-do-i-access-the-serial-rs232-port" id="id24">How do I access the serial (RS232) port?</a></p></li>
  213. <li><p><a class="reference internal" href="#why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it" id="id25">Why doesn’t closing sys.stdout (stdin, stderr) really close it?</a></p></li>
  214. </ul>
  215. </li>
  216. <li><p><a class="reference internal" href="#network-internet-programming" id="id26">Network/Internet Programming</a></p>
  217. <ul>
  218. <li><p><a class="reference internal" href="#what-www-tools-are-there-for-python" id="id27">What WWW tools are there for Python?</a></p></li>
  219. <li><p><a class="reference internal" href="#how-can-i-mimic-cgi-form-submission-method-post" id="id28">How can I mimic CGI form submission (METHOD=POST)?</a></p></li>
  220. <li><p><a class="reference internal" href="#what-module-should-i-use-to-help-with-generating-html" id="id29">What module should I use to help with generating HTML?</a></p></li>
  221. <li><p><a class="reference internal" href="#how-do-i-send-mail-from-a-python-script" id="id30">How do I send mail from a Python script?</a></p></li>
  222. <li><p><a class="reference internal" href="#how-do-i-avoid-blocking-in-the-connect-method-of-a-socket" id="id31">How do I avoid blocking in the connect() method of a socket?</a></p></li>
  223. </ul>
  224. </li>
  225. <li><p><a class="reference internal" href="#databases" id="id32">Databases</a></p>
  226. <ul>
  227. <li><p><a class="reference internal" href="#are-there-any-interfaces-to-database-packages-in-python" id="id33">Are there any interfaces to database packages in Python?</a></p></li>
  228. <li><p><a class="reference internal" href="#how-do-you-implement-persistent-objects-in-python" id="id34">How do you implement persistent objects in Python?</a></p></li>
  229. </ul>
  230. </li>
  231. <li><p><a class="reference internal" href="#mathematics-and-numerics" id="id35">Mathematics and Numerics</a></p>
  232. <ul>
  233. <li><p><a class="reference internal" href="#how-do-i-generate-random-numbers-in-python" id="id36">How do I generate random numbers in Python?</a></p></li>
  234. </ul>
  235. </li>
  236. </ul>
  237. </li>
  238. </ul>
  239. </div>
  240. <section id="general-library-questions">
  241. <h2><a class="toc-backref" href="#id2">General Library Questions</a><a class="headerlink" href="#general-library-questions" title="Permalink to this headline">¶</a></h2>
  242. <section id="how-do-i-find-a-module-or-application-to-perform-task-x">
  243. <h3><a class="toc-backref" href="#id3">How do I find a module or application to perform task X?</a><a class="headerlink" href="#how-do-i-find-a-module-or-application-to-perform-task-x" title="Permalink to this headline">¶</a></h3>
  244. <p>Check <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">the Library Reference</span></a> to see if there’s a relevant
  245. standard library module. (Eventually you’ll learn what’s in the standard
  246. library and will be able to skip this step.)</p>
  247. <p>For third-party packages, search the <a class="reference external" href="https://pypi.org">Python Package Index</a> or try <a class="reference external" href="https://www.google.com">Google</a> or
  248. another web search engine. Searching for “Python” plus a keyword or two for
  249. your topic of interest will usually find something helpful.</p>
  250. </section>
  251. <section id="where-is-the-math-py-socket-py-regex-py-etc-source-file">
  252. <h3><a class="toc-backref" href="#id4">Where is the math.py (socket.py, regex.py, etc.) source file?</a><a class="headerlink" href="#where-is-the-math-py-socket-py-regex-py-etc-source-file" title="Permalink to this headline">¶</a></h3>
  253. <p>If you can’t find a source file for a module it may be a built-in or
  254. dynamically loaded module implemented in C, C++ or other compiled language.
  255. In this case you may not have the source file or it may be something like
  256. <code class="file docutils literal notranslate"><span class="pre">mathmodule.c</span></code>, somewhere in a C source directory (not on the Python Path).</p>
  257. <p>There are (at least) three kinds of modules in Python:</p>
  258. <ol class="arabic">
  259. <li><p>modules written in Python (.py);</p></li>
  260. <li><p>modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);</p></li>
  261. <li><p>modules written in C and linked with the interpreter; to get a list of these,
  262. type:</p>
  263. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
  264. <span class="nb">print</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">builtin_module_names</span><span class="p">)</span>
  265. </pre></div>
  266. </div>
  267. </li>
  268. </ol>
  269. </section>
  270. <section id="how-do-i-make-a-python-script-executable-on-unix">
  271. <h3><a class="toc-backref" href="#id5">How do I make a Python script executable on Unix?</a><a class="headerlink" href="#how-do-i-make-a-python-script-executable-on-unix" title="Permalink to this headline">¶</a></h3>
  272. <p>You need to do two things: the script file’s mode must be executable and the
  273. first line must begin with <code class="docutils literal notranslate"><span class="pre">#!</span></code> followed by the path of the Python
  274. interpreter.</p>
  275. <p>The first is done by executing <code class="docutils literal notranslate"><span class="pre">chmod</span> <span class="pre">+x</span> <span class="pre">scriptfile</span></code> or perhaps <code class="docutils literal notranslate"><span class="pre">chmod</span> <span class="pre">755</span>
  276. <span class="pre">scriptfile</span></code>.</p>
  277. <p>The second can be done in a number of ways. The most straightforward way is to
  278. write</p>
  279. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/local/bin/python</span>
  280. </pre></div>
  281. </div>
  282. <p>as the very first line of your file, using the pathname for where the Python
  283. interpreter is installed on your platform.</p>
  284. <p>If you would like the script to be independent of where the Python interpreter
  285. lives, you can use the <strong class="program">env</strong> program. Almost all Unix variants support
  286. the following, assuming the Python interpreter is in a directory on the user’s
  287. <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>:</p>
  288. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
  289. </pre></div>
  290. </div>
  291. <p><em>Don’t</em> do this for CGI scripts. The <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code> variable for CGI scripts is
  292. often very minimal, so you need to use the actual absolute pathname of the
  293. interpreter.</p>
  294. <p>Occasionally, a user’s environment is so full that the <strong class="program">/usr/bin/env</strong>
  295. program fails; or there’s no env program at all. In that case, you can try the
  296. following hack (due to Alex Rezinsky):</p>
  297. <div class="highlight-sh notranslate"><div class="highlight"><pre><span></span><span class="ch">#! /bin/sh</span>
  298. <span class="s2">&quot;&quot;&quot;:&quot;</span>
  299. <span class="nb">exec</span><span class="w"> </span>python<span class="w"> </span><span class="nv">$0</span><span class="w"> </span><span class="si">${</span><span class="nv">1</span><span class="p">+</span><span class="s2">&quot;</span><span class="nv">$@</span><span class="s2">&quot;</span><span class="si">}</span>
  300. <span class="s2">&quot;&quot;&quot;</span>
  301. </pre></div>
  302. </div>
  303. <p>The minor disadvantage is that this defines the script’s __doc__ string.
  304. However, you can fix that by adding</p>
  305. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="vm">__doc__</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;...Whatever...&quot;&quot;&quot;</span>
  306. </pre></div>
  307. </div>
  308. </section>
  309. <section id="is-there-a-curses-termcap-package-for-python">
  310. <h3><a class="toc-backref" href="#id6">Is there a curses/termcap package for Python?</a><a class="headerlink" href="#is-there-a-curses-termcap-package-for-python" title="Permalink to this headline">¶</a></h3>
  311. <p>For Unix variants: The standard Python source distribution comes with a curses
  312. module in the <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Modules">Modules</a> subdirectory, though it’s not compiled by default.
  313. (Note that this is not available in the Windows distribution – there is no
  314. curses module for Windows.)</p>
  315. <p>The <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> module supports basic curses features as well as many additional
  316. functions from ncurses and SYSV curses such as colour, alternative character set
  317. support, pads, and mouse support. This means the module isn’t compatible with
  318. operating systems that only have BSD curses, but there don’t seem to be any
  319. currently maintained OSes that fall into this category.</p>
  320. </section>
  321. <section id="is-there-an-equivalent-to-c-s-onexit-in-python">
  322. <h3><a class="toc-backref" href="#id7">Is there an equivalent to C’s onexit() in Python?</a><a class="headerlink" href="#is-there-an-equivalent-to-c-s-onexit-in-python" title="Permalink to this headline">¶</a></h3>
  323. <p>The <a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> module provides a register function that is similar to C’s
  324. <code class="xref c c-func docutils literal notranslate"><span class="pre">onexit()</span></code>.</p>
  325. </section>
  326. <section id="why-don-t-my-signal-handlers-work">
  327. <h3><a class="toc-backref" href="#id8">Why don’t my signal handlers work?</a><a class="headerlink" href="#why-don-t-my-signal-handlers-work" title="Permalink to this headline">¶</a></h3>
  328. <p>The most common problem is that the signal handler is declared with the wrong
  329. argument list. It is called as</p>
  330. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">handler</span><span class="p">(</span><span class="n">signum</span><span class="p">,</span> <span class="n">frame</span><span class="p">)</span>
  331. </pre></div>
  332. </div>
  333. <p>so it should be declared with two parameters:</p>
  334. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">handler</span><span class="p">(</span><span class="n">signum</span><span class="p">,</span> <span class="n">frame</span><span class="p">):</span>
  335. <span class="o">...</span>
  336. </pre></div>
  337. </div>
  338. </section>
  339. </section>
  340. <section id="common-tasks">
  341. <h2><a class="toc-backref" href="#id9">Common tasks</a><a class="headerlink" href="#common-tasks" title="Permalink to this headline">¶</a></h2>
  342. <section id="how-do-i-test-a-python-program-or-component">
  343. <h3><a class="toc-backref" href="#id10">How do I test a Python program or component?</a><a class="headerlink" href="#how-do-i-test-a-python-program-or-component" title="Permalink to this headline">¶</a></h3>
  344. <p>Python comes with two testing frameworks. The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module finds
  345. examples in the docstrings for a module and runs them, comparing the output with
  346. the expected output given in the docstring.</p>
  347. <p>The <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module is a fancier testing framework modelled on Java and
  348. Smalltalk testing frameworks.</p>
  349. <p>To make testing easier, you should use good modular design in your program.
  350. Your program should have almost all functionality
  351. encapsulated in either functions or class methods – and this sometimes has the
  352. surprising and delightful effect of making the program run faster (because local
  353. variable accesses are faster than global accesses). Furthermore the program
  354. should avoid depending on mutating global variables, since this makes testing
  355. much more difficult to do.</p>
  356. <p>The “global main logic” of your program may be as simple as</p>
  357. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
  358. <span class="n">main_logic</span><span class="p">()</span>
  359. </pre></div>
  360. </div>
  361. <p>at the bottom of the main module of your program.</p>
  362. <p>Once your program is organized as a tractable collection of function and class
  363. behaviours, you should write test functions that exercise the behaviours. A
  364. test suite that automates a sequence of tests can be associated with each module.
  365. This sounds like a lot of work, but since Python is so terse and flexible it’s
  366. surprisingly easy. You can make coding much more pleasant and fun by writing
  367. your test functions in parallel with the “production code”, since this makes it
  368. easy to find bugs and even design flaws earlier.</p>
  369. <p>“Support modules” that are not intended to be the main module of a program may
  370. include a self-test of the module.</p>
  371. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
  372. <span class="n">self_test</span><span class="p">()</span>
  373. </pre></div>
  374. </div>
  375. <p>Even programs that interact with complex external interfaces may be tested when
  376. the external interfaces are unavailable by using “fake” interfaces implemented
  377. in Python.</p>
  378. </section>
  379. <section id="how-do-i-create-documentation-from-doc-strings">
  380. <h3><a class="toc-backref" href="#id11">How do I create documentation from doc strings?</a><a class="headerlink" href="#how-do-i-create-documentation-from-doc-strings" title="Permalink to this headline">¶</a></h3>
  381. <p>The <a class="reference internal" href="../library/pydoc.html#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> module can create HTML from the doc strings in your Python
  382. source code. An alternative for creating API documentation purely from
  383. docstrings is <a class="reference external" href="https://epydoc.sourceforge.net/">epydoc</a>. <a class="reference external" href="https://www.sphinx-doc.org">Sphinx</a> can also include docstring content.</p>
  384. </section>
  385. <section id="how-do-i-get-a-single-keypress-at-a-time">
  386. <h3><a class="toc-backref" href="#id12">How do I get a single keypress at a time?</a><a class="headerlink" href="#how-do-i-get-a-single-keypress-at-a-time" title="Permalink to this headline">¶</a></h3>
  387. <p>For Unix variants there are several solutions. It’s straightforward to do this
  388. using curses, but curses is a fairly large module to learn.</p>
  389. </section>
  390. </section>
  391. <section id="threads">
  392. <h2><a class="toc-backref" href="#id13">Threads</a><a class="headerlink" href="#threads" title="Permalink to this headline">¶</a></h2>
  393. <section id="how-do-i-program-using-threads">
  394. <h3><a class="toc-backref" href="#id14">How do I program using threads?</a><a class="headerlink" href="#how-do-i-program-using-threads" title="Permalink to this headline">¶</a></h3>
  395. <p>Be sure to use the <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module and not the <a class="reference internal" href="../library/_thread.html#module-_thread" title="_thread: Low-level threading API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code></a> module.
  396. The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module builds convenient abstractions on top of the
  397. low-level primitives provided by the <a class="reference internal" href="../library/_thread.html#module-_thread" title="_thread: Low-level threading API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code></a> module.</p>
  398. </section>
  399. <section id="none-of-my-threads-seem-to-run-why">
  400. <h3><a class="toc-backref" href="#id15">None of my threads seem to run: why?</a><a class="headerlink" href="#none-of-my-threads-seem-to-run-why" title="Permalink to this headline">¶</a></h3>
  401. <p>As soon as the main thread exits, all threads are killed. Your main thread is
  402. running too quickly, giving the threads no time to do any work.</p>
  403. <p>A simple fix is to add a sleep to the end of the program that’s long enough for
  404. all the threads to finish:</p>
  405. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">time</span>
  406. <span class="k">def</span> <span class="nf">thread_task</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
  407. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
  408. <span class="nb">print</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
  409. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
  410. <span class="n">T</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">thread_task</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">),</span> <span class="n">i</span><span class="p">))</span>
  411. <span class="n">T</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
  412. <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># &lt;---------------------------!</span>
  413. </pre></div>
  414. </div>
  415. <p>But now (on many platforms) the threads don’t run in parallel, but appear to run
  416. sequentially, one at a time! The reason is that the OS thread scheduler doesn’t
  417. start a new thread until the previous thread is blocked.</p>
  418. <p>A simple fix is to add a tiny sleep to the start of the run function:</p>
  419. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">thread_task</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
  420. <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.001</span><span class="p">)</span> <span class="c1"># &lt;--------------------!</span>
  421. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
  422. <span class="nb">print</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
  423. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
  424. <span class="n">T</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">thread_task</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">),</span> <span class="n">i</span><span class="p">))</span>
  425. <span class="n">T</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
  426. <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
  427. </pre></div>
  428. </div>
  429. <p>Instead of trying to guess a good delay value for <a class="reference internal" href="../library/time.html#time.sleep" title="time.sleep"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.sleep()</span></code></a>,
  430. it’s better to use some kind of semaphore mechanism. One idea is to use the
  431. <a class="reference internal" href="../library/queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code></a> module to create a queue object, let each thread append a token to
  432. the queue when it finishes, and let the main thread read as many tokens from the
  433. queue as there are threads.</p>
  434. </section>
  435. <section id="how-do-i-parcel-out-work-among-a-bunch-of-worker-threads">
  436. <h3><a class="toc-backref" href="#id16">How do I parcel out work among a bunch of worker threads?</a><a class="headerlink" href="#how-do-i-parcel-out-work-among-a-bunch-of-worker-threads" title="Permalink to this headline">¶</a></h3>
  437. <p>The easiest way is to use the <a class="reference internal" href="../library/concurrent.futures.html#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">concurrent.futures</span></code></a> module,
  438. especially the <a class="reference internal" href="../library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ThreadPoolExecutor</span></code></a> class.</p>
  439. <p>Or, if you want fine control over the dispatching algorithm, you can write
  440. your own logic manually. Use the <a class="reference internal" href="../library/queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code></a> module to create a queue
  441. containing a list of jobs. The <a class="reference internal" href="../library/queue.html#queue.Queue" title="queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> class maintains a
  442. list of objects and has a <code class="docutils literal notranslate"><span class="pre">.put(obj)</span></code> method that adds items to the queue and
  443. a <code class="docutils literal notranslate"><span class="pre">.get()</span></code> method to return them. The class will take care of the locking
  444. necessary to ensure that each job is handed out exactly once.</p>
  445. <p>Here’s a trivial example:</p>
  446. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">queue</span><span class="o">,</span> <span class="nn">time</span>
  447. <span class="c1"># The worker thread gets jobs off the queue. When the queue is empty, it</span>
  448. <span class="c1"># assumes there will be no more work and exits.</span>
  449. <span class="c1"># (Realistically workers will run until terminated.)</span>
  450. <span class="k">def</span> <span class="nf">worker</span><span class="p">():</span>
  451. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Running worker&#39;</span><span class="p">)</span>
  452. <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>
  453. <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  454. <span class="k">try</span><span class="p">:</span>
  455. <span class="n">arg</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">block</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
  456. <span class="k">except</span> <span class="n">queue</span><span class="o">.</span><span class="n">Empty</span><span class="p">:</span>
  457. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Worker&#39;</span><span class="p">,</span> <span class="n">threading</span><span class="o">.</span><span class="n">current_thread</span><span class="p">(),</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">)</span>
  458. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;queue empty&#39;</span><span class="p">)</span>
  459. <span class="k">break</span>
  460. <span class="k">else</span><span class="p">:</span>
  461. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Worker&#39;</span><span class="p">,</span> <span class="n">threading</span><span class="o">.</span><span class="n">current_thread</span><span class="p">(),</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">)</span>
  462. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;running with argument&#39;</span><span class="p">,</span> <span class="n">arg</span><span class="p">)</span>
  463. <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.5</span><span class="p">)</span>
  464. <span class="c1"># Create queue</span>
  465. <span class="n">q</span> <span class="o">=</span> <span class="n">queue</span><span class="o">.</span><span class="n">Queue</span><span class="p">()</span>
  466. <span class="c1"># Start a pool of 5 workers</span>
  467. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
  468. <span class="n">t</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">worker</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;worker </span><span class="si">%i</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">))</span>
  469. <span class="n">t</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
  470. <span class="c1"># Begin adding work to the queue</span>
  471. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">50</span><span class="p">):</span>
  472. <span class="n">q</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
  473. <span class="c1"># Give threads time to run</span>
  474. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Main thread sleeping&#39;</span><span class="p">)</span>
  475. <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
  476. </pre></div>
  477. </div>
  478. <p>When run, this will produce the following output:</p>
  479. <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Running worker
  480. Running worker
  481. Running worker
  482. Running worker
  483. Running worker
  484. Main thread sleeping
  485. Worker &lt;Thread(worker 1, started 130283832797456)&gt; running with argument 0
  486. Worker &lt;Thread(worker 2, started 130283824404752)&gt; running with argument 1
  487. Worker &lt;Thread(worker 3, started 130283816012048)&gt; running with argument 2
  488. Worker &lt;Thread(worker 4, started 130283807619344)&gt; running with argument 3
  489. Worker &lt;Thread(worker 5, started 130283799226640)&gt; running with argument 4
  490. Worker &lt;Thread(worker 1, started 130283832797456)&gt; running with argument 5
  491. ...
  492. </pre></div>
  493. </div>
  494. <p>Consult the module’s documentation for more details; the <a class="reference internal" href="../library/queue.html#queue.Queue" title="queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a>
  495. class provides a featureful interface.</p>
  496. </section>
  497. <section id="what-kinds-of-global-value-mutation-are-thread-safe">
  498. <h3><a class="toc-backref" href="#id17">What kinds of global value mutation are thread-safe?</a><a class="headerlink" href="#what-kinds-of-global-value-mutation-are-thread-safe" title="Permalink to this headline">¶</a></h3>
  499. <p>A <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">global interpreter lock</span></a> (GIL) is used internally to ensure that only one
  500. thread runs in the Python VM at a time. In general, Python offers to switch
  501. among threads only between bytecode instructions; how frequently it switches can
  502. be set via <a class="reference internal" href="../library/sys.html#sys.setswitchinterval" title="sys.setswitchinterval"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setswitchinterval()</span></code></a>. Each bytecode instruction and
  503. therefore all the C implementation code reached from each instruction is
  504. therefore atomic from the point of view of a Python program.</p>
  505. <p>In theory, this means an exact accounting requires an exact understanding of the
  506. PVM bytecode implementation. In practice, it means that operations on shared
  507. variables of built-in data types (ints, lists, dicts, etc) that “look atomic”
  508. really are.</p>
  509. <p>For example, the following operations are all atomic (L, L1, L2 are lists, D,
  510. D1, D2 are dicts, x, y are objects, i, j are ints):</p>
  511. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  512. <span class="n">L1</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">L2</span><span class="p">)</span>
  513. <span class="n">x</span> <span class="o">=</span> <span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
  514. <span class="n">x</span> <span class="o">=</span> <span class="n">L</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
  515. <span class="n">L1</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="n">L2</span>
  516. <span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
  517. <span class="n">x</span> <span class="o">=</span> <span class="n">y</span>
  518. <span class="n">x</span><span class="o">.</span><span class="n">field</span> <span class="o">=</span> <span class="n">y</span>
  519. <span class="n">D</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">=</span> <span class="n">y</span>
  520. <span class="n">D1</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">D2</span><span class="p">)</span>
  521. <span class="n">D</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
  522. </pre></div>
  523. </div>
  524. <p>These aren’t:</p>
  525. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">i</span> <span class="o">=</span> <span class="n">i</span><span class="o">+</span><span class="mi">1</span>
  526. <span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">L</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
  527. <span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">L</span><span class="p">[</span><span class="n">j</span><span class="p">]</span>
  528. <span class="n">D</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">=</span> <span class="n">D</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>
  529. </pre></div>
  530. </div>
  531. <p>Operations that replace other objects may invoke those other objects’
  532. <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method when their reference count reaches zero, and that can
  533. affect things. This is especially true for the mass updates to dictionaries and
  534. lists. When in doubt, use a mutex!</p>
  535. </section>
  536. <section id="can-t-we-get-rid-of-the-global-interpreter-lock">
  537. <h3><a class="toc-backref" href="#id18">Can’t we get rid of the Global Interpreter Lock?</a><a class="headerlink" href="#can-t-we-get-rid-of-the-global-interpreter-lock" title="Permalink to this headline">¶</a></h3>
  538. <p>The <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">global interpreter lock</span></a> (GIL) is often seen as a hindrance to Python’s
  539. deployment on high-end multiprocessor server machines, because a multi-threaded
  540. Python program effectively only uses one CPU, due to the insistence that
  541. (almost) all Python code can only run while the GIL is held.</p>
  542. <p>Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive
  543. patch set (the “free threading” patches) that removed the GIL and replaced it
  544. with fine-grained locking. Adam Olsen recently did a similar experiment
  545. in his <a class="reference external" href="https://code.google.com/archive/p/python-safethread">python-safethread</a>
  546. project. Unfortunately, both experiments exhibited a sharp drop in single-thread
  547. performance (at least 30% slower), due to the amount of fine-grained locking
  548. necessary to compensate for the removal of the GIL.</p>
  549. <p>This doesn’t mean that you can’t make good use of Python on multi-CPU machines!
  550. You just have to be creative with dividing the work up between multiple
  551. <em>processes</em> rather than multiple <em>threads</em>. The
  552. <a class="reference internal" href="../library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor" title="concurrent.futures.ProcessPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProcessPoolExecutor</span></code></a> class in the new
  553. <a class="reference internal" href="../library/concurrent.futures.html#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">concurrent.futures</span></code></a> module provides an easy way of doing so; the
  554. <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module provides a lower-level API in case you want
  555. more control over dispatching of tasks.</p>
  556. <p>Judicious use of C extensions will also help; if you use a C extension to
  557. perform a time-consuming task, the extension can release the GIL while the
  558. thread of execution is in the C code and allow other threads to get some work
  559. done. Some standard library modules such as <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> and <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a>
  560. already do this.</p>
  561. <p>It has been suggested that the GIL should be a per-interpreter-state lock rather
  562. than truly global; interpreters then wouldn’t be able to share objects.
  563. Unfortunately, this isn’t likely to happen either. It would be a tremendous
  564. amount of work, because many object implementations currently have global state.
  565. For example, small integers and short strings are cached; these caches would
  566. have to be moved to the interpreter state. Other object types have their own
  567. free list; these free lists would have to be moved to the interpreter state.
  568. And so on.</p>
  569. <p>And I doubt that it can even be done in finite time, because the same problem
  570. exists for 3rd party extensions. It is likely that 3rd party extensions are
  571. being written at a faster rate than you can convert them to store all their
  572. global state in the interpreter state.</p>
  573. <p>And finally, once you have multiple interpreters not sharing any state, what
  574. have you gained over running each interpreter in a separate process?</p>
  575. </section>
  576. </section>
  577. <section id="input-and-output">
  578. <h2><a class="toc-backref" href="#id19">Input and Output</a><a class="headerlink" href="#input-and-output" title="Permalink to this headline">¶</a></h2>
  579. <section id="how-do-i-delete-a-file-and-other-file-questions">
  580. <h3><a class="toc-backref" href="#id20">How do I delete a file? (And other file questions…)</a><a class="headerlink" href="#how-do-i-delete-a-file-and-other-file-questions" title="Permalink to this headline">¶</a></h3>
  581. <p>Use <code class="docutils literal notranslate"><span class="pre">os.remove(filename)</span></code> or <code class="docutils literal notranslate"><span class="pre">os.unlink(filename)</span></code>; for documentation, see
  582. the <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module. The two functions are identical; <a class="reference internal" href="../library/os.html#os.unlink" title="os.unlink"><code class="xref py py-func docutils literal notranslate"><span class="pre">unlink()</span></code></a> is simply
  583. the name of the Unix system call for this function.</p>
  584. <p>To remove a directory, use <a class="reference internal" href="../library/os.html#os.rmdir" title="os.rmdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.rmdir()</span></code></a>; use <a class="reference internal" href="../library/os.html#os.mkdir" title="os.mkdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.mkdir()</span></code></a> to create one.
  585. <code class="docutils literal notranslate"><span class="pre">os.makedirs(path)</span></code> will create any intermediate directories in <code class="docutils literal notranslate"><span class="pre">path</span></code> that
  586. don’t exist. <code class="docutils literal notranslate"><span class="pre">os.removedirs(path)</span></code> will remove intermediate directories as
  587. long as they’re empty; if you want to delete an entire directory tree and its
  588. contents, use <a class="reference internal" href="../library/shutil.html#shutil.rmtree" title="shutil.rmtree"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.rmtree()</span></code></a>.</p>
  589. <p>To rename a file, use <code class="docutils literal notranslate"><span class="pre">os.rename(old_path,</span> <span class="pre">new_path)</span></code>.</p>
  590. <p>To truncate a file, open it using <code class="docutils literal notranslate"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">open(filename,</span> <span class="pre">&quot;rb+&quot;)</span></code>, and use
  591. <code class="docutils literal notranslate"><span class="pre">f.truncate(offset)</span></code>; offset defaults to the current seek position. There’s
  592. also <code class="docutils literal notranslate"><span class="pre">os.ftruncate(fd,</span> <span class="pre">offset)</span></code> for files opened with <a class="reference internal" href="../library/os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a>, where
  593. <em>fd</em> is the file descriptor (a small integer).</p>
  594. <p>The <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module also contains a number of functions to work on files
  595. including <a class="reference internal" href="../library/shutil.html#shutil.copyfile" title="shutil.copyfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">copyfile()</span></code></a>, <a class="reference internal" href="../library/shutil.html#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">copytree()</span></code></a>, and
  596. <a class="reference internal" href="../library/shutil.html#shutil.rmtree" title="shutil.rmtree"><code class="xref py py-func docutils literal notranslate"><span class="pre">rmtree()</span></code></a>.</p>
  597. </section>
  598. <section id="how-do-i-copy-a-file">
  599. <h3><a class="toc-backref" href="#id21">How do I copy a file?</a><a class="headerlink" href="#how-do-i-copy-a-file" title="Permalink to this headline">¶</a></h3>
  600. <p>The <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module contains a <a class="reference internal" href="../library/shutil.html#shutil.copyfile" title="shutil.copyfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">copyfile()</span></code></a> function.
  601. Note that on Windows NTFS volumes, it does not copy
  602. <a class="reference external" href="https://en.wikipedia.org/wiki/NTFS#Alternate_data_stream_(ADS)">alternate data streams</a>
  603. nor <a class="reference external" href="https://en.wikipedia.org/wiki/Resource_fork">resource forks</a>
  604. on macOS HFS+ volumes, though both are now rarely used.
  605. It also doesn’t copy file permissions and metadata, though using
  606. <a class="reference internal" href="../library/shutil.html#shutil.copy2" title="shutil.copy2"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.copy2()</span></code></a> instead will preserve most (though not all) of it.</p>
  607. </section>
  608. <section id="how-do-i-read-or-write-binary-data">
  609. <h3><a class="toc-backref" href="#id22">How do I read (or write) binary data?</a><a class="headerlink" href="#how-do-i-read-or-write-binary-data" title="Permalink to this headline">¶</a></h3>
  610. <p>To read or write complex binary data formats, it’s best to use the <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a>
  611. module. It allows you to take a string containing binary data (usually numbers)
  612. and convert it to Python objects; and vice versa.</p>
  613. <p>For example, the following code reads two 2-byte integers and one 4-byte integer
  614. in big-endian format from a file:</p>
  615. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">struct</span>
  616. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s2">&quot;rb&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  617. <span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span>
  618. <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="s2">&quot;&gt;hhl&quot;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
  619. </pre></div>
  620. </div>
  621. <p>The ‘&gt;’ in the format string forces big-endian data; the letter ‘h’ reads one
  622. “short integer” (2 bytes), and ‘l’ reads one “long integer” (4 bytes) from the
  623. string.</p>
  624. <p>For data that is more regular (e.g. a homogeneous list of ints or floats),
  625. you can also use the <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> module.</p>
  626. <div class="admonition note">
  627. <p class="admonition-title">Note</p>
  628. <p>To read and write binary data, it is mandatory to open the file in
  629. binary mode (here, passing <code class="docutils literal notranslate"><span class="pre">&quot;rb&quot;</span></code> to <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>). If you use
  630. <code class="docutils literal notranslate"><span class="pre">&quot;r&quot;</span></code> instead (the default), the file will be open in text mode
  631. and <code class="docutils literal notranslate"><span class="pre">f.read()</span></code> will return <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> objects rather than
  632. <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> objects.</p>
  633. </div>
  634. </section>
  635. <section id="i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why">
  636. <h3><a class="toc-backref" href="#id23">I can’t seem to use os.read() on a pipe created with os.popen(); why?</a><a class="headerlink" href="#i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why" title="Permalink to this headline">¶</a></h3>
  637. <p><a class="reference internal" href="../library/os.html#os.read" title="os.read"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.read()</span></code></a> is a low-level function which takes a file descriptor, a small
  638. integer representing the opened file. <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a> creates a high-level
  639. file object, the same type returned by the built-in <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function.
  640. Thus, to read <em>n</em> bytes from a pipe <em>p</em> created with <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a>, you need to
  641. use <code class="docutils literal notranslate"><span class="pre">p.read(n)</span></code>.</p>
  642. </section>
  643. <section id="how-do-i-access-the-serial-rs232-port">
  644. <h3><a class="toc-backref" href="#id24">How do I access the serial (RS232) port?</a><a class="headerlink" href="#how-do-i-access-the-serial-rs232-port" title="Permalink to this headline">¶</a></h3>
  645. <p>For Win32, OSX, Linux, BSD, Jython, IronPython:</p>
  646. <blockquote>
  647. <div><p><a class="reference external" href="https://pypi.org/project/pyserial/">https://pypi.org/project/pyserial/</a></p>
  648. </div></blockquote>
  649. <p>For Unix, see a Usenet post by Mitch Chapman:</p>
  650. <blockquote>
  651. <div><p><a class="reference external" href="https://groups.google.com/groups?selm=34A04430.CF9&#64;ohioee.com">https://groups.google.com/groups?selm=34A04430.CF9&#64;ohioee.com</a></p>
  652. </div></blockquote>
  653. </section>
  654. <section id="why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it">
  655. <h3><a class="toc-backref" href="#id25">Why doesn’t closing sys.stdout (stdin, stderr) really close it?</a><a class="headerlink" href="#why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it" title="Permalink to this headline">¶</a></h3>
  656. <p>Python <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file objects</span></a> are a high-level layer of
  657. abstraction on low-level C file descriptors.</p>
  658. <p>For most file objects you create in Python via the built-in <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>
  659. function, <code class="docutils literal notranslate"><span class="pre">f.close()</span></code> marks the Python file object as being closed from
  660. Python’s point of view, and also arranges to close the underlying C file
  661. descriptor. This also happens automatically in <code class="docutils literal notranslate"><span class="pre">f</span></code>’s destructor, when
  662. <code class="docutils literal notranslate"><span class="pre">f</span></code> becomes garbage.</p>
  663. <p>But stdin, stdout and stderr are treated specially by Python, because of the
  664. special status also given to them by C. Running <code class="docutils literal notranslate"><span class="pre">sys.stdout.close()</span></code> marks
  665. the Python-level file object as being closed, but does <em>not</em> close the
  666. associated C file descriptor.</p>
  667. <p>To close the underlying C file descriptor for one of these three, you should
  668. first be sure that’s what you really want to do (e.g., you may confuse
  669. extension modules trying to do I/O). If it is, use <a class="reference internal" href="../library/os.html#os.close" title="os.close"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.close()</span></code></a>:</p>
  670. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="n">stdin</span><span class="o">.</span><span class="n">fileno</span><span class="p">())</span>
  671. <span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="n">stdout</span><span class="o">.</span><span class="n">fileno</span><span class="p">())</span>
  672. <span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="n">stderr</span><span class="o">.</span><span class="n">fileno</span><span class="p">())</span>
  673. </pre></div>
  674. </div>
  675. <p>Or you can use the numeric constants 0, 1 and 2, respectively.</p>
  676. </section>
  677. </section>
  678. <section id="network-internet-programming">
  679. <h2><a class="toc-backref" href="#id26">Network/Internet Programming</a><a class="headerlink" href="#network-internet-programming" title="Permalink to this headline">¶</a></h2>
  680. <section id="what-www-tools-are-there-for-python">
  681. <h3><a class="toc-backref" href="#id27">What WWW tools are there for Python?</a><a class="headerlink" href="#what-www-tools-are-there-for-python" title="Permalink to this headline">¶</a></h3>
  682. <p>See the chapters titled <a class="reference internal" href="../library/internet.html#internet"><span class="std std-ref">Internet Protocols and Support</span></a> and <a class="reference internal" href="../library/netdata.html#netdata"><span class="std std-ref">Internet Data Handling</span></a> in the Library
  683. Reference Manual. Python has many modules that will help you build server-side
  684. and client-side web systems.</p>
  685. <p>A summary of available frameworks is maintained by Paul Boddie at
  686. <a class="reference external" href="https://wiki.python.org/moin/WebProgramming">https://wiki.python.org/moin/WebProgramming</a>.</p>
  687. <p>Cameron Laird maintains a useful set of pages about Python web technologies at
  688. <a class="reference external" href="https://web.archive.org/web/20210224183619/http://phaseit.net/claird/comp.lang.python/web_python">https://web.archive.org/web/20210224183619/http://phaseit.net/claird/comp.lang.python/web_python</a>.</p>
  689. </section>
  690. <section id="how-can-i-mimic-cgi-form-submission-method-post">
  691. <h3><a class="toc-backref" href="#id28">How can I mimic CGI form submission (METHOD=POST)?</a><a class="headerlink" href="#how-can-i-mimic-cgi-form-submission-method-post" title="Permalink to this headline">¶</a></h3>
  692. <p>I would like to retrieve web pages that are the result of POSTing a form. Is
  693. there existing code that would let me do this easily?</p>
  694. <p>Yes. Here’s a simple example that uses <a class="reference internal" href="../library/urllib.request.html#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.request</span></code></a>:</p>
  695. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/local/bin/python</span>
  696. <span class="kn">import</span> <span class="nn">urllib.request</span>
  697. <span class="c1"># build the query string</span>
  698. <span class="n">qs</span> <span class="o">=</span> <span class="s2">&quot;First=Josephine&amp;MI=Q&amp;Last=Public&quot;</span>
  699. <span class="c1"># connect and send the server a path</span>
  700. <span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://www.some-server.out-there&#39;</span>
  701. <span class="s1">&#39;/cgi-bin/some-cgi-script&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">qs</span><span class="p">)</span>
  702. <span class="k">with</span> <span class="n">req</span><span class="p">:</span>
  703. <span class="n">msg</span><span class="p">,</span> <span class="n">hdrs</span> <span class="o">=</span> <span class="n">req</span><span class="o">.</span><span class="n">read</span><span class="p">(),</span> <span class="n">req</span><span class="o">.</span><span class="n">info</span><span class="p">()</span>
  704. </pre></div>
  705. </div>
  706. <p>Note that in general for percent-encoded POST operations, query strings must be
  707. quoted using <a class="reference internal" href="../library/urllib.parse.html#urllib.parse.urlencode" title="urllib.parse.urlencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.parse.urlencode()</span></code></a>. For example, to send
  708. <code class="docutils literal notranslate"><span class="pre">name=Guy</span> <span class="pre">Steele,</span> <span class="pre">Jr.</span></code>:</p>
  709. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib.parse</span>
  710. <span class="gp">&gt;&gt;&gt; </span><span class="n">urllib</span><span class="o">.</span><span class="n">parse</span><span class="o">.</span><span class="n">urlencode</span><span class="p">({</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;Guy Steele, Jr.&#39;</span><span class="p">})</span>
  711. <span class="go">&#39;name=Guy+Steele%2C+Jr.&#39;</span>
  712. </pre></div>
  713. </div>
  714. <div class="admonition seealso">
  715. <p class="admonition-title">See also</p>
  716. <p><a class="reference internal" href="../howto/urllib2.html#urllib-howto"><span class="std std-ref">HOWTO Fetch Internet Resources Using The urllib Package</span></a> for extensive examples.</p>
  717. </div>
  718. </section>
  719. <section id="what-module-should-i-use-to-help-with-generating-html">
  720. <h3><a class="toc-backref" href="#id29">What module should I use to help with generating HTML?</a><a class="headerlink" href="#what-module-should-i-use-to-help-with-generating-html" title="Permalink to this headline">¶</a></h3>
  721. <p>You can find a collection of useful links on the <a class="reference external" href="https://wiki.python.org/moin/WebProgramming">Web Programming wiki page</a>.</p>
  722. </section>
  723. <section id="how-do-i-send-mail-from-a-python-script">
  724. <h3><a class="toc-backref" href="#id30">How do I send mail from a Python script?</a><a class="headerlink" href="#how-do-i-send-mail-from-a-python-script" title="Permalink to this headline">¶</a></h3>
  725. <p>Use the standard library module <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a>.</p>
  726. <p>Here’s a very simple interactive mail sender that uses it. This method will
  727. work on any host that supports an SMTP listener.</p>
  728. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">smtplib</span>
  729. <span class="n">fromaddr</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s2">&quot;From: &quot;</span><span class="p">)</span>
  730. <span class="n">toaddrs</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s2">&quot;To: &quot;</span><span class="p">)</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;,&#39;</span><span class="p">)</span>
  731. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Enter message, end with ^D:&quot;</span><span class="p">)</span>
  732. <span class="n">msg</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
  733. <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  734. <span class="n">line</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
  735. <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="p">:</span>
  736. <span class="k">break</span>
  737. <span class="n">msg</span> <span class="o">+=</span> <span class="n">line</span>
  738. <span class="c1"># The actual mail send</span>
  739. <span class="n">server</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">)</span>
  740. <span class="n">server</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">fromaddr</span><span class="p">,</span> <span class="n">toaddrs</span><span class="p">,</span> <span class="n">msg</span><span class="p">)</span>
  741. <span class="n">server</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
  742. </pre></div>
  743. </div>
  744. <p>A Unix-only alternative uses sendmail. The location of the sendmail program
  745. varies between systems; sometimes it is <code class="docutils literal notranslate"><span class="pre">/usr/lib/sendmail</span></code>, sometimes
  746. <code class="docutils literal notranslate"><span class="pre">/usr/sbin/sendmail</span></code>. The sendmail manual page will help you out. Here’s
  747. some sample code:</p>
  748. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
  749. <span class="n">SENDMAIL</span> <span class="o">=</span> <span class="s2">&quot;/usr/sbin/sendmail&quot;</span> <span class="c1"># sendmail location</span>
  750. <span class="n">p</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">popen</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%s</span><span class="s2"> -t -i&quot;</span> <span class="o">%</span> <span class="n">SENDMAIL</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">)</span>
  751. <span class="n">p</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;To: receiver@example.com</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
  752. <span class="n">p</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;Subject: test</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
  753. <span class="n">p</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span> <span class="c1"># blank line separating headers from body</span>
  754. <span class="n">p</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;Some text</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
  755. <span class="n">p</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;some more text</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
  756. <span class="n">sts</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
  757. <span class="k">if</span> <span class="n">sts</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
  758. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Sendmail exit status&quot;</span><span class="p">,</span> <span class="n">sts</span><span class="p">)</span>
  759. </pre></div>
  760. </div>
  761. </section>
  762. <section id="how-do-i-avoid-blocking-in-the-connect-method-of-a-socket">
  763. <h3><a class="toc-backref" href="#id31">How do I avoid blocking in the connect() method of a socket?</a><a class="headerlink" href="#how-do-i-avoid-blocking-in-the-connect-method-of-a-socket" title="Permalink to this headline">¶</a></h3>
  764. <p>The <a class="reference internal" href="../library/select.html#module-select" title="select: Wait for I/O completion on multiple streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">select</span></code></a> module is commonly used to help with asynchronous I/O on
  765. sockets.</p>
  766. <p>To prevent the TCP connect from blocking, you can set the socket to non-blocking
  767. mode. Then when you do the <a class="reference internal" href="../library/socket.html#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a>,
  768. you will either connect immediately
  769. (unlikely) or get an exception that contains the error number as <code class="docutils literal notranslate"><span class="pre">.errno</span></code>.
  770. <code class="docutils literal notranslate"><span class="pre">errno.EINPROGRESS</span></code> indicates that the connection is in progress, but hasn’t
  771. finished yet. Different OSes will return different values, so you’re going to
  772. have to check what’s returned on your system.</p>
  773. <p>You can use the <a class="reference internal" href="../library/socket.html#socket.socket.connect_ex" title="socket.socket.connect_ex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect_ex()</span></code></a> method
  774. to avoid creating an exception.
  775. It will just return the errno value.
  776. To poll, you can call <a class="reference internal" href="../library/socket.html#socket.socket.connect_ex" title="socket.socket.connect_ex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect_ex()</span></code></a> again later
  777. – <code class="docutils literal notranslate"><span class="pre">0</span></code> or <code class="docutils literal notranslate"><span class="pre">errno.EISCONN</span></code> indicate that you’re connected – or you can pass this
  778. socket to <a class="reference internal" href="../library/select.html#select.select" title="select.select"><code class="xref py py-meth docutils literal notranslate"><span class="pre">select.select()</span></code></a> to check if it’s writable.</p>
  779. <div class="admonition note">
  780. <p class="admonition-title">Note</p>
  781. <p>The <a class="reference internal" href="../library/asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> module provides a general purpose single-threaded and
  782. concurrent asynchronous library, which can be used for writing non-blocking
  783. network code.
  784. The third-party <a class="reference external" href="https://twisted.org/">Twisted</a> library is
  785. a popular and feature-rich alternative.</p>
  786. </div>
  787. </section>
  788. </section>
  789. <section id="databases">
  790. <h2><a class="toc-backref" href="#id32">Databases</a><a class="headerlink" href="#databases" title="Permalink to this headline">¶</a></h2>
  791. <section id="are-there-any-interfaces-to-database-packages-in-python">
  792. <h3><a class="toc-backref" href="#id33">Are there any interfaces to database packages in Python?</a><a class="headerlink" href="#are-there-any-interfaces-to-database-packages-in-python" title="Permalink to this headline">¶</a></h3>
  793. <p>Yes.</p>
  794. <p>Interfaces to disk-based hashes such as <a class="reference internal" href="../library/dbm.html#module-dbm.ndbm" title="dbm.ndbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">DBM</span></code></a> and <a class="reference internal" href="../library/dbm.html#module-dbm.gnu" title="dbm.gnu: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">GDBM</span></code></a> are also included with standard Python. There is also the
  795. <a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module, which provides a lightweight disk-based relational
  796. database.</p>
  797. <p>Support for most relational databases is available. See the
  798. <a class="reference external" href="https://wiki.python.org/moin/DatabaseProgramming">DatabaseProgramming wiki page</a> for details.</p>
  799. </section>
  800. <section id="how-do-you-implement-persistent-objects-in-python">
  801. <h3><a class="toc-backref" href="#id34">How do you implement persistent objects in Python?</a><a class="headerlink" href="#how-do-you-implement-persistent-objects-in-python" title="Permalink to this headline">¶</a></h3>
  802. <p>The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> library module solves this in a very general way (though you
  803. still can’t store things like open files, sockets or windows), and the
  804. <a class="reference internal" href="../library/shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a> library module uses pickle and (g)dbm to create persistent
  805. mappings containing arbitrary Python objects.</p>
  806. </section>
  807. </section>
  808. <section id="mathematics-and-numerics">
  809. <h2><a class="toc-backref" href="#id35">Mathematics and Numerics</a><a class="headerlink" href="#mathematics-and-numerics" title="Permalink to this headline">¶</a></h2>
  810. <section id="how-do-i-generate-random-numbers-in-python">
  811. <h3><a class="toc-backref" href="#id36">How do I generate random numbers in Python?</a><a class="headerlink" href="#how-do-i-generate-random-numbers-in-python" title="Permalink to this headline">¶</a></h3>
  812. <p>The standard module <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> implements a random number generator. Usage
  813. is simple:</p>
  814. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
  815. <span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span>
  816. </pre></div>
  817. </div>
  818. <p>This returns a random floating point number in the range [0, 1).</p>
  819. <p>There are also many other specialized generators in this module, such as:</p>
  820. <ul class="simple">
  821. <li><p><code class="docutils literal notranslate"><span class="pre">randrange(a,</span> <span class="pre">b)</span></code> chooses an integer in the range [a, b).</p></li>
  822. <li><p><code class="docutils literal notranslate"><span class="pre">uniform(a,</span> <span class="pre">b)</span></code> chooses a floating point number in the range [a, b).</p></li>
  823. <li><p><code class="docutils literal notranslate"><span class="pre">normalvariate(mean,</span> <span class="pre">sdev)</span></code> samples the normal (Gaussian) distribution.</p></li>
  824. </ul>
  825. <p>Some higher-level functions operate on sequences directly, such as:</p>
  826. <ul class="simple">
  827. <li><p><code class="docutils literal notranslate"><span class="pre">choice(S)</span></code> chooses a random element from a given sequence.</p></li>
  828. <li><p><code class="docutils literal notranslate"><span class="pre">shuffle(L)</span></code> shuffles a list in-place, i.e. permutes it randomly.</p></li>
  829. </ul>
  830. <p>There’s also a <code class="docutils literal notranslate"><span class="pre">Random</span></code> class you can instantiate to create independent
  831. multiple random number generators.</p>
  832. </section>
  833. </section>
  834. </section>
  835. <div class="clearer"></div>
  836. </div>
  837. </div>
  838. </div>
  839. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  840. <div class="sphinxsidebarwrapper">
  841. <div>
  842. <h3><a href="../contents.html">Table of Contents</a></h3>
  843. <ul>
  844. <li><a class="reference internal" href="#">Library and Extension FAQ</a><ul>
  845. <li><a class="reference internal" href="#general-library-questions">General Library Questions</a></li>
  846. <li><a class="reference internal" href="#common-tasks">Common tasks</a></li>
  847. <li><a class="reference internal" href="#threads">Threads</a></li>
  848. <li><a class="reference internal" href="#input-and-output">Input and Output</a></li>
  849. <li><a class="reference internal" href="#network-internet-programming">Network/Internet Programming</a></li>
  850. <li><a class="reference internal" href="#databases">Databases</a></li>
  851. <li><a class="reference internal" href="#mathematics-and-numerics">Mathematics and Numerics</a></li>
  852. </ul>
  853. </li>
  854. </ul>
  855. </div>
  856. <div>
  857. <h4>Previous topic</h4>
  858. <p class="topless"><a href="design.html"
  859. title="previous chapter">Design and History FAQ</a></p>
  860. </div>
  861. <div>
  862. <h4>Next topic</h4>
  863. <p class="topless"><a href="extending.html"
  864. title="next chapter">Extending/Embedding FAQ</a></p>
  865. </div>
  866. <div role="note" aria-label="source link">
  867. <h3>This Page</h3>
  868. <ul class="this-page-menu">
  869. <li><a href="../bugs.html">Report a Bug</a></li>
  870. <li>
  871. <a href="https://github.com/python/cpython/blob/main/Doc/faq/library.rst"
  872. rel="nofollow">Show Source
  873. </a>
  874. </li>
  875. </ul>
  876. </div>
  877. </div>
  878. </div>
  879. <div class="clearer"></div>
  880. </div>
  881. <div class="related" role="navigation" aria-label="related navigation">
  882. <h3>Navigation</h3>
  883. <ul>
  884. <li class="right" style="margin-right: 10px">
  885. <a href="../genindex.html" title="General Index"
  886. >index</a></li>
  887. <li class="right" >
  888. <a href="../py-modindex.html" title="Python Module Index"
  889. >modules</a> |</li>
  890. <li class="right" >
  891. <a href="extending.html" title="Extending/Embedding FAQ"
  892. >next</a> |</li>
  893. <li class="right" >
  894. <a href="design.html" title="Design and History FAQ"
  895. >previous</a> |</li>
  896. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  897. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  898. <li class="switchers">
  899. <div class="language_switcher_placeholder"></div>
  900. <div class="version_switcher_placeholder"></div>
  901. </li>
  902. <li>
  903. </li>
  904. <li id="cpython-language-and-version">
  905. <a href="../index.html">3.12.0 Documentation</a> &#187;
  906. </li>
  907. <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li>
  908. <li class="nav-item nav-item-this"><a href="">Library and Extension FAQ</a></li>
  909. <li class="right">
  910. <div class="inline-search" role="search">
  911. <form class="inline-search" action="../search.html" method="get">
  912. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  913. <input type="submit" value="Go" />
  914. </form>
  915. </div>
  916. |
  917. </li>
  918. <li class="right">
  919. <label class="theme-selector-label">
  920. Theme
  921. <select class="theme-selector" oninput="activateTheme(this.value)">
  922. <option value="auto" selected>Auto</option>
  923. <option value="light">Light</option>
  924. <option value="dark">Dark</option>
  925. </select>
  926. </label> |</li>
  927. </ul>
  928. </div>
  929. <div class="footer">
  930. &copy; <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
  931. <br />
  932. This page is licensed under the Python Software Foundation License Version 2.
  933. <br />
  934. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  935. <br />
  936. See <a href="/license.html">History and License</a> for more information.<br />
  937. <br />
  938. The Python Software Foundation is a non-profit corporation.
  939. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  940. <br />
  941. <br />
  942. Last updated on Oct 02, 2023.
  943. <a href="/bugs.html">Found a bug</a>?
  944. <br />
  945. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
  946. </div>
  947. </body>
  948. </html>