Iterating generator from C

Sven Suursoho sven at spam.pri.ee
Sat May 13 17:10:25 EDT 2006


Hi,


I am working on project that has embedded python interpreter to run  
user-specified python procedures. Those procedures might return any  
iterable object with set of result data -- basically everything for which  
iter() returns valid object (list, tuple, dict, iterator etc)

It works ok, except generator under Python 2.4 with debugging enabled (see  
http://sourceforge.net/tracker/index.php?func=detail&aid=1483133&group_id=5470&atid=105470).

Is there any way to rewrite following program to handle returned generator  
without hitting this bug?
Error handling is omitted for clarity.

#include <Python.h>

const char *py_source =
     "def fn():\n"
     "   yield 1\n";

int main ()
{
   Py_Initialize();

   PyObject *globals = PyDict_New();

   // insert function code into interpreter
   PyObject *code = PyRun_String(py_source, Py_file_input, globals, NULL);
   Py_DECREF(code);

   // do call
   code = Py_CompileString("fn()", "<string>", Py_eval_input);
   PyObject *gen = PyEval_EvalCode((PyCodeObject *)code, globals, NULL);

   // iterate result
   PyObject *item;
   while ((item = PyIter_Next(gen))) {
       printf("> %ld\n", PyInt_AsLong(item));
       Py_DECREF(item);
   }

   Py_DECREF(gen);
   Py_DECREF(code);
   Py_DECREF(globals);

   Py_Finalize();
   return 0;
}


Br,
-- 
Sven Suursoho



More information about the Python-list mailing list