simple? embedding question

sndive at gmail.com sndive at gmail.com
Wed Oct 31 01:04:45 CET 2007


On Oct 30, 1:26 pm, Farshid Lashkari <n... at spam.com> wrote:
> snd... at gmail.com wrote:
> > suppose i have imported two modules foo and bar with
> > foo=PyImport_ImportModule("foo") and bar=PyImport_ImportModule("bar")
> > respectively.
>
> > 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.
>
> -Farshid

i switched to PyImport_ImportModuleEx per your suggestion but i still
get

Traceback (most recent call last):
  File "<string>", line 1, in ?
NameError: name '__main__' is not defined

i tried PyRun_SimpleString("__main__.foo.baz()"); :
Traceback (most recent call last):
  File "<string>", line 1, in ?
NameError: name '__main__' is not defined

i do not have if __name__ == '__main__':
statement anywhere in the module i'm importing,
but nevertheless i checked that PyImport_AddModule("__main__");
and subsequent getdict return non null pointers.
does non null dictionary indicate that PyImport_AddModule
succeeded as opposed to creating an empty module object?





More information about the Python-list mailing list