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

R

Roger House

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).

Any help will be greatly appreciated.

Roger House
Software Developer
 
A

Anssi Saari

Roger House said:
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).

There's an example of this at
http://stackoverflow.com/questions/3789881/create-and-call-python-function-from-string-via-c-api

The comments say this took quite a lot of investigation. I believe it
too, since it doesn't exactly leap out from the documentation... The
example returns only a single fixed integer, but changing it to return
a tuple shouldn't be a problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top