embedding python - PyImport_ImportModule returns null

Alex Martelli aleax at aleax.it
Thu Mar 6 22:51:54 CET 2003


On Thursday 06 March 2003 08:44 pm, Bjorn Pettersen wrote:
   ...
> Perhaps you would know how to import a module so that it can be used in
> PyRun_String()? I've tried PyImpor_Import, PyImport_ImportModule, and
> PyImport_ImportModuleEx which all imported the module but didn't make it
> visible.

They give you the module object; if you want any object, including that
module you just imported, to be available under a name X in some
other module such as __main__, you set-attribute accordingly to bind
the name to the object.  E.g. in the following snippet:

> void main() {
>     Py_Initialize();
>     PySys_SetPath(Py_GetPath());
>
>
>     PyObject* mainmod = PyImport_AddModule("__main__");
>     Py_INCREF(mainmod);
>     PyObject* ns = PyModule_GetDict(mainmod);
>     Py_INCREF(ns);
>
>     PyObject* timeModule = PyImport_ImportModuleEx("time", ns, ns,
> NULL);
>     if (!timeModule) std::cout << getTraceback() << std::endl;
>     std::cout << "time module imported successfully" << std::endl;

you have the object timeModule and you want it to be visible in
module object mainmod under the name 'time', i.e., in dictionary
ns at key 'time'.  So you can for example:

       PyModule_AddObject(mainmod, "time", timeModule);

careful -- this steals a reference to timeModule, so incref it now
if you need it to stick around, or else just omit decref'ing it later.

Apart from this, the following code:


>     PyObject* timeFn = PyRun_String("time.time", Py_eval_input, ns, ns);
>
>     if (!timeFn) std::cout << getTraceback() << std::endl;
>
>     Py_XDECREF(timeModule);
>     Py_XDECREF(timeFn);
>     Py_DECREF(ns);
>     Py_DECREF(mainmod);
>     Py_Finalize();
> }

should now work.

Python statement import does implicit binding -- you can see

    import time

as equivalent to

    time = __import__('time')

and at the C-API level you must use this more detailed approach -- it's
not QUITE as high-level as the Python statement 'import'!-)


Alex






More information about the Python-list mailing list