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

(yzsuai) #1

/ make new namespace dictionary /
pdict = PyDict_New();
if (pdict == NULL) return −1;
PyDict_SetItemString(pdict, "builtins", PyEval_GetBuiltins());


/ precompile strings of code to bytecode objects /
pcode1 = Py_CompileString(codestr1, "", Py_file_input);
pcode2 = Py_CompileString(codestr2, "", Py_eval_input);
pcode3 = Py_CompileString(codestr3, "", Py_file_input);


/ run compiled bytecode in namespace dict /
if (pcode1 && pcode2 && pcode3) {
(void) PyEval_EvalCode((PyCodeObject )pcode1, pdict, pdict);
presult = PyEval_EvalCode((PyCodeObject
)pcode2, pdict, pdict);
PyArg_Parse(presult, "s", &cval);
printf("%s\n", cval);
Py_DECREF(presult);


/ rerun code object repeatedly /
for (i = 0; i <= 10; i++) {
PyDict_SetItemString(pdict, "X", PyLong_FromLong(i));
(void) PyEval_EvalCode((PyCodeObject )pcode3, pdict, pdict);
}
printf("\n");
}
/
free referenced objects */
Py_XDECREF(pdict);
Py_XDECREF(pcode1);
Py_XDECREF(pcode2);
Py_XDECREF(pcode3);
Py_Finalize();
}


This program combines a variety of techniques that we’ve already seen. The namespace
in which the compiled code strings run, for instance, is a newly created dictionary (not
an existing module object), and inputs for code strings are passed as preset variables
in the namespace. When built and executed, the first part of the output is similar to
previous examples in this section, but the last line represents running the same pre-
compiled code string 11 times:


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

0:0 1:1 2:4 3:9 4:16 5:25 6:36 7:49 8:64 9:81 10:100

If your system executes Python code strings multiple times, it is a major speedup to
precompile to bytecode in this fashion. This step is not required in other contexts that
invoke callable Python objects—including the common embedding use case presented
in the next section.


Basic Embedding Techniques | 1529
Free download pdf