Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Embedding: PyImport_Import not from the current directory

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!

like image 747
Guy L Avatar asked Jan 22 '14 10:01

Guy L


1 Answers

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.

like image 86
Guy L Avatar answered Oct 10 '22 16:10

Guy L