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