PyImport_ImportModule, PyModule_GetDict
Michael P. Reilly
arcege at shore.net
Thu Jul 8 13:37:17 EDT 1999
Randy Heiland <heiland at ncsa.uiuc.edu> wrote:
: If I understand this correctly, the equivalent of doing this:
:>>> import mymodule
:>>> dir(mymodule)
: is sort of this, in the C API:
: PyObject *mod = PyImport_ImportModule("mymodule");
: PyObject *myDict = PyModule_GetDict(mod);
: Q: what is the C API equivalent of this:
:>>> from mymodule import *
:>>> dir()
You will have to do something a little more:
PyObject *fromlist, *main, *globals;
PyObject *sysmod, *sysdict, *key, *val;
int pos; /* used internally by PyDict_Next() */
/* tell __import__ to return the top-level module */
fromlist = Py_BuildValue("[s]", "*");
main = PyImport_ImportModule("__main__");
globals = PyModule_GetDict(main);
/* ImportModuleEx handles "from package.module import *" as well */
sysmod = PyImport_ImportModuleEx("sys", globals, globals, fromlist);
sysdict = PyModule_GetDict(sysmod);
/* perform standard name bindings */
while (PyDict_Next(sysdict, &pos, &key, &val) > 0) {
if (!PyString_Check(key) ||
(PyString_AS_STRING(key)[0] != '_'))
PyDict_SetItem(globals, key, val);
}
If you look at the documentation for __import__, it does not perform the
name binding in the globals dictionary (for some reason ;), so that must
be performed manually.
-Arcege
More information about the Python-list
mailing list