Question

using the next line

pModule = PyImport_Import(pName);

Only load modules from the current directory.

But what I want to load from somewhere else? Is there a neat way to do so?

PyRun_SimpleString("import sys\nsys.path.append('<dir>')"); Works, but it's a little bit ugly - I'm looking for a better way

Thanks!

Was it helpful?

Solution

Just found the answer I was looking for at http://realmike.org/blog/2012/07/08/embedding-python-tutorial-part-1/

Normally, when importing a module, Python tries to find the module file next to the importing module (the module that contains the import statement). Python then tries the directories in “sys.path”. The current working directory is usually not considered. In our case, the import is performed via the API, so there is no importing module in whose directory Python could search for “shout_filter.py”. The plug-in is also not on “sys.path”. One way of enabling Python to find the plug-in is to add the current working directory to the module search path by doing the equivalent of “sys.path.append(‘.’)” via the API.

Py_Initialize();
PyObject* sysPath = PySys_GetObject((char*)"path");
PyObject* programName = PyString_FromString(SplitFilename(argv[1]).c_str());
PyList_Append(sysPath, programName);
Py_DECREF(programName);

SplitFilename is a function I wrote to get the directory.

OTHER TIPS

There is a good way because this is the way it is frequently done with site-packes.

import sys
sys.path.append(directory) # sys.path is a list of all directories to import from

or you use

os.cwd(directory) # change the working directory

before the import.

An other way is ugly:

import types, sys
m = types.ModuleType('module')
sys.modules['module'] = m
exec open('file').read() in m.__dict__ # python3

Maybe you asked for a C-function to do your work but I do not know one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top