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

(yzsuai) #1

Running Simple Code Strings


Perhaps the simplest way to run Python code from C is by calling the PyRun_Simple
String API function. With it, C programs can execute Python programs represented as
C character string arrays. This call is also very limited: all code runs in the same name-
space (the module main), the code strings must be Python statements (not expres-
sions), and there is no direct way to communicate inputs or outputs with the Python
code run.


Still, it’s a simple place to start. Moreover, when augmented with an imported C ex-
tension module that the embedded Python code can use to communicate with the
enclosing C layer, this technique can satisfy many embedding goals. To demonstrate
the basics, the C program in Example 20-23 runs Python code to accomplish the same
results as the Python interactive session listed in the prior section.


Example 20-23. PP4E\Integrate\Embed\Basics\embed-simple.c


/***



  • simple code strings: C acts like the interactive

  • prompt, code runs in main, no output sent to C;
    ***/


#include <Python.h> / standard API def /


main() {
printf("embed-simple\n");
Py_Initialize();
PyRun_SimpleString("import usermod"); / load .py file /
PyRun_SimpleString("print(usermod.message)"); / on Python path /
PyRun_SimpleString("x = usermod.message"); / compile and run /
PyRun_SimpleString("print(usermod.transform(x))");
Py_Finalize();
}


The first thing you should notice here is that when Python is embedded, C programs
always call Py_Initialize to initialize linked-in Python libraries before using any other
API functions and normally call Py_Finalize to shut the interpreter down.


The rest of this code is straightforward—C submits hardcoded strings to Python that
are roughly what we typed interactively. In fact, we could concatenate all the Python
code strings here with \n characters between, and submit it once as a single string.
Internally, PyRun_SimpleString invokes the Python compiler and interpreter to run the
strings sent from C; as usual, the Python compiler is always available in systems that
contain Python.


Compiling and running


To build a standalone executable from this C source file, you need to link its compiled
form with the Python library file. In this chapter, “library” usually means the binary


Basic Embedding Techniques | 1519
Free download pdf