simple? embedding question
no at spam.com
Tue Oct 30 20:26:05 CET 2007
sndive at gmail.com wrote:
> suppose i have imported two modules foo and bar with
> foo=PyImport_ImportModule("foo") and bar=PyImport_ImportModule("bar")
> Now suppose I have an artitrary python expression to evaluate.
> Do I need to parse that thring and check for foo. and bar. before
> jumping the usual
> PyModule_GetDict,PyDict_GetItemString,PyObject_CallObject hoop hoop on
> the PyObject for
> the prefix or there is a better way?
> btw PyRun_SimpleString("foo.baz()"); does not work:
> Traceback (most recent call last):
> File "<string>", line 1, in ?
> NameError: name 'foo' is not defined
> and i potentially need a PyObject* back with the result of the
> expression anyway.
I believe the problem is that you are not importing the "foo" and "bar"
modules into the __main__ scope. Try using PyImport_ImportModuleEx,
which will allow you to specify the global scope to import the module
into. For example, to import the modules into the __main__ scope you
could do the following:
PyObject* mainmod = PyImport_AddModule("__main__");
PyObject* maindict = PyModule_GetDict(mainmod);
foo = PyImport_ImportModuleEx("foo", maindict , maindict , NULL);
bar = PyImport_ImportModuleEx("bar", maindict , maindict , NULL);
Once the modules are imported into the __main__ scope, you should be
able to use PyRun_SimpleString() to evaluate expressions.
More information about the Python-list