Search code examples
pythonc++python-embedding

Import Python module from path in embedded Python


I'm using embedded Python in C++. I can import a module like so, given my_module.py is a file:

PyObject* pName PyUnicode_DecodeFSDefault("my_module");
PyObject* pModule = PyImport_Import(pName);

This works nicely for the most part, except that I have no control over where I can put the files containing the module; it has to be in the same directory as the executable. This is a problem for my use-case. I would like to be able to use any path to a file and import the module from there. However, I can seem to find a way to do it.


Solution

  • Assuming you've already called Py_Initialize at some point, you should be able to do:

    PyObject* sysPath = PySys_GetObject((char*)"path");
    PyList_Append(sysPath, (PyUnicode_FromString(pathToModuleDirectory)));
    

    Where pathToModuleDirectory is a string containing the path to the directory containing the module you want to be able to import. Now you should be able to import the module in the way that was described in the question.