Is it possible to execute Python code from C++ without writing to a file?

Chris Angelico rosuav at gmail.com
Fri Apr 15 20:32:55 EDT 2011


On Sat, Apr 16, 2011 at 9:46 AM, Roger House <rhouse at sonic.net> wrote:
> I'm a Python newbie who's been given a task requiring calls of Python code
> from a C++ program.  I've tried various tutorials and dug into The Python/C
> API doc and the Extending and Embedding Python doc, but I haven't been able
> to answer this question:
>
>    Is it possible in a C++ program to generate Python code, execute
>    it, and get output back (say a tuple of 10 or so items) without
>    doing any file i/o?
>
> Clearly it works to write the generated Python to a file and then use
> PyImport_Import and PyObject_CallObject to call a function returning the
> output tuple.  But it seems like it should be possible to do this without
> writing the Python code to a file.  I tried PyRun_String, but I can't see
> how it
> can be used to return a tuple (the Py_file_input option always returns
> None).

What I do for this is have the Python code place its return value into
a particular location. If you're using file input, I think it's
restricted to returning an integer; but you can do something like
this:

const char *python_code="result=('hello','world',42)";
PyObject *globals=... (use same as locals if you don't need globals)

PyObject *locals=PyDict_New();
Py_XDECREF(PyRun_StringFlags(python_code,Py_file_input,globals,locals,0);
PyObject *returned_tuple=PyDict_GetItemString(locals,"result");
Py_DECREF(locals);

You now own a reference to whatever the Python code put into its
variable "result", in the C variable returned_tuple. Of course, it
might not be a tuple at all, and it might not even be present (in
which case returned_tuple will be NULL). This is a fairly effective
way for Python to return hefty amounts of data to C.

Don't forget to decref the return value.

Hope that helps!

Chris Angelico



More information about the Python-list mailing list