Search code examples
pythoncpython-3.xpython-c-api

Import module after Py_Initialize


Today, I use PyImport_AppendInittab to append python modules built in C. PyImport_AppendInittab needs to be called before Py_Initialize. I can't finalize and then initialize the engine again. The problem is that now I need to append some modules after Py_Initialize. Is there a way to do it?

I'm using Python 3.6.


Solution

  • Solved the problem by doing this:

    if (Py_IsInitialized()) {
        PyImport_AddModule(module_name);
        PyObject* pyModule = moduleInitFunc();
        PyObject* sys_modules = PyImport_GetModuleDict();
        PyDict_SetItemString(sys_modules, module_name, pyModule);
        Py_DECREF(pyModule);
    }
    

    See this answer.