Why can't PyImport_Import load a module from the current directory?

I am trying to run an implementation example and I cannot load the module from the current working directory, unless I explicitly add it to sys.path , then it works:

 PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\".\")"); 

Shouldn't Python look for modules in the current directory?

Edit1 : tried only importing the module with

 Py_Initialize(); PyRun_SimpleString("import multiply"); 

And still the following error fails:

 Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named multiply 

Edit2 . From sys.path docs :

If the script directory is not accessible (for example, if the interpreter is invoked interactively or if the script is read from standard input), path [0] is an empty string that directs Python to search for modules in the current directory first .

Not sure what this means is unavailable, but if I type sys.path[0] it is not empty:

 /usr/lib/pymodules/python2.7 
+8
python linux python-embedding
source share
3 answers

You need to call PySys_SetArgv(int argc, char **argv, int updatepath) for the relative import to work. This will add the script path to sys.path if updatepath is 0 (refer to docs for more information).

The following should do the trick

 #include <Python.h> int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); /* optional but recommended */ Py_Initialize(); PySys_SetArgv(argc, argv); // must call this to get sys.argv and relative imports PyRun_SimpleString("import os, sys\n" "print sys.argv, \"\\n\".join(sys.path)\n" "print os.getcwd()\n" "import thing\n" // import a relative module "thing.printer()\n"); Py_Finalize(); return 0; } 
+18
source share

I had exactly the same problem, and I solved it simply by adding Py_Initialize(); and Py_Finalize();

Hope this helps you

0
source share

What I need to do with python 3.5: PySys_SetPath in order to be able to import from cwd :

 QString qs = QDir::currentPath(); std::wstring ws = qs.toStdWString(); PySys_SetPath(ws.data()); 

Q in it Qt.

0
source share

All Articles