Most of this output is produced by Python print statements sent from C to the linked-
in Python library. It’s as if C has become an interactive Python programmer.
Naturally, strings of Python code run by C probably would not be hardcoded in a C
program file like this. They might instead be loaded from a text file or GUI, extracted
from HTML or XML files, fetched from a persistent database or socket, and so on.
With such external sources, the Python code strings that are run from C could be
changed arbitrarily without having to recompile the C program that runs them. They
may even be changed on site, and by end users of a system. To make the most of code
strings, though, we need to move on to more flexible API tools.
Pragmatic details: Under Python 3.1 and Cygwin on Windows, I had to
first set my PYTHONPATH to include the current directory in order to run
the embedding examples, with the shell command export PYTHON
PATH=.. I also had to use the shell command ./embed-simple to execute
the program because. was also not on my system path setting and isn’t
initially when you install Cygwin.
Your mileage may vary; but if you have trouble, try running the embed-
ded Python commands import sys and print sys.path from C to see
what Python’s path looks like, and take a look at the Python/C API
manual for more on path configuration for embedded applications.
Running Code Strings with Results and Namespaces
Example 20-26 uses the following API calls to run code strings that return expression
results back to C:
Py_Initialize
Initializes linked-in Python libraries as before
PyImport_ImportModule
Imports a Python module and returns a pointer to it
PyModule_GetDict
Fetches a module’s attribute dictionary object
PyRun_String
Runs a string of code in explicit namespaces
PyObject_SetAttrString
Assigns an object attribute by namestring
PyArg_Parse
Converts a Python return value object to C form
The import calls are used to fetch the namespace of the usermod module listed in Ex-
ample 20-22 so that code strings can be run there directly and will have access to names
defined in that module without qualifications. Py_Import_ImportModule is like a Python
import statement, but the imported module object is returned to C; it is not assigned
1522 | Chapter 20: Python/C Integration