Getting output from embedded python program

Rick L. Ratzel rick.ratzel at magma-da.com
Tue Apr 20 01:27:41 EDT 2004


Kim wrote:
> Hi everyone,
> I'm writing a embeded python program, and I want to evaluate some
> expression by calling function:
> 
> PyRun_SimpleString("print 'hello'")
> 
> I don't want to output it to stdout but putting it into string somehow
> sothat I can process it.
> 

    Here is a way to get the result of a Python expression eval from C 
(derived from example at 
http://elmer.sourceforge.net/PyCon04/elmer_pycon04.html ) ...obviously, 
if you evaluate a print statement, you will still get output on stdout 
though:

...
PyObject* evalModule;
PyObject* evalDict;
PyObject* evalVal;
char* retString;

PyRun_SimpleString( "result = 'foo' + 'bar'" )

evalModule = PyImport_AddModule( (char*)"__main__" );
evalDict = PyModule_GetDict( evalModule );
evalVal = PyDict_GetItemString( evalDict, "result" );

if( evalVal == NULL ) {
     PyErr_Print();
     exit( 1 );

} else {
     /*
      * PyString_AsString returns char* repr of PyObject, which should
      * not be modified in any way...this should probably be copied for
      * safety
      */
     retString = PyString_AsString( evalVal );
}
...

    In this case, you need to know that the expression will evaluate to 
a string result in order to call PyString_AsString().  If you don't know 
this, you will have to check the type of the PyObject first.






More information about the Python-list mailing list