1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.