Search code examples
pythoncpython-c-apipython-extensions

Import and use standard Python module from inside Python C extension


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?


Solution

  • 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").