exec a string in an embedded environment

Graham Fawcett graham.fawcett at gmail.com
Wed Jan 11 18:54:21 CET 2006


Tommy R wrote:
> I need some way to execute a string and pass arguments to the functions
> inside the string. We have discussed a solution where we first load the
> string (containing some funcs) and then run something similar to
> Py_RunString("foo(1.0, 'str')");  We need to do this in a generic way
> so we can send in arbitrary arguments.

You could use

    foo_ptr = Py_RunString("foo", Py_eval_input, globals_ptr,
locals_ptr)

to get a reference to the foo function, and then use

    result_ptr = PyObject_Call(foo_ptr, args_ptr, kwargs_ptr)

to call it with arbitrary arguments and keyword arguments. Of course,
you're responsible for setting up the globals and locals, as well as
the args list and kwargs dictionary objects.

The PyObject_Call signature, from <abstract.h>, is:

     PyAPI_FUNC(PyObject *) PyObject_Call(PyObject *callable_object,
					 PyObject *args, PyObject *kw);

Does this help?

Graham




More information about the Python-list mailing list