How can I run precompiled code objects?

Alex Martelli aleaxit at yahoo.com
Fri Jul 13 13:20:57 CEST 2001


"Vesselin Peev" <vesselinpeev at hotmail.com> wrote in message
news:mailman.995002401.30502.python-list at python.org...
> Hello,
>
> Can anyone tell me how to use the so called "code objects" in Python, for
> example the ones created via
>
> PyObject* Py_CompileString(char *str, char *filename, int start)
>
> There's no explanation on the matter that I can find.

In Python, you can pass a code object to the exec statement
or to the eval built-in function,


> All I want to do is to execute different precompiled python code blocks
from
> a C program (I have already embedded Python). I could make do without
> bytecode but then the speed would be much les.

A "code block" is not suitable for eval(), so exec it will
have to be, if you're working in Python as you said at the
start.  If you're working in C as you say now, the C API
function you have to call is PyEval_EvalCode.  It takes 3
arguments -- a code object, then two dictionaries to use as
local and global namespaces -- the last arg can be 0, but
not the 2nd one.


So anyway, a typical usage pattern might be:


    PyObject *globals, *code, *result;

    /* prepare an innocuous 'globals' dictionary */
    globals = PyDict_New();
    PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());

    /* compile your string of statements into a code object */
    code = Py_CompileString(statements, "<stmts>", Py_file_input);
    if(!code) {
        PyErr_Print();
        return 0;
    }

    /* execute the compiled statement */
    result = PyEval_EvalCode((PyCodeObject *)code, globals, 0);
    Py_DECREF(code);
    if(!result) {
        PyErr_Print();
        return 0;
    } else {
        Py_DECREF(result);
        return 1;
    }


Season to taste if, as it seems, you may want to keep the code
objects around, reuse a globals dictionary, etc, etc.


Alex






More information about the Python-list mailing list