home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / doc / python / faq / library.html < prev    next >
Encoding:
Extensible Markup Language  |  2009-04-19  |  57.8 KB  |  1,140 lines

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <meta name="generator" content="Docutils 0.5: http://docutils.sourceforge.net/" />
  7. <title>Python Library and Extension FAQ</title>
  8. <meta name="date" content="2005-12-16" />
  9. <style type="text/css">
  10.  
  11. /*
  12. :Author: David Goodger (goodger@python.org)
  13. :Id: $Id: html4css1.css 5196 2007-06-03 20:25:28Z wiemann $
  14. :Copyright: This stylesheet has been placed in the public domain.
  15.  
  16. Default cascading style sheet for the HTML output of Docutils.
  17.  
  18. See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
  19. customize this style sheet.
  20. */
  21.  
  22. /* used to remove borders from tables and images */
  23. .borderless, table.borderless td, table.borderless th {
  24.   border: 0 }
  25.  
  26. table.borderless td, table.borderless th {
  27.   /* Override padding for "table.docutils td" with "! important".
  28.      The right padding separates the table cells. */
  29.   padding: 0 0.5em 0 0 ! important }
  30.  
  31. .first {
  32.   /* Override more specific margin styles with "! important". */
  33.   margin-top: 0 ! important }
  34.  
  35. .last, .with-subtitle {
  36.   margin-bottom: 0 ! important }
  37.  
  38. .hidden {
  39.   display: none }
  40.  
  41. a.toc-backref {
  42.   text-decoration: none ;
  43.   color: black }
  44.  
  45. blockquote.epigraph {
  46.   margin: 2em 5em ; }
  47.  
  48. dl.docutils dd {
  49.   margin-bottom: 0.5em }
  50.  
  51. /* Uncomment (and remove this text!) to get bold-faced definition list terms
  52. dl.docutils dt {
  53.   font-weight: bold }
  54. */
  55.  
  56. div.abstract {
  57.   margin: 2em 5em }
  58.  
  59. div.abstract p.topic-title {
  60.   font-weight: bold ;
  61.   text-align: center }
  62.  
  63. div.admonition, div.attention, div.caution, div.danger, div.error,
  64. div.hint, div.important, div.note, div.tip, div.warning {
  65.   margin: 2em ;
  66.   border: medium outset ;
  67.   padding: 1em }
  68.  
  69. div.admonition p.admonition-title, div.hint p.admonition-title,
  70. div.important p.admonition-title, div.note p.admonition-title,
  71. div.tip p.admonition-title {
  72.   font-weight: bold ;
  73.   font-family: sans-serif }
  74.  
  75. div.attention p.admonition-title, div.caution p.admonition-title,
  76. div.danger p.admonition-title, div.error p.admonition-title,
  77. div.warning p.admonition-title {
  78.   color: red ;
  79.   font-weight: bold ;
  80.   font-family: sans-serif }
  81.  
  82. /* Uncomment (and remove this text!) to get reduced vertical space in
  83.    compound paragraphs.
  84. div.compound .compound-first, div.compound .compound-middle {
  85.   margin-bottom: 0.5em }
  86.  
  87. div.compound .compound-last, div.compound .compound-middle {
  88.   margin-top: 0.5em }
  89. */
  90.  
  91. div.dedication {
  92.   margin: 2em 5em ;
  93.   text-align: center ;
  94.   font-style: italic }
  95.  
  96. div.dedication p.topic-title {
  97.   font-weight: bold ;
  98.   font-style: normal }
  99.  
  100. div.figure {
  101.   margin-left: 2em ;
  102.   margin-right: 2em }
  103.  
  104. div.footer, div.header {
  105.   clear: both;
  106.   font-size: smaller }
  107.  
  108. div.line-block {
  109.   display: block ;
  110.   margin-top: 1em ;
  111.   margin-bottom: 1em }
  112.  
  113. div.line-block div.line-block {
  114.   margin-top: 0 ;
  115.   margin-bottom: 0 ;
  116.   margin-left: 1.5em }
  117.  
  118. div.sidebar {
  119.   margin: 0 0 0.5em 1em ;
  120.   border: medium outset ;
  121.   padding: 1em ;
  122.   background-color: #ffffee ;
  123.   width: 40% ;
  124.   float: right ;
  125.   clear: right }
  126.  
  127. div.sidebar p.rubric {
  128.   font-family: sans-serif ;
  129.   font-size: medium }
  130.  
  131. div.system-messages {
  132.   margin: 5em }
  133.  
  134. div.system-messages h1 {
  135.   color: red }
  136.  
  137. div.system-message {
  138.   border: medium outset ;
  139.   padding: 1em }
  140.  
  141. div.system-message p.system-message-title {
  142.   color: red ;
  143.   font-weight: bold }
  144.  
  145. div.topic {
  146.   margin: 2em }
  147.  
  148. h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
  149. h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
  150.   margin-top: 0.4em }
  151.  
  152. h1.title {
  153.   text-align: center }
  154.  
  155. h2.subtitle {
  156.   text-align: center }
  157.  
  158. hr.docutils {
  159.   width: 75% }
  160.  
  161. img.align-left {
  162.   clear: left }
  163.  
  164. img.align-right {
  165.   clear: right }
  166.  
  167. ol.simple, ul.simple {
  168.   margin-bottom: 1em }
  169.  
  170. ol.arabic {
  171.   list-style: decimal }
  172.  
  173. ol.loweralpha {
  174.   list-style: lower-alpha }
  175.  
  176. ol.upperalpha {
  177.   list-style: upper-alpha }
  178.  
  179. ol.lowerroman {
  180.   list-style: lower-roman }
  181.  
  182. ol.upperroman {
  183.   list-style: upper-roman }
  184.  
  185. p.attribution {
  186.   text-align: right ;
  187.   margin-left: 50% }
  188.  
  189. p.caption {
  190.   font-style: italic }
  191.  
  192. p.credits {
  193.   font-style: italic ;
  194.   font-size: smaller }
  195.  
  196. p.label {
  197.   white-space: nowrap }
  198.  
  199. p.rubric {
  200.   font-weight: bold ;
  201.   font-size: larger ;
  202.   color: maroon ;
  203.   text-align: center }
  204.  
  205. p.sidebar-title {
  206.   font-family: sans-serif ;
  207.   font-weight: bold ;
  208.   font-size: larger }
  209.  
  210. p.sidebar-subtitle {
  211.   font-family: sans-serif ;
  212.   font-weight: bold }
  213.  
  214. p.topic-title {
  215.   font-weight: bold }
  216.  
  217. pre.address {
  218.   margin-bottom: 0 ;
  219.   margin-top: 0 ;
  220.   font-family: serif ;
  221.   font-size: 100% }
  222.  
  223. pre.literal-block, pre.doctest-block {
  224.   margin-left: 2em ;
  225.   margin-right: 2em }
  226.  
  227. span.classifier {
  228.   font-family: sans-serif ;
  229.   font-style: oblique }
  230.  
  231. span.classifier-delimiter {
  232.   font-family: sans-serif ;
  233.   font-weight: bold }
  234.  
  235. span.interpreted {
  236.   font-family: sans-serif }
  237.  
  238. span.option {
  239.   white-space: nowrap }
  240.  
  241. span.pre {
  242.   white-space: pre }
  243.  
  244. span.problematic {
  245.   color: red }
  246.  
  247. span.section-subtitle {
  248.   /* font-size relative to parent (h1..h6 element) */
  249.   font-size: 80% }
  250.  
  251. table.citation {
  252.   border-left: solid 1px gray;
  253.   margin-left: 1px }
  254.  
  255. table.docinfo {
  256.   margin: 2em 4em }
  257.  
  258. table.docutils {
  259.   margin-top: 0.5em ;
  260.   margin-bottom: 0.5em }
  261.  
  262. table.footnote {
  263.   border-left: solid 1px black;
  264.   margin-left: 1px }
  265.  
  266. table.docutils td, table.docutils th,
  267. table.docinfo td, table.docinfo th {
  268.   padding-left: 0.5em ;
  269.   padding-right: 0.5em ;
  270.   vertical-align: top }
  271.  
  272. table.docutils th.field-name, table.docinfo th.docinfo-name {
  273.   font-weight: bold ;
  274.   text-align: left ;
  275.   white-space: nowrap ;
  276.   padding-left: 0 }
  277.  
  278. h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
  279. h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
  280.   font-size: 100% }
  281.  
  282. ul.auto-toc {
  283.   list-style-type: none }
  284.  
  285. </style>
  286. </head>
  287. <body>
  288. <div class="document" id="python-library-and-extension-faq">
  289. <h1 class="title">Python Library and Extension FAQ</h1>
  290. <table class="docinfo" frame="void" rules="none">
  291. <col class="docinfo-name" />
  292. <col class="docinfo-content" />
  293. <tbody valign="top">
  294. <tr><th class="docinfo-name">Date:</th>
  295. <td>2005-12-16</td></tr>
  296. <tr><th class="docinfo-name">Version:</th>
  297. <td>8684</td></tr>
  298. <tr class="field"><th class="docinfo-name">Web site:</th><td class="field-body"><a class="reference external" href="http://www.python.org/">http://www.python.org/</a></td>
  299. </tr>
  300. </tbody>
  301. </table>
  302. <div class="contents topic" id="contents">
  303. <p class="topic-title first">Contents</p>
  304. <ul class="auto-toc simple">
  305. <li><a class="reference internal" href="#general-library-questions" id="id3">1   General Library Questions</a><ul class="auto-toc">
  306. <li><a class="reference internal" href="#how-do-i-find-a-module-or-application-to-perform-task-x" id="id4">1.1   How do I find a module or application to perform task X?</a></li>
  307. <li><a class="reference internal" href="#where-is-the-math-py-socket-py-regex-py-etc-source-file" id="id5">1.2   Where is the math.py (socket.py, regex.py, etc.) source file?</a></li>
  308. <li><a class="reference internal" href="#how-do-i-make-a-python-script-executable-on-unix" id="id6">1.3   How do I make a Python script executable on Unix?</a></li>
  309. <li><a class="reference internal" href="#is-there-a-curses-termcap-package-for-python" id="id7">1.4   Is there a curses/termcap package for Python?</a></li>
  310. <li><a class="reference internal" href="#is-there-an-equivalent-to-c-s-onexit-in-python" id="id8">1.5   Is there an equivalent to C's onexit() in Python?</a></li>
  311. <li><a class="reference internal" href="#why-don-t-my-signal-handlers-work" id="id9">1.6   Why don't my signal handlers work?</a></li>
  312. </ul>
  313. </li>
  314. <li><a class="reference internal" href="#common-tasks" id="id10">2   Common tasks</a><ul class="auto-toc">
  315. <li><a class="reference internal" href="#how-do-i-test-a-python-program-or-component" id="id11">2.1   How do I test a Python program or component?</a></li>
  316. <li><a class="reference internal" href="#how-do-i-create-documentation-from-doc-strings" id="id12">2.2   How do I create documentation from doc strings?</a></li>
  317. <li><a class="reference internal" href="#how-do-i-get-a-single-keypress-at-a-time" id="id13">2.3   How do I get a single keypress at a time?</a></li>
  318. </ul>
  319. </li>
  320. <li><a class="reference internal" href="#threads" id="id14">3   Threads</a><ul class="auto-toc">
  321. <li><a class="reference internal" href="#how-do-i-program-using-threads" id="id15">3.1   How do I program using threads?</a></li>
  322. <li><a class="reference internal" href="#none-of-my-threads-seem-to-run-why" id="id16">3.2   None of my threads seem to run: why?</a></li>
  323. <li><a class="reference internal" href="#how-do-i-parcel-out-work-among-a-bunch-of-worker-threads" id="id17">3.3   How do I parcel out work among a bunch of worker threads?</a></li>
  324. <li><a class="reference internal" href="#what-kinds-of-global-value-mutation-are-thread-safe" id="id18">3.4   What kinds of global value mutation are thread-safe?</a></li>
  325. <li><a class="reference internal" href="#can-t-we-get-rid-of-the-global-interpreter-lock" id="id19">3.5   Can't we get rid of the Global Interpreter Lock?</a></li>
  326. </ul>
  327. </li>
  328. <li><a class="reference internal" href="#input-and-output" id="id20">4   Input and Output</a><ul class="auto-toc">
  329. <li><a class="reference internal" href="#how-do-i-delete-a-file-and-other-file-questions" id="id21">4.1   How do I delete a file? (And other file questions...)</a></li>
  330. <li><a class="reference internal" href="#how-do-i-copy-a-file" id="id22">4.2   How do I copy a file?</a></li>
  331. <li><a class="reference internal" href="#how-do-i-read-or-write-binary-data" id="id23">4.3   How do I read (or write) binary data?</a></li>
  332. <li><a class="reference internal" href="#i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why" id="id24">4.4   I can't seem to use os.read() on a pipe created with os.popen(); why?</a></li>
  333. <li><a class="reference internal" href="#how-do-i-run-a-subprocess-with-pipes-connected-to-both-input-and-output" id="id25">4.5   How do I run a subprocess with pipes connected to both input and output?</a></li>
  334. <li><a class="reference internal" href="#how-do-i-access-the-serial-rs232-port" id="id26">4.6   How do I access the serial (RS232) port?</a></li>
  335. <li><a class="reference internal" href="#why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it" id="id27">4.7   Why doesn't closing sys.stdout (stdin, stderr) really close it?</a></li>
  336. </ul>
  337. </li>
  338. <li><a class="reference internal" href="#network-internet-programming" id="id28">5   Network/Internet Programming</a><ul class="auto-toc">
  339. <li><a class="reference internal" href="#what-www-tools-are-there-for-python" id="id29">5.1   What WWW tools are there for Python?</a></li>
  340. <li><a class="reference internal" href="#how-can-i-mimic-cgi-form-submission-method-post" id="id30">5.2   How can I mimic CGI form submission (METHOD=POST)?</a></li>
  341. <li><a class="reference internal" href="#what-module-should-i-use-to-help-with-generating-html" id="id31">5.3   What module should I use to help with generating HTML?</a></li>
  342. <li><a class="reference internal" href="#how-do-i-send-mail-from-a-python-script" id="id32">5.4   How do I send mail from a Python script?</a></li>
  343. <li><a class="reference internal" href="#how-do-i-avoid-blocking-in-the-connect-method-of-a-socket" id="id33">5.5   How do I avoid blocking in the connect() method of a socket?</a></li>
  344. </ul>
  345. </li>
  346. <li><a class="reference internal" href="#databases" id="id34">6   Databases</a><ul class="auto-toc">
  347. <li><a class="reference internal" href="#are-there-any-interfaces-to-database-packages-in-python" id="id35">6.1   Are there any interfaces to database packages in Python?</a></li>
  348. <li><a class="reference internal" href="#how-do-you-implement-persistent-objects-in-python" id="id36">6.2   How do you implement persistent objects in Python?</a></li>
  349. <li><a class="reference internal" href="#why-is-cpickle-so-slow" id="id37">6.3   Why is cPickle so slow?</a></li>
  350. <li><a class="reference internal" href="#if-my-program-crashes-with-a-bsddb-or-anydbm-database-open-it-gets-corrupted-how-come" id="id38">6.4   If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?</a></li>
  351. <li><a class="reference internal" href="#i-tried-to-open-berkeley-db-file-but-bsddb-produces-bsddb-error-22-invalid-argument-help-how-can-i-restore-my-data" id="id39">6.5   I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data?</a></li>
  352. </ul>
  353. </li>
  354. <li><a class="reference internal" href="#mathematics-and-numerics" id="id40">7   Mathematics and Numerics</a><ul class="auto-toc">
  355. <li><a class="reference internal" href="#how-do-i-generate-random-numbers-in-python" id="id41">7.1   How do I generate random numbers in Python?</a></li>
  356. </ul>
  357. </li>
  358. </ul>
  359. </div>
  360. <div class="section" id="general-library-questions">
  361. <h1><a class="toc-backref" href="#id3">1   General Library Questions</a></h1>
  362. <div class="section" id="how-do-i-find-a-module-or-application-to-perform-task-x">
  363. <h2><a class="toc-backref" href="#id4">1.1   How do I find a module or application to perform task X?</a></h2>
  364. <p>Check <a class="reference external" href="http://www.python.org/doc/lib/">the Library Reference</a> to see
  365. if there's a relevant standard library module.  (Eventually you'll
  366. learn what's in the standard library and will able to skip this step.)</p>
  367. <p>Search the <a class="reference external" href="http://cheeseshop.python.org/pypi">Python Package Index</a>.</p>
  368. <p>Next, check the <a class="reference external" href="http://www.vex.net/parnassus/">Vaults of Parnassus</a>,
  369. an older index of packages.</p>
  370. <p>Finally, try <a class="reference external" href="http://www.google.com">Google</a> or other Web search
  371. engine.  Searching for "Python" plus a keyword or two for your topic
  372. of interest will usually find something helpful.</p>
  373. </div>
  374. <div class="section" id="where-is-the-math-py-socket-py-regex-py-etc-source-file">
  375. <h2><a class="toc-backref" href="#id5">1.2   Where is the math.py (socket.py, regex.py, etc.) source file?</a></h2>
  376. <p>If you can't find a source file for a module it may be a builtin
  377. or dynamically loaded module implemented in C, C++ or other
  378. compiled language.  In this case you may not have the source
  379. file or it may be something like mathmodule.c, somewhere in
  380. a C source directory (not on the Python Path).</p>
  381. <p>There are (at least) three kinds of modules in Python:</p>
  382. <ol class="arabic">
  383. <li><p class="first">modules written in Python (.py);</p>
  384. </li>
  385. <li><p class="first">modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);</p>
  386. </li>
  387. <li><p class="first">modules written in C and linked with the interpreter; to get a list
  388. of these, type:</p>
  389. <pre class="literal-block">
  390. import sys
  391. print sys.builtin_module_names
  392. </pre>
  393. </li>
  394. </ol>
  395. </div>
  396. <div class="section" id="how-do-i-make-a-python-script-executable-on-unix">
  397. <h2><a class="toc-backref" href="#id6">1.3   How do I make a Python script executable on Unix?</a></h2>
  398. <p>You need to do two things: the script file's mode must be executable
  399. and the first line must begin with <tt class="docutils literal"><span class="pre">#!</span></tt>  followed by the path of
  400. the Python interpreter.</p>
  401. <p>The first is done by executing <tt class="docutils literal"><span class="pre">chmod</span> <span class="pre">+x</span> <span class="pre">scriptfile</span></tt> or perhaps
  402. <tt class="docutils literal"><span class="pre">chmod</span> <span class="pre">755</span> <span class="pre">scriptfile</span></tt>.</p>
  403. <p>The second can be done in a number of ways.  The most straightforward
  404. way is to write</p>
  405. <pre class="literal-block">
  406. #!/usr/local/bin/python
  407. </pre>
  408. <p>as the very first line of your file, using the pathname for where the
  409. Python interpreter is installed on your platform.</p>
  410. <p>If you would like the script to be independent of where the Python
  411. interpreter lives, you can use the "env" program.  Almost all
  412. Unix variants support the following, assuming the python interpreter
  413. is in a directory on the user's $PATH:</p>
  414. <pre class="literal-block">
  415. #! /usr/bin/env python
  416. </pre>
  417. <p><em>Don't</em> do this for CGI scripts.  The $PATH variable for
  418. CGI scripts is often very minimal, so you need to use the actual
  419. absolute pathname of the interpreter.</p>
  420. <p>Occasionally, a user's environment is so full that the /usr/bin/env
  421. program fails; or there's no env program at all.
  422. In that case, you can try the following hack (due to Alex Rezinsky):</p>
  423. <pre class="literal-block">
  424. #! /bin/sh
  425. """:"
  426. exec python $0 ${1+"$@"}
  427. """
  428. </pre>
  429. <p>The minor disadvantage is that this defines the script's __doc__ string.
  430. However, you can fix that by adding</p>
  431. <pre class="literal-block">
  432. __doc__ = """...Whatever..."""
  433. </pre>
  434. </div>
  435. <div class="section" id="is-there-a-curses-termcap-package-for-python">
  436. <h2><a class="toc-backref" href="#id7">1.4   Is there a curses/termcap package for Python?</a></h2>
  437. <p>For Unix variants: The standard Python source distribution comes with
  438. a curses module in the Modules/ subdirectory, though it's not compiled
  439. by default (note that this is not available in the Windows
  440. distribution -- there is no curses module for Windows).</p>
  441. <p>The curses module supports basic curses features as well as many
  442. additional functions from ncurses and SYSV curses such as colour,
  443. alternative character set support, pads, and mouse support. This means
  444. the module isn't compatible with operating systems that only
  445. have BSD curses, but there don't seem to be any currently maintained
  446. OSes that fall into this category.</p>
  447. <p>For Windows: use <a class="reference external" href="http://effbot.org/zone/console-index.htm">the consolelib module</a>.</p>
  448. </div>
  449. <div class="section" id="is-there-an-equivalent-to-c-s-onexit-in-python">
  450. <h2><a class="toc-backref" href="#id8">1.5   Is there an equivalent to C's onexit() in Python?</a></h2>
  451. <p><a class="reference external" href="http://www.python.org/doc/lib/module-atexit.html">The atexit module</a> provides a
  452. register function that is similar to C's onexit.</p>
  453. </div>
  454. <div class="section" id="why-don-t-my-signal-handlers-work">
  455. <h2><a class="toc-backref" href="#id9">1.6   Why don't my signal handlers work?</a></h2>
  456. <p>The most common problem is that the signal handler is declared
  457. with the wrong argument list.  It is called as</p>
  458. <pre class="literal-block">
  459. handler(signum, frame)
  460. </pre>
  461. <p>so it should be declared with two arguments:</p>
  462. <pre class="literal-block">
  463. def handler(signum, frame):
  464.     ...
  465. </pre>
  466. </div>
  467. </div>
  468. <div class="section" id="common-tasks">
  469. <h1><a class="toc-backref" href="#id10">2   Common tasks</a></h1>
  470. <div class="section" id="how-do-i-test-a-python-program-or-component">
  471. <h2><a class="toc-backref" href="#id11">2.1   How do I test a Python program or component?</a></h2>
  472. <p>Python comes with two testing frameworks.  The <a class="reference external" href="http://www.python.org/doc/lib/module-doctest.html">doctest module</a> finds examples
  473. in the docstrings for a module and runs them, comparing the output
  474. with the expected output given in the docstring.</p>
  475. <p>The <a class="reference external" href="http://www.python.org/doc/lib/module-unittest.html">unittest module</a> is a fancier
  476. testing framework modelled on Java and Smalltalk testing frameworks.</p>
  477. <p>For testing, it helps to write the program so that it may be easily
  478. tested by using good modular design.  Your program should have almost
  479. all functionality encapsulated in either functions or class methods --
  480. and this sometimes has the surprising and delightful effect of making
  481. the program run faster (because local variable accesses are faster
  482. than global accesses).  Furthermore the program should avoid depending
  483. on mutating global variables, since this makes testing much more
  484. difficult to do.</p>
  485. <p>The "global main logic" of your program may be as simple
  486. as</p>
  487. <pre class="literal-block">
  488. if __name__=="__main__":
  489.      main_logic()
  490. </pre>
  491. <p>at the bottom of the main module of your program.</p>
  492. <p>Once your program is organized as a tractable collection
  493. of functions and class behaviours you should write test
  494. functions that exercise the behaviours.  A test suite
  495. can be associated with each module which automates
  496. a sequence of tests.  This sounds like a lot of work, but
  497. since Python is so terse and flexible it's surprisingly easy.
  498. You can make coding much more pleasant and fun by
  499. writing your test functions in parallel with the "production
  500. code", since this makes it easy to find bugs and even
  501. design flaws earlier.</p>
  502. <p>"Support modules" that are not intended to be the main module of a
  503. program may include a self-test of the module.</p>
  504. <pre class="literal-block">
  505. if __name__ == "__main__":
  506.    self_test()
  507. </pre>
  508. <p>Even programs that interact with complex external interfaces may be
  509. tested when the external interfaces are unavailable by using "fake"
  510. interfaces implemented in Python.</p>
  511. </div>
  512. <div class="section" id="how-do-i-create-documentation-from-doc-strings">
  513. <h2><a class="toc-backref" href="#id12">2.2   How do I create documentation from doc strings?</a></h2>
  514. <p>The <a class="reference external" href="http://www.python.org/doc/lib/module-pydoc.html">pydoc module</a>
  515. can create HTML from the doc strings in your Python source code.  An
  516. alternative is <a class="reference external" href="http://starship.python.net/crew/danilo/pythondoc/">pythondoc</a>.</p>
  517. </div>
  518. <div class="section" id="how-do-i-get-a-single-keypress-at-a-time">
  519. <h2><a class="toc-backref" href="#id13">2.3   How do I get a single keypress at a time?</a></h2>
  520. <p>For Unix variants:There are several solutions.
  521. It's straightforward to do this using curses, but curses is a
  522. fairly large module to learn.  Here's a solution without curses:</p>
  523. <pre class="literal-block">
  524. import termios, fcntl, sys, os
  525. fd = sys.stdin.fileno()
  526.  
  527. oldterm = termios.tcgetattr(fd)
  528. newattr = termios.tcgetattr(fd)
  529. newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
  530. termios.tcsetattr(fd, termios.TCSANOW, newattr)
  531.  
  532. oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
  533. fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
  534.  
  535. try:
  536.     while 1:
  537.         try:
  538.             c = sys.stdin.read(1)
  539.             print "Got character", `c`
  540.         except IOError: pass
  541. finally:
  542.     termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
  543.     fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
  544. </pre>
  545. <p>You need the <tt class="docutils literal"><span class="pre">termios</span></tt> and the <tt class="docutils literal"><span class="pre">fcntl</span></tt> module for any of this to work,
  546. and I've only tried it on Linux, though it should work elsewhere.
  547. In this code, characters are read and printed one at a time.</p>
  548. <p><tt class="docutils literal"><span class="pre">termios.tcsetattr()</span></tt> turns off stdin's echoing and disables canonical
  549. mode.  <tt class="docutils literal"><span class="pre">fcntl.fnctl()</span></tt> is used to obtain stdin's file descriptor flags
  550. and modify them for non-blocking mode.  Since reading stdin when it is
  551. empty results in an <tt class="docutils literal"><span class="pre">IOError</span></tt>, this error is caught and ignored.</p>
  552. </div>
  553. </div>
  554. <div class="section" id="threads">
  555. <h1><a class="toc-backref" href="#id14">3   Threads</a></h1>
  556. <div class="section" id="how-do-i-program-using-threads">
  557. <h2><a class="toc-backref" href="#id15">3.1   How do I program using threads?</a></h2>
  558. <p>Be sure to use <a class="reference external" href="http://www.python.org/doc/lib/module-threading.html">the threading module</a> and not the
  559. <tt class="docutils literal"><span class="pre">thread</span></tt> module.  The <tt class="docutils literal"><span class="pre">threading</span></tt> module builds convenient
  560. abstractions on top of the low-level primitives provided by the
  561. <tt class="docutils literal"><span class="pre">thread</span></tt> module.</p>
  562. <p>Aahz has a set of slides from his threading tutorial that are helpful;
  563. see <a class="reference external" href="http://starship.python.net/crew/aahz/OSCON2001/">http://starship.python.net/crew/aahz/OSCON2001/</a>.</p>
  564. </div>
  565. <div class="section" id="none-of-my-threads-seem-to-run-why">
  566. <h2><a class="toc-backref" href="#id16">3.2   None of my threads seem to run: why?</a></h2>
  567. <p>As soon as the main thread exits, all threads are killed.  Your main
  568. thread is running too quickly, giving the threads no time to do any work.</p>
  569. <p>A simple fix is to add a sleep to the end of the program
  570. that's long enough for all the threads to finish:</p>
  571. <pre class="literal-block">
  572. import threading, time
  573.  
  574. def thread_task(name, n):
  575.     for i in range(n): print name, i
  576.  
  577. for i in range(10):
  578.     T = threading.Thread(target=thread_task, args=(str(i), i))
  579.     T.start()
  580.  
  581. time.sleep(10) # <----------------------------!
  582. </pre>
  583. <p>But now (on many platforms) the threads don't run in parallel,
  584. but appear to run sequentially, one at a time!  The reason is
  585. that the OS thread scheduler doesn't start a new thread until
  586. the previous thread is blocked.</p>
  587. <p>A simple fix is to add a tiny sleep to the start of the run
  588. function:</p>
  589. <pre class="literal-block">
  590. def thread_task(name, n):
  591.     time.sleep(0.001) # <---------------------!
  592.     for i in range(n): print name, i
  593.  
  594. for i in range(10):
  595.     T = threading.Thread(target=thread_task, args=(str(i), i))
  596.     T.start()
  597.  
  598. time.sleep(10)
  599. </pre>
  600. <p>Instead of trying to guess how long a <tt class="docutils literal"><span class="pre">time.sleep()</span></tt> delay will be
  601. enough, it's better to use some kind of semaphore mechanism.  One idea
  602. is to use the <a class="reference external" href="http://www.python.org/doc/lib/module-Queue.html">Queue module</a> to create a queue
  603. object, let each thread append a token to the queue when it finishes,
  604. and let the main thread read as many tokens from the queue as there
  605. are threads.</p>
  606. </div>
  607. <div class="section" id="how-do-i-parcel-out-work-among-a-bunch-of-worker-threads">
  608. <h2><a class="toc-backref" href="#id17">3.3   How do I parcel out work among a bunch of worker threads?</a></h2>
  609. <p>Use the <a class="reference external" href="http://www.python.org/doc/lib/module-Queue.html">Queue module</a> to create a queue
  610. containing a list of jobs.  The <tt class="docutils literal"><span class="pre">Queue</span></tt> class maintains a list of
  611. objects with <tt class="docutils literal"><span class="pre">.put(obj)</span></tt> to add an item to the queue and <tt class="docutils literal"><span class="pre">.get()</span></tt>
  612. to return an item.  The class will take care of the locking necessary
  613. to ensure that each job is handed out exactly once.</p>
  614. <p>Here's a trivial example:</p>
  615. <pre class="literal-block">
  616. import threading, Queue, time
  617.  
  618. # The worker thread gets jobs off the queue.  When the queue is empty, it
  619. # assumes there will be no more work and exits.
  620. # (Realistically workers will run until terminated.)
  621. def worker ():
  622.     print 'Running worker'
  623.     time.sleep(0.1)
  624.     while True:
  625.         try:
  626.             arg = q.get(block=False)
  627.         except Queue.Empty:
  628.             print 'Worker', threading.currentThread(),
  629.             print 'queue empty'
  630.             break
  631.         else:
  632.             print 'Worker', threading.currentThread(),
  633.             print 'running with argument', arg
  634.             time.sleep(0.5)
  635.  
  636. # Create queue
  637. q = Queue.Queue()
  638.  
  639. # Start a pool of 5 workers
  640. for i in range(5):
  641.     t = threading.Thread(target=worker, name='worker %i' % (i+1))
  642.     t.start()
  643.  
  644. # Begin adding work to the queue
  645. for i in range(50):
  646.     q.put(i)
  647.  
  648. # Give threads time to run
  649. print 'Main thread sleeping'
  650. time.sleep(5)
  651. </pre>
  652. <p>When run, this will produce the following output:</p>
  653. <blockquote>
  654. Running worker
  655. Running worker
  656. Running worker
  657. Running worker
  658. Running worker
  659. Main thread sleeping
  660. Worker <Thread(worker 1, started)> running with argument 0
  661. Worker <Thread(worker 2, started)> running with argument 1
  662. Worker <Thread(worker 3, started)> running with argument 2
  663. Worker <Thread(worker 4, started)> running with argument 3
  664. Worker <Thread(worker 5, started)> running with argument 4
  665. Worker <Thread(worker 1, started)> running with argument 5
  666. ...</blockquote>
  667. <p>Consult the module's documentation for more details; the <tt class="docutils literal"><span class="pre">Queue</span></tt>
  668. class provides a featureful interface.</p>
  669. </div>
  670. <div class="section" id="what-kinds-of-global-value-mutation-are-thread-safe">
  671. <h2><a class="toc-backref" href="#id18">3.4   What kinds of global value mutation are thread-safe?</a></h2>
  672. <p>A global interpreter lock (GIL) is used internally to ensure that only
  673. one thread runs in the Python VM at a time.  In general, Python offers
  674. to switch among threads only between bytecode instructions; how
  675. frequently it switches can be set via <tt class="docutils literal"><span class="pre">sys.setcheckinterval()</span></tt>.
  676. Each bytecode instruction and therefore all the C implementation code
  677. reached from each instruction is therefore atomic from the point of view of a Python program.</p>
  678. <p>In theory, this means an exact accounting requires an exact
  679. understanding of the PVM bytecode implementation.  In practice, it
  680. means that operations on shared variables of builtin data types (ints,
  681. lists, dicts, etc) that "look atomic" really are.</p>
  682. <p>For example, the following operations are all atomic (L, L1, L2 are lists, D, D1, D2 are dicts, x, y
  683. are objects, i, j are ints):</p>
  684. <pre class="literal-block">
  685. L.append(x)
  686. L1.extend(L2)
  687. x = L[i]
  688. x = L.pop()
  689. L1[i:j] = L2
  690. L.sort()
  691. x = y
  692. x.field = y
  693. D[x] = y
  694. D1.update(D2)
  695. D.keys()
  696. </pre>
  697. <p>These aren't:</p>
  698. <pre class="literal-block">
  699. i = i+1
  700. L.append(L[-1])
  701. L[i] = L[j]
  702. D[x] = D[x] + 1
  703. </pre>
  704. <p>Operations that replace other objects may invoke those other
  705. objects' <tt class="docutils literal"><span class="pre">__del__</span></tt> method when their reference count reaches zero, and
  706. that can affect things.  This is especially true for the mass updates
  707. to dictionaries and lists.  When in doubt, use a mutex!</p>
  708. </div>
  709. <div class="section" id="can-t-we-get-rid-of-the-global-interpreter-lock">
  710. <h2><a class="toc-backref" href="#id19">3.5   Can't we get rid of the Global Interpreter Lock?</a></h2>
  711. <p>The Global Interpreter Lock (GIL) is often seen as a hindrance to
  712. Python's deployment on high-end multiprocessor server machines,
  713. because a multi-threaded Python program effectively only uses one CPU,
  714. due to the insistence that (almost) all Python code can only run while
  715. the GIL is held.</p>
  716. <p>Back in the days of Python 1.5, Greg Stein actually implemented a
  717. comprehensive patch set (the "free threading" patches) that removed
  718. the GIL and replaced it with fine-grained locking.  Unfortunately, even
  719. on Windows (where locks are very efficient) this ran ordinary Python
  720. code about twice as slow as the interpreter using the GIL.  On Linux
  721. the performance loss was even worse because pthread locks aren't as
  722. efficient.</p>
  723. <p>Since then, the idea of getting rid of the GIL has occasionally come
  724. up but nobody has found a way to deal with the expected slowdown, and
  725. users who don't use threads would not be happy if their code ran at
  726. half at the speed.  Greg's free threading patch set has not been kept
  727. up-to-date for later Python versions.</p>
  728. <p>This doesn't mean that you can't make good use of Python on multi-CPU
  729. machines!  You just have to be creative with dividing the work up
  730. between multiple <em>processes</em> rather than multiple <em>threads</em>.
  731. Judicious use of C extensions will also help; if you use a C extension
  732. to perform a time-consuming task, the extension can release the GIL
  733. while the thread of execution is in the C code and allow other threads
  734. to get some work done.</p>
  735. <p>It has been suggested that the GIL should be a per-interpreter-state
  736. lock rather than truly global; interpreters then wouldn't be able to
  737. share objects.  Unfortunately, this isn't likely to happen either.  It
  738. would be a tremendous amount of work, because many object
  739. implementations currently have global state.  For example, small
  740. integers and short strings are cached; these caches would have to be
  741. moved to the interpreter state.  Other object types have their own
  742. free list; these free lists would have to be moved to the interpreter
  743. state.  And so on.</p>
  744. <p>And I doubt that it can even be done in finite time, because the same
  745. problem exists for 3rd party extensions.  It is likely that 3rd party
  746. extensions are being written at a faster rate than you can convert
  747. them to store all their global state in the interpreter state.</p>
  748. <p>And finally, once you have multiple interpreters not sharing any
  749. state, what have you gained over running each interpreter
  750. in a separate process?</p>
  751. </div>
  752. </div>
  753. <div class="section" id="input-and-output">
  754. <h1><a class="toc-backref" href="#id20">4   Input and Output</a></h1>
  755. <div class="section" id="how-do-i-delete-a-file-and-other-file-questions">
  756. <h2><a class="toc-backref" href="#id21">4.1   How do I delete a file? (And other file questions...)</a></h2>
  757. <p>Use <tt class="docutils literal"><span class="pre">os.remove(filename)</span></tt> or <tt class="docutils literal"><span class="pre">os.unlink(filename)</span></tt>; for
  758. documentation, see <a class="reference external" href="http://www.python.org/doc/lib/module-posix.html">the POSIX module</a>.  The two
  759. functions are identical; <tt class="docutils literal"><span class="pre">unlink()</span></tt> is simply the name of the Unix
  760. system call for this function.</p>
  761. <p>To remove a directory, use <tt class="docutils literal"><span class="pre">os.rmdir()</span></tt>; use <tt class="docutils literal"><span class="pre">os.mkdir()</span></tt> to
  762. create one.  <tt class="docutils literal"><span class="pre">os.makedirs(path)</span></tt> will create any intermediate
  763. directories in <tt class="docutils literal"><span class="pre">path</span></tt> that don't exist. <tt class="docutils literal"><span class="pre">os.removedirs(path)</span></tt> will
  764. remove intermediate directories as long as they're empty; if you want
  765. to delete an entire directory tree and its contents, use
  766. <tt class="docutils literal"><span class="pre">shutil.rmtree()</span></tt>.</p>
  767. <p>To rename a file, use <tt class="docutils literal"><span class="pre">os.rename(old_path,</span> <span class="pre">new_path)</span></tt>.</p>
  768. <p>To truncate a file, open it using <tt class="docutils literal"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">open(filename,</span> <span class="pre">"r+")</span></tt>, and use
  769. <tt class="docutils literal"><span class="pre">f.truncate(offset)</span></tt>; offset defaults to the current seek position.
  770. There's also <tt class="docutils literal"><span class="pre">`os.ftruncate(fd,</span> <span class="pre">offset)</span></tt> for files opened with <tt class="docutils literal"><span class="pre">os.open()</span></tt>,
  771. where <tt class="docutils literal"><span class="pre">fd</span></tt> is the file descriptor (a small integer).</p>
  772. <p>The <tt class="docutils literal"><span class="pre">shutil</span></tt> module also contains a number of functions to work on files
  773. including <tt class="docutils literal"><span class="pre">copyfile</span></tt>, <tt class="docutils literal"><span class="pre">copytree</span></tt>, and <tt class="docutils literal"><span class="pre">rmtree</span></tt>.</p>
  774. </div>
  775. <div class="section" id="how-do-i-copy-a-file">
  776. <h2><a class="toc-backref" href="#id22">4.2   How do I copy a file?</a></h2>
  777. <p>The <tt class="docutils literal"><span class="pre">shutil</span></tt> module contains a <tt class="docutils literal"><span class="pre">copyfile()</span></tt> function.  Note that
  778. on MacOS 9 it doesn't copy the resource fork and Finder info.</p>
  779. </div>
  780. <div class="section" id="how-do-i-read-or-write-binary-data">
  781. <h2><a class="toc-backref" href="#id23">4.3   How do I read (or write) binary data?</a></h2>
  782. <p>or complex data formats, it's best to use <a class="reference external" href="http://www.python.org/doc/lib/module-struct.html">the struct module</a>.  It allows you
  783. to take a string containing binary data (usually numbers) and convert
  784. it to Python objects; and vice versa.</p>
  785. <p>For example, the following code reads two 2-byte integers
  786. and one 4-byte integer in big-endian format from a file:</p>
  787. <pre class="literal-block">
  788. import struct
  789.  
  790. f = open(filename, "rb")  # Open in binary mode for portability
  791. s = f.read(8)
  792. x, y, z = struct.unpack(">hhl", s)
  793. </pre>
  794. <p>The '>' in the format string forces big-endian data; the letter
  795. 'h' reads one "short integer" (2 bytes), and 'l' reads one
  796. "long integer" (4 bytes) from the string.</p>
  797. <p>For data that is more regular (e.g. a homogeneous list of ints or
  798. thefloats), you can also use <a class="reference external" href="http://www.python.org/doc/lib/module-array.html">the array module</a>.</p>
  799. </div>
  800. <div class="section" id="i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why">
  801. <h2><a class="toc-backref" href="#id24">4.4   I can't seem to use os.read() on a pipe created with os.popen(); why?</a></h2>
  802. <p><tt class="docutils literal"><span class="pre">os.read()</span></tt> is a low-level function which takes a file descriptor, a
  803. small integer representing the opened file.  <tt class="docutils literal"><span class="pre">os.popen()</span></tt> creates a
  804. high-level file object, the same type returned by the builtin
  805. <tt class="docutils literal"><span class="pre">open()</span></tt> function.  Thus, to read n bytes from a pipe p created with
  806. <tt class="docutils literal"><span class="pre">os.popen()</span></tt>, you need to use <tt class="docutils literal"><span class="pre">p.read(n)</span></tt>.</p>
  807. </div>
  808. <div class="section" id="how-do-i-run-a-subprocess-with-pipes-connected-to-both-input-and-output">
  809. <h2><a class="toc-backref" href="#id25">4.5   How do I run a subprocess with pipes connected to both input and output?</a></h2>
  810. <p>Use <a class="reference external" href="http://www.python.org/doc/lib/module-popen2.html">the popen2 module</a>.  For example:</p>
  811. <pre class="literal-block">
  812. import popen2
  813. fromchild, tochild = popen2.popen2("command")
  814. tochild.write("input\n")
  815. tochild.flush()
  816. output = fromchild.readline()
  817. </pre>
  818. <p>Warning: in general it is unwise to do this because you can easily
  819. cause a deadlock where your process is blocked waiting for output from
  820. the child while the child is blocked waiting for input from you.  This
  821. can be caused because the parent expects the child to output more text
  822. than it does, or it can be caused by data being stuck in stdio buffers
  823. due to lack of flushing.  The Python parent can of course explicitly
  824. flush the data it sends to the child before it reads any output, but
  825. if the child is a naive C program it may have been written to never
  826. explicitly flush its output, even if it is interactive, since flushing
  827. is normally automatic.</p>
  828. <p>Note that a deadlock is also possible if you use <tt class="docutils literal"><span class="pre">popen3</span></tt> to read
  829. stdout and stderr. If one of the two is too large for the internal
  830. buffer (increasing the buffer size does not help) and you <tt class="docutils literal"><span class="pre">read()</span></tt>
  831. the other one first, there is a deadlock, too.</p>
  832. <p>Note on a bug in popen2: unless your program calls <tt class="docutils literal"><span class="pre">wait()</span></tt>
  833. or <tt class="docutils literal"><span class="pre">waitpid()</span></tt>, finished child processes are never removed,
  834. and eventually calls to popen2 will fail because of a limit on
  835. the number of child processes.  Calling <tt class="docutils literal"><span class="pre">os.waitpid</span></tt> with the
  836. <tt class="docutils literal"><span class="pre">os.WNOHANG</span></tt> option can prevent this; a good place to insert such
  837. a call would be before calling <tt class="docutils literal"><span class="pre">popen2</span></tt> again.</p>
  838. <p>In many cases, all you really need is to run some data through a
  839. command and get the result back.  Unless the amount of data is very
  840. large, the easiest way to do this is to write it to a temporary file
  841. and run the command with that temporary file as input.  The <a class="reference external" href="http://www.python.org/doc/lib/module-tempfile.html">standard
  842. module tempfile</a>
  843. exports a <tt class="docutils literal"><span class="pre">mktemp()</span></tt> function  to generate unique temporary file names.</p>
  844. <pre class="literal-block">
  845. import tempfile
  846. import os
  847. class Popen3:
  848.    """
  849.    This is a deadlock-safe version of popen that returns
  850.    an object with errorlevel, out (a string) and err (a string).
  851.    (capturestderr may not work under windows.)
  852.    Example: print Popen3('grep spam','\n\nhere spam\n\n').out
  853.    """
  854.    def __init__(self,command,input=None,capturestderr=None):
  855.        outfile=tempfile.mktemp()
  856.        command="( %s ) > %s" % (command,outfile)
  857.        if input:
  858.            infile=tempfile.mktemp()
  859.            open(infile,"w").write(input)
  860.            command=command+" <"+infile
  861.        if capturestderr:
  862.            errfile=tempfile.mktemp()
  863.            command=command+" 2>"+errfile
  864.        self.errorlevel=os.system(command) >> 8
  865.        self.out=open(outfile,"r").read()
  866.        os.remove(outfile)
  867.        if input:
  868.            os.remove(infile)
  869.        if capturestderr:
  870.            self.err=open(errfile,"r").read()
  871.            os.remove(errfile)
  872. </pre>
  873. <p>Note that many interactive programs (e.g. vi) don't work well with
  874. pipes substituted for standard input and output.  You will have to use
  875. pseudo ttys ("ptys") instead of pipes. Or you can use a Python
  876. interface to Don Libes' "expect" library.  A Python extension that
  877. interfaces to expect is called "expy" and available from
  878. <a class="reference external" href="http://expectpy.sourceforge.net">http://expectpy.sourceforge.net</a>.  A pure Python solution that works
  879. like expect is ` pexpect <<a class="reference external" href="http://pexpect.sourceforge.net">http://pexpect.sourceforge.net</a>>`_.</p>
  880. </div>
  881. <div class="section" id="how-do-i-access-the-serial-rs232-port">
  882. <h2><a class="toc-backref" href="#id26">4.6   How do I access the serial (RS232) port?</a></h2>
  883. <p>For Win32, POSIX (Linux, BSD, etc.), Jython:</p>
  884. <blockquote>
  885. <a class="reference external" href="http://pyserial.sourceforge.net">http://pyserial.sourceforge.net</a></blockquote>
  886. <p>For Unix, see a Usenet post by Mitch Chapman:</p>
  887. <blockquote>
  888. <a class="reference external" href="http://groups.google.com/groups?selm=34A04430.CF9@ohioee.com">http://groups.google.com/groups?selm=34A04430.CF9@ohioee.com</a></blockquote>
  889. </div>
  890. <div class="section" id="why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it">
  891. <h2><a class="toc-backref" href="#id27">4.7   Why doesn't closing sys.stdout (stdin, stderr) really close it?</a></h2>
  892. <p>Python file objects are a high-level layer of abstraction on top of C
  893. streams, which in turn are a medium-level layer of abstraction on top
  894. of (among other things) low-level C file descriptors.</p>
  895. <p>For most file objects you create in Python via the builtin <tt class="docutils literal"><span class="pre">file</span></tt>
  896. constructor, <tt class="docutils literal"><span class="pre">f.close()</span></tt> marks the Python file object as being closed
  897. from Python's point of view, and also arranges to close the underlying
  898. C stream.  This also happens automatically in f's destructor, when f
  899. becomes garbage.</p>
  900. <p>But stdin, stdout and stderr are treated specially by Python, because
  901. of the special status also given to them by C.  Running
  902. <tt class="docutils literal"><span class="pre">sys.stdout.close()</span></tt> marks the Python-level file object as being
  903. closed, but does <em>not</em> close the associated C stream.</p>
  904. <p>To close the underlying C stream for one of these three, you should
  905. first be sure that's what you really want to do (e.g., you may confuse
  906. extension modules trying to do I/O).  If it is, use
  907. os.close:</p>
  908. <pre class="literal-block">
  909. os.close(0)   # close C's stdin stream
  910. os.close(1)   # close C's stdout stream
  911. os.close(2)   # close C's stderr stream
  912. </pre>
  913. </div>
  914. </div>
  915. <div class="section" id="network-internet-programming">
  916. <h1><a class="toc-backref" href="#id28">5   Network/Internet Programming</a></h1>
  917. <div class="section" id="what-www-tools-are-there-for-python">
  918. <h2><a class="toc-backref" href="#id29">5.1   What WWW tools are there for Python?</a></h2>
  919. <p>See the chapters titled <a class="reference external" href="http://www.python.org/doc/lib/internet.html">"Internet Protocols and Support"</a> and <a class="reference external" href="http://www.python.org/doc/lib/netdata.html">"Internet Data
  920. Handling"</a> in the
  921. Library Reference Manual. Python has many modules that will help you
  922. build server-side and client-side web systems.</p>
  923. <p>A summary of available frameworks is maintained by Paul Boddie at
  924. <a class="reference external" href="http://www.python.org/cgi-bin/moinmoin/WebProgramming">http://www.python.org/cgi-bin/moinmoin/WebProgramming</a> .</p>
  925. <p>Cameron Laird maintains a useful set of pages about Python web technologies at
  926. <a class="reference external" href="http://phaseit.net/claird/comp.lang.python/web_python.html">http://phaseit.net/claird/comp.lang.python/web_python.html</a>.</p>
  927. <p>The <a class="reference external" href="http://www.python.org/topics/web/">Web Programming topic guide</a>
  928. also points to many useful resources.</p>
  929. </div>
  930. <div class="section" id="how-can-i-mimic-cgi-form-submission-method-post">
  931. <h2><a class="toc-backref" href="#id30">5.2   How can I mimic CGI form submission (METHOD=POST)?</a></h2>
  932. <p>I would like to retrieve web pages that are the result of POSTing a
  933. form. Is there existing code that would let me do this easily?</p>
  934. <p>Yes. Here's a simple example that uses httplib:</p>
  935. <pre class="literal-block">
  936. #!/usr/local/bin/python
  937.  
  938. import httplib, sys, time
  939.  
  940. ### build the query string
  941. qs = "First=Josephine&MI=Q&Last=Public"
  942.  
  943. ### connect and send the server a path
  944. httpobj = httplib.HTTP('www.some-server.out-there', 80)
  945. httpobj.putrequest('POST', '/cgi-bin/some-cgi-script')
  946. ### now generate the rest of the HTTP headers...
  947. httpobj.putheader('Accept', '*/*')
  948. httpobj.putheader('Connection', 'Keep-Alive')
  949. httpobj.putheader('Content-type', 'application/x-www-form-urlencoded')
  950. httpobj.putheader('Content-length', '%d' % len(qs))
  951. httpobj.endheaders()
  952. httpobj.send(qs)
  953. ### find out what the server said in response...
  954. reply, msg, hdrs = httpobj.getreply()
  955. if reply != 200:
  956.     sys.stdout.write(httpobj.getfile().read())
  957. </pre>
  958. <p>Note that in general for URL-encoded POST operations,  query
  959. strings must be quoted by using <tt class="docutils literal"><span class="pre">urllib.quote()</span></tt>.  For example to send name="Guy
  960. Steele, Jr.":</p>
  961. <pre class="literal-block">
  962. >>> from urllib import quote
  963. >>> x = quote("Guy Steele, Jr.")
  964. >>> x
  965. 'Guy%20Steele,%20Jr.'
  966. >>> query_string = "name="+x
  967. >>> query_string
  968. 'name=Guy%20Steele,%20Jr.'
  969. </pre>
  970. </div>
  971. <div class="section" id="what-module-should-i-use-to-help-with-generating-html">
  972. <h2><a class="toc-backref" href="#id31">5.3   What module should I use to help with generating HTML?</a></h2>
  973. <p>There are many different modules available:</p>
  974. <ul class="simple">
  975. <li>HTMLgen is a class library of objects corresponding to all the HTML
  976. 3.2 markup tags. It's used when you are writing in Python and wish
  977. to synthesize HTML pages for generating a web or for CGI forms, etc.</li>
  978. <li>DocumentTemplate and Zope Page Templates are two different systems that are
  979. part of Zope.</li>
  980. <li>Quixote's PTL uses Python syntax to assemble strings of text.</li>
  981. </ul>
  982. <p>Consult the <a class="reference external" href="http://www.python.org/topics/web/">Web Programming topic guide</a> for more links.</p>
  983. </div>
  984. <div class="section" id="how-do-i-send-mail-from-a-python-script">
  985. <h2><a class="toc-backref" href="#id32">5.4   How do I send mail from a Python script?</a></h2>
  986. <p>Use <a class="reference external" href="http://www.python.org/doc/lib/module-smtplib.html">the standard library module smtplib</a>.</p>
  987. <p>Here's a very simple interactive mail sender that uses it.  This
  988. method will work on any host that supports an SMTP listener.</p>
  989. <pre class="literal-block">
  990. import sys, smtplib
  991.  
  992. fromaddr = raw_input("From: ")
  993. toaddrs  = raw_input("To: ").split(',')
  994. print "Enter message, end with ^D:"
  995. msg = ''
  996. while 1:
  997.     line = sys.stdin.readline()
  998.     if not line:
  999.         break
  1000.     msg = msg + line
  1001.  
  1002. # The actual mail send
  1003. server = smtplib.SMTP('localhost')
  1004. server.sendmail(fromaddr, toaddrs, msg)
  1005. server.quit()
  1006. </pre>
  1007. <p>A Unix-only alternative uses sendmail.  The location of the
  1008. sendmail program varies between systems; sometimes it is
  1009. <tt class="docutils literal"><span class="pre">/usr/lib/sendmail</span></tt>, sometime <tt class="docutils literal"><span class="pre">/usr/sbin/sendmail</span></tt>.  The sendmail
  1010. manual page will help you out.  Here's some sample code:</p>
  1011. <pre class="literal-block">
  1012. SENDMAIL = "/usr/sbin/sendmail" # sendmail location
  1013. import os
  1014. p = os.popen("%s -t -i" % SENDMAIL, "w")
  1015. p.write("To: receiver@example.com\n")
  1016. p.write("Subject: test\n")
  1017. p.write("\n") # blank line separating headers from body
  1018. p.write("Some text\n")
  1019. p.write("some more text\n")
  1020. sts = p.close()
  1021. if sts != 0:
  1022.     print "Sendmail exit status", sts
  1023. </pre>
  1024. </div>
  1025. <div class="section" id="how-do-i-avoid-blocking-in-the-connect-method-of-a-socket">
  1026. <h2><a class="toc-backref" href="#id33">5.5   How do I avoid blocking in the connect() method of a socket?</a></h2>
  1027. <p>The select module is commonly used to help with asynchronous
  1028. I/O on sockets.</p>
  1029. <p>To prevent the TCP connect from blocking, you can set the socket to
  1030. non-blocking mode.  Then when you do the <tt class="docutils literal"><span class="pre">connect()</span></tt>, you will
  1031. either connect immediately (unlikely) or get an exception that
  1032. contains the error number as <tt class="docutils literal"><span class="pre">.errno</span></tt>.  <tt class="docutils literal"><span class="pre">errno.EINPROGRESS</span></tt>
  1033. indicates that the connection is in progress, but hasn't finished yet.
  1034. Different OSes will return different values, so you're going to have
  1035. to check what's returned on your system.</p>
  1036. <p>You can use the <tt class="docutils literal"><span class="pre">connect_ex()</span></tt> method to avoid creating an
  1037. exception.  It will just return the errno value.  To poll, you can
  1038. call <tt class="docutils literal"><span class="pre">connect_ex()</span></tt> again later -- 0 or <tt class="docutils literal"><span class="pre">errno.EISCONN</span></tt> indicate
  1039. that you're connected -- or you can pass this socket to select to
  1040. check if it's writeable.</p>
  1041. </div>
  1042. </div>
  1043. <div class="section" id="databases">
  1044. <h1><a class="toc-backref" href="#id34">6   Databases</a></h1>
  1045. <div class="section" id="are-there-any-interfaces-to-database-packages-in-python">
  1046. <h2><a class="toc-backref" href="#id35">6.1   Are there any interfaces to database packages in Python?</a></h2>
  1047. <p>Yes.</p>
  1048. <p>Python 2.3 includes the <tt class="docutils literal"><span class="pre">bsddb</span></tt> package which provides an interface
  1049. to the <a class="reference external" href="http://www.python.org/doc/lib/module-bsddb.html">BerkeleyDB</a> library.
  1050. Interfaces to disk-based hashes such as <a class="reference external" href="http://www.python.org/doc/lib/module-dbm.html">DBM</a> and <a class="reference external" href="http://www.python.org/doc/lib/module-gdbm.html">GDBM</a> are also included
  1051. with standard Python.</p>
  1052. <p>Support for most relational databases is available.  See the <a class="reference external" href="http://www.python.org/topics/database">Database
  1053. Topic Guide</a> for details.</p>
  1054. </div>
  1055. <div class="section" id="how-do-you-implement-persistent-objects-in-python">
  1056. <h2><a class="toc-backref" href="#id36">6.2   How do you implement persistent objects in Python?</a></h2>
  1057. <p>The <a class="reference external" href="http://www.python.org/doc/lib/module-pickle.html">pickle library module</a> solves this in a
  1058. very general way (though you still can't store things like open files,
  1059. sockets or windows), and the <a class="reference external" href="http://www.python.org/doc/lib/module-shelve.html">shelve library module</a> uses pickle and
  1060. (g)dbm to create persistent mappings containing arbitrary Python
  1061. objects.  For better performance, you can use
  1062. <a class="reference external" href="http://www.python.org/doc/lib/module-cPickle.html">the cPickle module</a>.</p>
  1063. <p>A more awkward way of doing things is to use pickle's little sister,
  1064. marshal.  <a class="reference external" href="http://www.python.org/doc/lib/module-marshal.html">The marshal module</a> provides very
  1065. fast ways to store noncircular basic Python types to files and
  1066. strings, and back again.  Although marshal does not do fancy things
  1067. like store instances or handle shared references properly, it does run
  1068. extremely fast.  For example loading a half megabyte of data may take
  1069. less than a third of a second.  This often beats doing something more
  1070. complex and general such as using gdbm with pickle/shelve.</p>
  1071. </div>
  1072. <div class="section" id="why-is-cpickle-so-slow">
  1073. <h2><a class="toc-backref" href="#id37">6.3   Why is cPickle so slow?</a></h2>
  1074. <p>The default format used by the pickle module is a slow one that
  1075. results in readable pickles.  Making it the default, but it would
  1076. break backward compatibility:</p>
  1077. <pre class="literal-block">
  1078. largeString = 'z' * (100 * 1024)
  1079. myPickle = cPickle.dumps(largeString, protocol=1)
  1080. </pre>
  1081. </div>
  1082. <div class="section" id="if-my-program-crashes-with-a-bsddb-or-anydbm-database-open-it-gets-corrupted-how-come">
  1083. <h2><a class="toc-backref" href="#id38">6.4   If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?</a></h2>
  1084. <p>Databases opened for write access with the bsddb module (and often by
  1085. the anydbm module, since it will preferentially use bsddb) must
  1086. explicitly be closed using the <tt class="docutils literal"><span class="pre">.close()</span></tt> method of the database.  The
  1087. underlying library caches database contents which need to be
  1088. converted to on-disk form and written.</p>
  1089. <p>If you have initialized a new bsddb database but not written anything to
  1090. it before the program crashes, you will often wind up with a zero-length
  1091. file and encounter an exception the next time the file is opened.</p>
  1092. </div>
  1093. <div class="section" id="i-tried-to-open-berkeley-db-file-but-bsddb-produces-bsddb-error-22-invalid-argument-help-how-can-i-restore-my-data">
  1094. <h2><a class="toc-backref" href="#id39">6.5   I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data?</a></h2>
  1095. <p>Don't panic! Your data is probably intact. The most frequent cause
  1096. for the error is that you tried to open an earlier Berkeley DB file
  1097. with a later version of the Berkeley DB library.</p>
  1098. <p>Many Linux systems now have all three versions of Berkeley DB
  1099. available.  If you are migrating from version 1 to a newer version use
  1100. db_dump185 to dump a plain text version of the database.
  1101. If you are migrating from version 2 to version 3 use db2_dump to create
  1102. a plain text version of the database.  In either case, use db_load to
  1103. create a new native database for the latest version installed on your
  1104. computer.  If you have version 3 of Berkeley DB installed, you should
  1105. be able to use db2_load to create a native version 2 database.</p>
  1106. <p>You should move away from Berkeley DB version 1 files because
  1107. the hash file code contains known bugs that can corrupt your data.</p>
  1108. </div>
  1109. </div>
  1110. <div class="section" id="mathematics-and-numerics">
  1111. <h1><a class="toc-backref" href="#id40">7   Mathematics and Numerics</a></h1>
  1112. <div class="section" id="how-do-i-generate-random-numbers-in-python">
  1113. <h2><a class="toc-backref" href="#id41">7.1   How do I generate random numbers in Python?</a></h2>
  1114. <p>The <a class="reference external" href="http://www.python.org/doc/lib/module-random.html">standard module random</a> implements a random number
  1115. generator.  Usage is simple:</p>
  1116. <pre class="literal-block">
  1117. import random
  1118. random.random()
  1119. </pre>
  1120. <p>This returns a random floating point number in the range [0, 1).</p>
  1121. <p>There are also many other specialized generators in this module, such
  1122. as:</p>
  1123. <ul class="simple">
  1124. <li><tt class="docutils literal"><span class="pre">randrange(a,</span> <span class="pre">b)</span></tt> chooses an integer in the range [a, b).</li>
  1125. <li><tt class="docutils literal"><span class="pre">uniform(a,</span> <span class="pre">b)</span></tt> chooses a floating point number in the range [a, b).</li>
  1126. <li><tt class="docutils literal"><span class="pre">normalvariate(mean,</span> <span class="pre">sdev)</span></tt> samples the normal (Gaussian) distribution.</li>
  1127. </ul>
  1128. <p>Some higher-level functions operate on sequences directly, such as:</p>
  1129. <ul class="simple">
  1130. <li><tt class="docutils literal"><span class="pre">choice(S)</span></tt> chooses random element from a given sequence</li>
  1131. <li><tt class="docutils literal"><span class="pre">shuffle(L)</span></tt> shuffles a list in-place, i.e. permutes it randomly</li>
  1132. </ul>
  1133. <p>There's also a <tt class="docutils literal"><span class="pre">Random</span></tt> class you can instantiate
  1134. to create independent multiple random number generators.</p>
  1135. </div>
  1136. </div>
  1137. </div>
  1138. </body>
  1139. </html>
  1140.