I have Python extension module written in C. I want to use in this C code one of the standard Python modules, for example os
or shutil
. How is best to do this?
PyObject* os = PyImport_ImportModuleNoBlock("os");
if (os == NULL)
return NULL;
someattr = PyObject_GetAttrString(os, "someattr");
Py_DECREF(os);
If you import the module only once e.g., in init_yourmodule()
function then use PyImport_ImportModule("os")
.