embedding python in C++

Alex Martelli aleaxit at yahoo.com
Sun Jan 7 10:55:01 EST 2001


"Syver Enstad" <syver at NOSPAMcyberwatcher.com> wrote in message
news:934r1a$pda$1 at troll.powertech.no...
> I am total newbie to embedding Python in C++ (except with COM). What's the
> most straightforward way of executing a python file from C++ and grabbing
> the output in a string?

Should be no different than in C (as long as your C++ compiler is compatible
with the C one used to build Python on the platform in question), except
that
you can use handy C++ extras such as declaring variables 'just-in-time' when
you know what you want to initialize them with.

For "grabbing the output", I assume you mean getting characters that the
script is emitting to standard-output.  For that, it's somewhat simpler to
do
the 'output capture' in Python, with a StringIO object, then call its
getvalue
method to get the contents as a string.

Omitting the obvious needs for freeing/finalization of various stuff, and
error
checking, it could be something like (with a #include "Python.h" up at the
start
of the source file, of course!):

    Py_Initialize();
    char capture_stdout[] =
"import sys, StringIO\n\
sys.stdout=sys._capture=StringIO.StringIO()\n";
    int rc = PyRun_SimpleString(capture_stdout);
    FILE* f = fopen("foo.py", "r");
    rc = PyRun_SimpleFile(f, "foo.py");
    PyObject* sysmod = PyImport_ImportModule("sys");
    PyObject* capobj = PyObject_GetAttrString(sysmod,"_capture");
    PyObject* strres = PyObject_CallMethod(capobj,"getvalue",0);
    char* cres = PyString_AsString(strres);

Now, if everything went well (one _should_ check at each step!-), you
have in the null-terminated C-string 'cres' all that foo.py code wrote to
its "standard-output" (with print or otherwise).  A "more straightforward"
way to do it than with these 7 Py* calls doesn't come to mind...


Alex






More information about the Python-list mailing list