Getting output from embedded python program

Rick L. Ratzel rick.ratzel at scd.magma-da.com
Wed May 19 15:20:29 EDT 2004


  I'm not sure, but I think your problem is related to the globals and 
locals args to PyRun_String().  If you're trying to use PyRun_String to 
evaluate within the scope of your module, you need to provide the 
globals dictionary (as returned by PyEval_GetGlobals() or similar) and 
the locals dictionary (the dictionary of the module itself), as well as 
the start token (like Py_eval_input as defined in Python.h).  Also, if 
you're getting NULL back (which means an exception was raised), you 
might want to check for the exception value which could give you more 
clues as to what went wrong...PyErr_Print() will print the traceback to 
stderr.

Kim wrote:
> Hi Rich, 
> You post is extremely useful. However when I tried to run the
> expression in My Module's context, instead of __main__ module. It
> always retunns NULL. How can I do that? I tried PyRun_String().. but
> didn't work. i don't really understand global and local arguments in
> PyRun_String(), token is set to 0?
> 
> THanks very much !
> Kim
> 
> 
>>...
>>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