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

(yzsuai) #1
C API call Python equivalent
PyObject_GetAttrString getattr(obj, attr)
PyObject_SetAttrString setattr(obj, attr, val)
PyObject_CallObject funcobj(*argstuple)
PyEval_CallObject funcobj(*argstuple)
PyRun_String eval(exprstr), exec(stmtstr)
PyRun_File exec(open(filename().read())

Because embedding relies on API call selection, becoming familiar with the Python C
API is fundamental to the embedding task. This chapter presents a handful of repre-
sentative embedding examples and discusses common API calls, but it does not provide
a comprehensive list of all tools in the API. Once you’ve mastered the examples here,
you’ll probably need to consult Python’s integration manuals for more details on avail-
able calls in this domain. As mentioned previously, Python offers two standard manuals
for C/C++ integration programmers: Extending and Embedding, an integration tutorial;
and Python/C API, the Python runtime library reference.


You can find the most recent releases of these manuals at http://www.python.org, and
possibly installed on your computer alongside Python itself. Beyond this chapter, these
manuals are likely to be your best resource for up-to-date and complete Python API
tool information.


What Is Embedded Code?


Before we jump into details, let’s get a handle on some of the core ideas in the embed-
ding domain. When this book speaks of “embedded” Python code, it simply means
any Python program structure that can be executed from C with a direct in-process
function call interface. Generally speaking, embedded Python code can take a variety
of forms:


Code strings
C programs can represent Python programs as character strings and run them as
either expressions or statements (much like using the eval and exec built-in func-
tions in Python).


Callable objects
C programs can load or reference Python callable objects such as functions, meth-
ods, and classes, and call them with argument list objects (much like func(pargs,
kargs) Python syntax).


Code files
C programs can execute entire Python program files by importing modules and
running script files through the API or general system calls (e.g., popen).


1516 | Chapter 20: Python/C Integration

Free download pdf