home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / share / doc / python / faq / extending.html next >
Encoding:
Extensible Markup Language  |  2006-07-05  |  35.5 KB  |  746 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>Extending/Embedding FAQ</title>
  8. <meta name="date" content="2004-04-08" />
  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="extending-embedding-faq">
  295. <h1 class="title">Extending/Embedding 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>2004-04-08</td></tr>
  302. <tr><th class="docinfo-name">Version:</th>
  303. <td>7294</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="#can-i-create-my-own-functions-in-c" id="id7" name="id7">1   Can I create my own functions in C?</a></li>
  312. <li><a class="reference" href="#id1" id="id8" name="id8">2   Can I create my own functions in C++?</a></li>
  313. <li><a class="reference" href="#writing-c-is-hard-are-there-any-alternatives" id="id9" name="id9">3   Writing C is hard; are there any alternatives?</a></li>
  314. <li><a class="reference" href="#how-can-i-execute-arbitrary-python-statements-from-c" id="id10" name="id10">4   How can I execute arbitrary Python statements from C?</a></li>
  315. <li><a class="reference" href="#how-can-i-evaluate-an-arbitrary-python-expression-from-c" id="id11" name="id11">5   How can I evaluate an arbitrary Python expression from C?</a></li>
  316. <li><a class="reference" href="#how-do-i-extract-c-values-from-a-python-object" id="id12" name="id12">6   How do I extract C values from a Python object?</a></li>
  317. <li><a class="reference" href="#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length" id="id13" name="id13">7   How do I use Py_BuildValue() to create a tuple of arbitrary length?</a></li>
  318. <li><a class="reference" href="#how-do-i-call-an-object-s-method-from-c" id="id14" name="id14">8   How do I call an object's method from C?</a></li>
  319. <li><a class="reference" href="#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr" id="id15" name="id15">9   How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a></li>
  320. <li><a class="reference" href="#how-do-i-access-a-module-written-in-python-from-c" id="id16" name="id16">10   How do I access a module written in Python from C?</a></li>
  321. <li><a class="reference" href="#how-do-i-interface-to-c-objects-from-python" id="id17" name="id17">11   How do I interface to C++ objects from Python?</a></li>
  322. <li><a class="reference" href="#i-added-a-module-using-the-setup-file-and-the-make-fails-why" id="id18" name="id18">12   I added a module using the Setup file and the make fails; why?</a></li>
  323. <li><a class="reference" href="#how-do-i-debug-an-extension" id="id19" name="id19">13   How do I debug an extension?</a></li>
  324. <li><a class="reference" href="#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why" id="id20" name="id20">14   I want to compile a Python module on my Linux system, but some files are missing. Why?</a></li>
  325. <li><a class="reference" href="#what-does-systemerror-pyimport-fixupextension-module-yourmodule-not-loaded-mean" id="id21" name="id21">15   What does "SystemError: _PyImport_FixupExtension: module yourmodule not loaded" mean?</a></li>
  326. <li><a class="reference" href="#how-do-i-tell-incomplete-input-from-invalid-input" id="id22" name="id22">16   How do I tell "incomplete input" from "invalid input"?</a></li>
  327. <li><a class="reference" href="#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual" id="id23" name="id23">17   How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a></li>
  328. <li><a class="reference" href="#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance" id="id24" name="id24">18   Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a></li>
  329. <li><a class="reference" href="#when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2" id="id25" name="id25">19   When importing module X, why do I get "undefined symbol: PyUnicodeUCS2*"?</a></li>
  330. </ul>
  331. </div>
  332. <div class="section">
  333. <h1><a class="toc-backref" href="#id7" id="can-i-create-my-own-functions-in-c" name="can-i-create-my-own-functions-in-c">1   Can I create my own functions in C?</a></h1>
  334. <p>Yes, you can create built-in modules containing functions,
  335. variables, exceptions and even new types in C.  This is explained in
  336. the document "Extending and Embedding the Python Interpreter" (<a class="reference" href="http://docs.python.org/ext/ext.html">http://docs.python.org/ext/ext.html</a>).</p>
  337. <p>Most intermediate or advanced Python books will also
  338. cover this topic.</p>
  339. </div>
  340. <div class="section">
  341. <h1><a class="toc-backref" href="#id8" id="id1" name="id1">2   Can I create my own functions in C++?</a></h1>
  342. <p>Yes, using the C compatibility features found in C++.
  343. Place <tt class="docutils literal"><span class="pre">extern</span> <span class="pre">"C"</span> <span class="pre">{</span> <span class="pre">...</span> <span class="pre">}</span></tt> around the Python include files and put
  344. <tt class="docutils literal"><span class="pre">extern</span> <span class="pre">"C"</span></tt> before each function that is going to be called by the
  345. Python interpreter.  Global or static C++ objects with constructors
  346. are probably not a good idea.</p>
  347. </div>
  348. <div class="section">
  349. <h1><a class="toc-backref" href="#id9" id="writing-c-is-hard-are-there-any-alternatives" name="writing-c-is-hard-are-there-any-alternatives">3   Writing C is hard; are there any alternatives?</a></h1>
  350. <p>There are a number of alternatives to writing your own C extensions,
  351. depending on what you're trying to do.</p>
  352. <p>If you need more speed, <a class="reference" href="http://psyco.sourceforge.net/">Psyco</a> generates x86 assembly code
  353. from Python bytecode.  You can use Psyco to compile the most
  354. time-critical functions in your code, and gain a significant
  355. improvement with very little effort, as long as you're running on a
  356. machine with an x86-compatible processor.</p>
  357. <p><a class="reference" href="http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/">Pyrex</a> is a compiler that accepts a slightly modified form of Python
  358. and generates the corresponding C code.  Pyrex makes it possible to write
  359. an extension without having to learn Python's C API.</p>
  360. <p>If you need to interface to some C library for which no Python
  361. extension currently exists, you can try wrapping the library's data
  362. types and functions with a tool such as <a class="reference" href="http://www.swig.org">SWIG</a>.
  363. For C++ libraries, you can look at <a class="reference" href="http://www.riverbankcomputing.co.uk/sip/">SIP</a>, <a class="reference" href="http://cxx.sourceforge.net/">CXX</a>, <a class="reference" href="http://www.boost.org/libs/python/doc/index.html">Boost</a>, or <a class="reference" href="http://www.scipy.org/site_content/weave">Weave</a>.</p>
  364. </div>
  365. <div class="section">
  366. <h1><a class="toc-backref" href="#id10" id="how-can-i-execute-arbitrary-python-statements-from-c" name="how-can-i-execute-arbitrary-python-statements-from-c">4   How can I execute arbitrary Python statements from C?</a></h1>
  367. <p>The highest-level function to do this is <tt class="docutils literal"><span class="pre">PyRun_SimpleString()</span></tt> which takes
  368. a single string argument to be executed in the context of the module
  369. <tt class="docutils literal"><span class="pre">__main__</span></tt> and returns 0 for success and -1 when an exception occurred
  370. (including <tt class="docutils literal"><span class="pre">SyntaxError</span></tt>).  If you want more control, use <tt class="docutils literal"><span class="pre">PyRun_String()</span></tt>;
  371. see the source for <tt class="docutils literal"><span class="pre">PyRun_SimpleString()</span></tt> in Python/pythonrun.c.</p>
  372. </div>
  373. <div class="section">
  374. <h1><a class="toc-backref" href="#id11" id="how-can-i-evaluate-an-arbitrary-python-expression-from-c" name="how-can-i-evaluate-an-arbitrary-python-expression-from-c">5   How can I evaluate an arbitrary Python expression from C?</a></h1>
  375. <p>Call the function <tt class="docutils literal"><span class="pre">PyRun_String()</span></tt> from the previous question with the
  376. start symbol <tt class="docutils literal"><span class="pre">Py_eval_input</span></tt>; it
  377. parses an expression, evaluates it and returns its value.</p>
  378. </div>
  379. <div class="section">
  380. <h1><a class="toc-backref" href="#id12" id="how-do-i-extract-c-values-from-a-python-object" name="how-do-i-extract-c-values-from-a-python-object">6   How do I extract C values from a Python object?</a></h1>
  381. <p>That depends on the object's type.  If it's a tuple,
  382. <tt class="docutils literal"><span class="pre">PyTupleSize(o)</span></tt> returns its length and <tt class="docutils literal"><span class="pre">PyTuple_GetItem(o,</span> <span class="pre">i)</span></tt>
  383. returns its i'th item.  Lists have similar functions, <tt class="docutils literal"><span class="pre">PyListSize(o)</span></tt>
  384. and <tt class="docutils literal"><span class="pre">PyList_GetItem(o,</span> <span class="pre">i)</span></tt>.</p>
  385. <p>For strings, <tt class="docutils literal"><span class="pre">PyString_Size(o)</span></tt> returns
  386. its length and <tt class="docutils literal"><span class="pre">PyString_AsString(o)</span></tt> a pointer to its value.
  387. Note that Python strings may contain null bytes so C's <tt class="docutils literal"><span class="pre">strlen()</span></tt>
  388. should not be used.</p>
  389. <p>To test the type of an object, first make sure
  390. it isn't NULL, and then use <tt class="docutils literal"><span class="pre">PyString_Check(o)</span></tt>, <tt class="docutils literal"><span class="pre">PyTuple_Check(o)</span></tt>,
  391. <tt class="docutils literal"><span class="pre">PyList_Check(o)</span></tt>, etc.</p>
  392. <p>There is also a high-level API to Python objects which is
  393. provided by the so-called 'abstract' interface -- read
  394. <tt class="docutils literal"><span class="pre">Include/abstract.h</span></tt> for further details.  It allows
  395. interfacing with any kind of Python sequence
  396. using calls like <tt class="docutils literal"><span class="pre">PySequence_Length()</span></tt>, <tt class="docutils literal"><span class="pre">PySequence_GetItem()</span></tt>, etc.)
  397. as well as many other useful protocols.</p>
  398. </div>
  399. <div class="section">
  400. <h1><a class="toc-backref" href="#id13" id="how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length" name="how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length">7   How do I use Py_BuildValue() to create a tuple of arbitrary length?</a></h1>
  401. <p>You can't.  Use <tt class="docutils literal"><span class="pre">t</span> <span class="pre">=</span> <span class="pre">PyTuple_New(n)</span></tt> instead, and fill it with
  402. objects using <tt class="docutils literal"><span class="pre">PyTuple_SetItem(t,</span> <span class="pre">i,</span> <span class="pre">o)</span></tt> -- note that this "eats" a
  403. reference count of <tt class="docutils literal"><span class="pre">o</span></tt>, so you have to <tt class="docutils literal"><span class="pre">Py_INCREF</span></tt> it.
  404. Lists have similar functions <tt class="docutils literal"><span class="pre">PyList_New(n)</span></tt> and
  405. <tt class="docutils literal"><span class="pre">PyList_SetItem(l,</span> <span class="pre">i,</span> <span class="pre">o)</span></tt>.  Note that you <em>must</em> set all the tuple items to
  406. some value before you pass the tuple to Python code --
  407. <tt class="docutils literal"><span class="pre">PyTuple_New(n)</span></tt> initializes them to NULL, which isn't a valid Python
  408. value.</p>
  409. </div>
  410. <div class="section">
  411. <h1><a class="toc-backref" href="#id14" id="how-do-i-call-an-object-s-method-from-c" name="how-do-i-call-an-object-s-method-from-c">8   How do I call an object's method from C?</a></h1>
  412. <p>The <tt class="docutils literal"><span class="pre">PyObject_CallMethod()</span></tt> function can be used to call an arbitrary
  413. method of an object.  The parameters are the object, the name of the
  414. method to call, a format string like that used with <tt class="docutils literal"><span class="pre">Py_BuildValue()</span></tt>, and the argument values:</p>
  415. <pre class="literal-block">
  416. PyObject *
  417. PyObject_CallMethod(PyObject *object, char *method_name,
  418.                     char *arg_format, ...);
  419. </pre>
  420. <p>This works for any object that has methods -- whether built-in or
  421. user-defined.  You are responsible for eventually <tt class="docutils literal"><span class="pre">Py_DECREF</span></tt>'ing the
  422. return value.</p>
  423. <p>To call, e.g., a file object's "seek" method with arguments 10, 0
  424. (assuming the file object pointer is "f"):</p>
  425. <pre class="literal-block">
  426. res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
  427. if (res == NULL) {
  428.         ... an exception occurred ...
  429. }
  430. else {
  431.         Py_DECREF(res);
  432. }
  433. </pre>
  434. <p>Note that since <tt class="docutils literal"><span class="pre">PyObject_CallObject()</span></tt> <em>always</em> wants a tuple for the
  435. argument list, to call a function without arguments, pass "()" for the
  436. format, and to call a function with one argument, surround the argument
  437. in parentheses, e.g. "(i)".</p>
  438. </div>
  439. <div class="section">
  440. <h1><a class="toc-backref" href="#id15" id="how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr" name="how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr">9   How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a></h1>
  441. <p>In Python code, define an object that supports the <tt class="docutils literal"><span class="pre">write()</span></tt> method.
  442. Assign this object to <tt class="docutils literal"><span class="pre">sys.stdout</span></tt> and <tt class="docutils literal"><span class="pre">sys.stderr</span></tt>.
  443. Call print_error, or just allow the standard traceback mechanism to
  444. work. Then, the output will go wherever your <tt class="docutils literal"><span class="pre">write()</span></tt> method sends it.</p>
  445. <p>The easiest way to do this is to use the StringIO class in the standard
  446. library.</p>
  447. <p>Sample code and use for catching stdout:</p>
  448. <pre class="literal-block">
  449. >>> class StdoutCatcher:
  450. ...     def __init__(self):
  451. ...         self.data = ''
  452. ...     def write(self, stuff):
  453. ...         self.data = self.data + stuff
  454. ...
  455. >>> import sys
  456. >>> sys.stdout = StdoutCatcher()
  457. >>> print 'foo'
  458. >>> print 'hello world!'
  459. >>> sys.stderr.write(sys.stdout.data)
  460. foo
  461. hello world!
  462. </pre>
  463. </div>
  464. <div class="section">
  465. <h1><a class="toc-backref" href="#id16" id="how-do-i-access-a-module-written-in-python-from-c" name="how-do-i-access-a-module-written-in-python-from-c">10   How do I access a module written in Python from C?</a></h1>
  466. <p>You can get a pointer to the module object as follows:</p>
  467. <pre class="literal-block">
  468. module = PyImport_ImportModule("<modulename>");
  469. </pre>
  470. <p>If the module hasn't been imported yet (i.e. it is not yet present in
  471. <tt class="docutils literal"><span class="pre">sys.modules</span></tt>), this initializes the module; otherwise it simply returns
  472. the value of <tt class="docutils literal"><span class="pre">sys.modules["<modulename>"]</span></tt>.  Note that it doesn't enter
  473. the module into any namespace -- it only ensures it has been
  474. initialized and is stored in <tt class="docutils literal"><span class="pre">sys.modules</span></tt>.</p>
  475. <p>You can then access the module's attributes (i.e. any name defined in
  476. the module) as follows:</p>
  477. <pre class="literal-block">
  478. attr = PyObject_GetAttrString(module, "<attrname>");
  479. </pre>
  480. <p>Calling <tt class="docutils literal"><span class="pre">PyObject_SetAttrString()</span></tt> to assign to variables in the module also works.</p>
  481. </div>
  482. <div class="section">
  483. <h1><a class="toc-backref" href="#id17" id="how-do-i-interface-to-c-objects-from-python" name="how-do-i-interface-to-c-objects-from-python">11   How do I interface to C++ objects from Python?</a></h1>
  484. <p>Depending on your requirements, there are many approaches.  To do
  485. this manually, begin by reading <a class="reference" href="http://docs.python.org/ext/ext.html">the "Extending and Embedding" document</a>.  Realize
  486. that for the Python run-time system, there isn't a whole lot of
  487. difference between C and C++ -- so the strategy of building a new Python
  488. type around a C structure (pointer) type will also work for C++
  489. objects.</p>
  490. <p>For C++ libraries, you can look at <a class="reference" href="http://www.riverbankcomputing.co.uk/sip/">SIP</a>, <a class="reference" href="http://cxx.sourceforge.net/">CXX</a>, <a class="reference" href="http://www.boost.org/libs/python/doc/index.html">Boost</a>, or <a class="reference" href="http://www.scipy.org/site_content/weave">Weave</a>.
  491. <a class="reference" href="http://www.swig.org">SWIG</a> is a similar automated tool that only supports C libraries.</p>
  492. </div>
  493. <div class="section">
  494. <h1><a class="toc-backref" href="#id18" id="i-added-a-module-using-the-setup-file-and-the-make-fails-why" name="i-added-a-module-using-the-setup-file-and-the-make-fails-why">12   I added a module using the Setup file and the make fails; why?</a></h1>
  495. <p>Setup must end in a newline, if there is no newline there, the build
  496. process fails.  (Fixing this requires some ugly shell script hackery,
  497. and this bug is so minor that it doesn't seem worth the effort.)</p>
  498. </div>
  499. <div class="section">
  500. <h1><a class="toc-backref" href="#id19" id="how-do-i-debug-an-extension" name="how-do-i-debug-an-extension">13   How do I debug an extension?</a></h1>
  501. <p>When using GDB with dynamically loaded extensions, you can't set a
  502. breakpoint in your extension until your extension is loaded.</p>
  503. <p>In your <tt class="docutils literal"><span class="pre">.gdbinit</span></tt> file (or interactively), add the command:</p>
  504. <pre class="literal-block">
  505. br _PyImport_LoadDynamicModule
  506. </pre>
  507. <p>Then, when you run GDB:</p>
  508. <pre class="literal-block">
  509. $ gdb /local/bin/python
  510. gdb) run myscript.py
  511. gdb) continue # repeat until your extension is loaded
  512. gdb) finish   # so that your extension is loaded
  513. gdb) br myfunction.c:50
  514. gdb) continue
  515. </pre>
  516. </div>
  517. <div class="section">
  518. <h1><a class="toc-backref" href="#id20" id="i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why" name="i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why">14   I want to compile a Python module on my Linux system, but some files are missing. Why?</a></h1>
  519. <p>Most packaged versions of Python don't include the
  520. /usr/lib/python2.x/config/ directory, which contains various files required
  521. for compiling Python extensions.</p>
  522. <p>For Red Hat, install the python-devel RPM to get the necessary files.</p>
  523. <p>For Debian, run <tt class="docutils literal"><span class="pre">apt-get</span> <span class="pre">install</span> <span class="pre">python-dev</span></tt>.</p>
  524. </div>
  525. <div class="section">
  526. <h1><a class="toc-backref" href="#id21" id="what-does-systemerror-pyimport-fixupextension-module-yourmodule-not-loaded-mean" name="what-does-systemerror-pyimport-fixupextension-module-yourmodule-not-loaded-mean">15   What does "SystemError: _PyImport_FixupExtension: module yourmodule not loaded" mean?</a></h1>
  527. <p>This means that you have created an extension module named "yourmodule", but your module init function does not initialize with that name.</p>
  528. <p>Every module init function will have a line similar to:</p>
  529. <pre class="literal-block">
  530. module = Py_InitModule("yourmodule", yourmodule_functions);
  531. </pre>
  532. <p>If the string passed to this function is not the same name as your
  533. extenion module, the <tt class="docutils literal"><span class="pre">SystemError</span></tt> exception will be raised.</p>
  534. </div>
  535. <div class="section">
  536. <h1><a class="toc-backref" href="#id22" id="how-do-i-tell-incomplete-input-from-invalid-input" name="how-do-i-tell-incomplete-input-from-invalid-input">16   How do I tell "incomplete input" from "invalid input"?</a></h1>
  537. <p>Sometimes you want to emulate the Python interactive interpreter's
  538. behavior, where it gives you a continuation prompt when the input
  539. is incomplete (e.g. you typed the start of an "if" statement
  540. or you didn't close your parentheses or triple string quotes),
  541. but it gives you a syntax error message immediately when the input
  542. is invalid.</p>
  543. <p>In Python you can use the <tt class="docutils literal"><span class="pre">codeop</span></tt> module, which approximates the
  544. parser's behavior sufficiently.  IDLE uses this, for example.</p>
  545. <p>The easiest way to do it in C is to call <tt class="docutils literal"><span class="pre">PyRun_InteractiveLoop()</span></tt>
  546. (perhaps in a separate thread) and let the Python interpreter handle
  547. the input for you. You can also set the <tt class="docutils literal"><span class="pre">PyOS_ReadlineFunctionPointer</span></tt>
  548. to point at your custom input function. See <tt class="docutils literal"><span class="pre">Modules/readline.c</span></tt> and
  549. <tt class="docutils literal"><span class="pre">Parser/myreadline.c</span></tt> for more hints.</p>
  550. <p>However sometimes you have to run the embedded Python interpreter in
  551. the same thread as your rest application and you can't allow the
  552. <tt class="docutils literal"><span class="pre">PyRun_InteractiveLoop()</span></tt> to stop while waiting for user input.  The
  553. one solution then is to call <tt class="docutils literal"><span class="pre">PyParser_ParseString()</span></tt> and test for
  554. <tt class="docutils literal"><span class="pre">e.error</span></tt> equal to <tt class="docutils literal"><span class="pre">E_EOF</span></tt>, which means the input is incomplete).
  555. Here's a sample code fragment, untested, inspired by code from Alex Farber:</p>
  556. <pre class="literal-block">
  557. #include <Python.h>
  558. #include <node.h>
  559. #include <errcode.h>
  560. #include <grammar.h>
  561. #include <parsetok.h>
  562. #include <compile.h>
  563.  
  564. int testcomplete(char *code)
  565.   /* code should end in \n */
  566.   /* return -1 for error, 0 for incomplete, 1 for complete */
  567. {
  568.   node *n;
  569.   perrdetail e;
  570.  
  571.   n = PyParser_ParseString(code, &_PyParser_Grammar,
  572.                            Py_file_input, &e);
  573.   if (n == NULL) {
  574.     if (e.error == E_EOF)
  575.       return 0;
  576.     return -1;
  577.   }
  578.  
  579.   PyNode_Free(n);
  580.   return 1;
  581. }
  582. </pre>
  583. <p>Another solution is trying to compile the received string with
  584. <tt class="docutils literal"><span class="pre">Py_CompileString()</span></tt>. If it compiles without errors, try to execute the returned
  585. code object by calling <tt class="docutils literal"><span class="pre">PyEval_EvalCode()</span></tt>. Otherwise save the input for
  586. later. If the compilation fails, find out if it's an error or just
  587. more input is required - by extracting the message string from the
  588. exception tuple and comparing it to the string "unexpected EOF while parsing".
  589. Here is a complete example using the GNU readline library (you may
  590. want to ignore SIGINT while calling readline()):</p>
  591. <pre class="literal-block">
  592. #include <stdio.h>
  593. #include <readline.h>
  594.  
  595. #include <Python.h>
  596. #include <object.h>
  597. #include <compile.h>
  598. #include <eval.h>
  599.  
  600. int main (int argc, char* argv[])
  601. {
  602.   int i, j, done = 0;                          /* lengths of line, code */
  603.   char ps1[] = ">>> ";
  604.   char ps2[] = "... ";
  605.   char *prompt = ps1;
  606.   char *msg, *line, *code = NULL;
  607.   PyObject *src, *glb, *loc;
  608.   PyObject *exc, *val, *trb, *obj, *dum;
  609.  
  610.   Py_Initialize ();
  611.   loc = PyDict_New ();
  612.   glb = PyDict_New ();
  613.   PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ());
  614.  
  615.   while (!done)
  616.   {
  617.     line = readline (prompt);
  618.  
  619.     if (NULL == line)                          /* CTRL-D pressed */
  620.     {
  621.       done = 1;
  622.     }
  623.     else
  624.     {
  625.       i = strlen (line);
  626.  
  627.       if (i > 0)
  628.         add_history (line);                    /* save non-empty lines */
  629.  
  630.       if (NULL == code)                        /* nothing in code yet */
  631.         j = 0;
  632.       else
  633.         j = strlen (code);
  634.  
  635.       code = realloc (code, i + j + 2);
  636.       if (NULL == code)                        /* out of memory */
  637.         exit (1);
  638.  
  639.       if (0 == j)                              /* code was empty, so */
  640.         code[0] = '\0';                        /* keep strncat happy */
  641.  
  642.       strncat (code, line, i);                 /* append line to code */
  643.       code[i + j] = '\n';                      /* append '\n' to code */
  644.       code[i + j + 1] = '\0';
  645.  
  646.       src = Py_CompileString (code, "<stdin>", Py_single_input);
  647.  
  648.       if (NULL != src)                         /* compiled just fine - */
  649.       {
  650.         if (ps1  == prompt ||                  /* ">>> " or */
  651.             '\n' == code[i + j - 1])           /* "... " and double '\n' */
  652.         {                                               /* so execute it */
  653.           dum = PyEval_EvalCode ((PyCodeObject *)src, glb, loc);
  654.           Py_XDECREF (dum);
  655.           Py_XDECREF (src);
  656.           free (code);
  657.           code = NULL;
  658.           if (PyErr_Occurred ())
  659.             PyErr_Print ();
  660.           prompt = ps1;
  661.         }
  662.       }                                        /* syntax error or E_EOF? */
  663.       else if (PyErr_ExceptionMatches (PyExc_SyntaxError))
  664.       {
  665.         PyErr_Fetch (&exc, &val, &trb);        /* clears exception! */
  666.  
  667.         if (PyArg_ParseTuple (val, "sO", &msg, &obj) &&
  668.             !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */
  669.         {
  670.           Py_XDECREF (exc);
  671.           Py_XDECREF (val);
  672.           Py_XDECREF (trb);
  673.           prompt = ps2;
  674.         }
  675.         else                                   /* some other syntax error */
  676.         {
  677.           PyErr_Restore (exc, val, trb);
  678.           PyErr_Print ();
  679.           free (code);
  680.           code = NULL;
  681.           prompt = ps1;
  682.         }
  683.       }
  684.       else                                     /* some non-syntax error */
  685.       {
  686.         PyErr_Print ();
  687.         free (code);
  688.         code = NULL;
  689.         prompt = ps1;
  690.       }
  691.  
  692.       free (line);
  693.     }
  694.   }
  695.  
  696.   Py_XDECREF(glb);
  697.   Py_XDECREF(loc);
  698.   Py_Finalize();
  699.   exit(0);
  700. }
  701. </pre>
  702. </div>
  703. <div class="section">
  704. <h1><a class="toc-backref" href="#id23" id="how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual" name="how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual">17   How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a></h1>
  705. <p>To dynamically load g++ extension modules, you must recompile Python, relink it using g++ (change LINKCC in the python Modules Makefile), and link your extension module using g++ (e.g., "g++ -shared -o mymodule.so mymodule.o").</p>
  706. </div>
  707. <div class="section">
  708. <h1><a class="toc-backref" href="#id24" id="can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance" name="can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance">18   Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a></h1>
  709. <p>In Python 2.2, you can inherit from builtin classes such as int, list, dict, etc.</p>
  710. <p>The Boost Python Library (BPL, <a class="reference" href="http://www.boost.org/libs/python/doc/index.html">http://www.boost.org/libs/python/doc/index.html</a>)
  711. provides a way of doing this from C++ (i.e. you can inherit from an
  712. extension class written in C++ using the BPL).</p>
  713. </div>
  714. <div class="section">
  715. <h1><a class="toc-backref" href="#id25" id="when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2" name="when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2">19   When importing module X, why do I get "undefined symbol: PyUnicodeUCS2*"?</a></h1>
  716. <p>You are using a version of Python that uses a 4-byte representation
  717. for Unicode characters, but some C extension module you are importing
  718. was compiled using a Python that uses a 2-byte representation for
  719. Unicode characters (the default).</p>
  720. <p>If instead the name of the undefined symbol starts with
  721. <tt class="docutils literal"><span class="pre">PyUnicodeUCS4</span></tt>, the problem is the reverse: Python was built using
  722. 2-byte Unicode characters, and the extension module was compiled using
  723. a Python with 4-byte Unicode characters.</p>
  724. <p>This can easily occur when using pre-built extension packages.  RedHat
  725. Linux 7.x, in particular, provided a "python2" binary that is compiled
  726. with 4-byte Unicode.  This only causes the link failure if the extension
  727. uses any of the <tt class="docutils literal"><span class="pre">PyUnicode_*()</span></tt> functions.  It is also a problem if an
  728. extension uses any of the Unicode-related format specifiers for
  729. <tt class="docutils literal"><span class="pre">Py_BuildValue</span></tt> (or similar) or parameter specifications for
  730. <tt class="docutils literal"><span class="pre">PyArg_ParseTuple()</span></tt>.</p>
  731. <p>You can check the size of the Unicode character a Python interpreter is
  732. using by checking the value of sys.maxunicode:</p>
  733. <pre class="literal-block">
  734. >>> import sys
  735. >>> if sys.maxunicode > 65535:
  736. ...     print 'UCS4 build'
  737. ... else:
  738. ...     print 'UCS2 build'
  739. </pre>
  740. <p>The only way to solve this problem is to use extension modules compiled
  741. with a Python binary built using the same size for Unicode characters.</p>
  742. </div>
  743. </div>
  744. </body>
  745. </html>
  746.