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

(yzsuai) #1

to a Python variable name. As a result, it’s probably more similar to the Python
import built-in function.


The PyRun_String call is the one that actually runs code here, though. It takes a code
string, a parser mode flag, and dictionary object pointers to serve as the global and local
namespaces for running the code string. The mode flag can be Py_eval_input to run an
expression or Py_file_input to run a statement; when running an expression, the result
of evaluating the expression is returned from this call (it comes back as a PyObject*
object pointer). The two namespace dictionary pointer arguments allow you to distin-
guish global and local scopes, but they are typically passed the same dictionary such
that code runs in a single namespace.


Example 20-26. PP4E\Integrate\Embed\Basics\embed-string.c


/ code-strings with results and namespaces /


#include <Python.h>


main() {
char cstr;
PyObject
pstr, pmod, pdict;
printf("embed-string\n");
Py_Initialize();


/ get usermod.message /
pmod = PyImport_ImportModule("usermod");
pdict = PyModule_GetDict(pmod);
pstr = PyRun_String("message", Py_eval_input, pdict, pdict);


/ convert to C /
PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);


/ assign usermod.X /
PyObject_SetAttrString(pmod, "X", pstr);


/ print usermod.transform(X) /
(void) PyRun_String("print(transform(X))", Py_file_input, pdict, pdict);
Py_DECREF(pmod);
Py_DECREF(pstr);
Py_Finalize();
}


When compiled and run, this file produces the same result as its predecessor:


.../PP4E/Integrate/Embed/Basics$ ./embed-string
embed-string
The meaning of life...
THE MEANING OF PYTHON...

However, very different work goes into producing this output. This time, C fetches,
converts, and prints the value of the Python module’s message attribute directly by


Basic Embedding Techniques | 1523
Free download pdf