Problem with C-API

Fredrik Lundh fredrik at
Sat Mar 18 09:46:18 CET 2006

John Dean wrote:

> Duncan's example worked to a point. The line PyRun_String( "print x",
> Py_file_input, dict, dict); print out the contents of x, but I don't want to
> print x out. I want to be able to grab whateven the variable x contains so
> that I can pass it on for further processing by the C++ application.

a better approach is to combine embedding and extending, and let the em-
bedded code use your extension to talk to your program.

if you want your program to access x, let the embedded script do

    import myapp

since you know how to extend Python, implementing write should be trivial.

if you insist on picking out variables from the embedded script, you can use
the same approach as when you want to pull out variables from code you've
exec'ed: run the code in a namespace dictionary, and extract the data from
the dictionary after you've run the code.  i.e.

    g = {}
    exec code in g
    x = g["x"]


    PyObject *g, *x;
    g = PyDict_New();
    PyDict_SetItemString(g, "__builtins__", PyEval_GetBuiltins());
    PyRun_String(mycode, Py_file_input, g, NULL);
    x = PyDict_GetItemString(g, "x");

(the SetItemString call is probably not needed in all cases)

> BTW this is only a test case. The real scripts are much bigger. I must say
> the documentation is not of much help and there are no books or articles
> covering embedding Python in any detail. What there is is very much out of
> date.

well, I'm getting a bit tired of all this "if it's not published within the last
few weeks, it's out of date" nonsense that people keep using as an excuse
for procrastination.  The Python C API is very stable, and the embedding
and extending basics haven't changed a bit in a decade.

and "no books" is also wrong; ORA's "Programming Python" spends some
40 pages on embedding only (including examples on how to extract stuff
from module namespaces).  I'm pretty sure it's not the only one.


More information about the Python-list mailing list