[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

running a string expression and assigning a global variable (X) within the module’s
namespace to serve as input for a Python print statement string.


Because the string execution call in this version lets you specify namespaces, you can
better partition the embedded code your system runs—each grouping can have a dis-
tinct namespace to avoid overwriting other groups’ variables. And because this call
returns a result, you can better communicate with the embedded code; expression
results are outputs, and assignments to globals in the namespace in which code runs
can serve as inputs.


Before we move on, I need to explain three coding issues here. First, this program also
decrements the reference count on objects passed to it from Python, using the
Py_DECREF call described in Python’s C API manuals. These calls are not strictly needed
here (the objects’ space is reclaimed when the programs exits anyhow), but they dem-
onstrate how embedding interfaces must manage reference counts when Python passes
object ownership to C. If this was a function called from a larger system, for instance,
you would generally want to decrement the count to allow Python to reclaim the
objects.


Second, in a realistic program, you should generally test the return values of all the API
calls in this program immediately to detect errors (e.g., import failure). Error tests are
omitted in this section’s example to keep the code simple, but they should be included
in your programs to make them more robust.


And third, there is a related function that lets you run entire files of code, but it is not
demonstrated in this chapter: PyRun_File. Because you can always load a file’s text and
run it as a single code string with PyRun_String, the PyRun_File call’s main advantage
is to avoid allocating memory for file content. In such multiline code strings, the \n
character terminates lines and indentation group blocks as usual.


Calling Python Objects


The last two sections dealt with running strings of code, but it’s easy for C programs
to deal in terms of Python objects, too. Example 20-27 accomplishes the same task as
Examples 20-23 and 20-26, but it uses other API tools to interact with objects in the
Python module directly:


PyImport_ImportModule
Imports the module from C as before


PyObject_GetAttrString
Fetches an object’s attribute value by name


PyEval_CallObject
Calls a Python function (or class or method)


PyArg_Parse
Converts Python objects to C values


1524 | Chapter 20: Python/C Integration

Free download pdf