Iterating generator from C

S

Sven Suursoho

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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top