[C++-sig] C integration question - how to get the result of an evaluation with PyEval_EvalCode()

Dietrich Bollmann d.bollmann at tu-berlin.de
Wed Jun 21 07:52:23 CEST 2006

Hi, I am working on a "python command port" for an application (blender) 
written in C and using python as scripting language. The idea is to let 
other applications interact with blender via a socket using blender 
python scripts / commands.

I got everything work - but couldn't figure out how to get the result of 
the evaluation for sending it back over the socket to the client.

I am using the following commands:

   /* compile python script / command */
   script_compiled = Py_CompileString(script, "<bcp>", Py_file_input);
   /* evaluate compiled python script / command */
   PyObject *result_obj;
   result_obj = PyEval_EvalCode(script_compiled, dict, dict);

By "result" I am thinking about something like the messages printed by 
the python shell as response when executing a command - if possible as 
string. There are some differences to the python interactive loop though:
- `script' might be one command string like `a = 123\n' or a whole 
script like `def blah(a, b):\n  c = a + b\n  print c\n\nblah(3, 4)\n\n'
- there might be empty lines inside of function or class definitions as 
the script is entered as one C string and not line by line
- I am only interested in the result of the last command (like `7' in 
the case of the second example)

A second wish would be to have something like a `get_value()' function 
which would return the value of some variable as result - like just 
entering the name of a variable in the python shell or using a print 
command like `print variable' from the shell. (In general I would like 
to let `print' print to the blender stdout though.)

Any idea?

Thanks for your help & best wishes, Dietrich

By the way, when experimenting with "results" I also tried the following 
snipped (an adapted version from the book "Programming Python" by Mark 

void experiment() {
   int cval;
   PyObject *pdict, *pval;

   /* make a new namespace */
   pdict = PyDict_New();
   PyDict_SetItemString(pdict, "__builtins__", PyEval_GetBuiltins());

   PyDict_SetItemString(pdict, "Y", PyInt_FromLong(2));   /* dict['Y'] = 
2   */
   PyRun_String("X = 99",  Py_file_input, pdict, pdict);  /* run 
statements  */
   PyRun_String("X = X+Y", Py_file_input, pdict, pdict);  /* same X and 
Y    */
   pval = PyDict_GetItemString(pdict, "X");               /* fetch 
dict['X'] */

   PyArg_Parse(pval, "i", &cval);                         /* convert to C */
   printf("result: %d\n", cval);                          /* result=101 */

But for some reason got the following when executing it:

   result: -1074019336

What have I done wrong?

Dietrich Bollmann

More information about the Cplusplus-sig mailing list