Iterating generator from C

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sven Suursoho

    #1

    Iterating generator from C

    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...0&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_CompileStrin g("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(it em));
    Py_DECREF(item) ;
    }

    Py_DECREF(gen);
    Py_DECREF(code) ;
    Py_DECREF(globa ls);

    Py_Finalize();
    return 0;
    }


    Br,
    --
    Sven Suursoho
Working...