PyImport_Import vs import
I tried to replace
PyRun_SimpleString("import Pootle");
from
PyObject *obj = PyString_FromString("Pootle");
PyImport_Import(obj);
Py_DECREF(obj);
after initializing the Pootle module in some C code. The first seems like the name is Pootle
available for subsequent calls PyRun_SimpleString
, but the second doesn't.
Can someone explain the difference to me? Is there a way to do what the first one does with C API calls?
thanks
a source to share
All calls PyImport_Import
are returning a reference to a module - it does not make such a reference available to other parts of the program. So, if you want to PyRun_SimpleString
see your new imported module, you need to add it manually.
PyRun_SimpleString
automatically works in the namespace of modules __main__
. Without paying too much attention to error checking (be careful with returning NULL!), This is a general scheme:
PyObject *main = PyImport_AddModule("__main__");
PyObject *obj = PyString_FromString("Pootle");
PyObject *pootle = PyImport_Import(obj);
PyObject_SetAttrString(main, "Pootle", pootle);
Py_DECREF(obj);
Py_XDECREF(pootle);
a source to share