编程语言
首页 > 编程语言> > python – 为什么PyImport_Import无法从当前目录加载模块?

python – 为什么PyImport_Import无法从当前目录加载模块?

作者:互联网

我正在尝试运行embedding example并且我无法从当前工作目录加载模块,除非我将其显式添加到sys.path然后它可以工作:

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

Python不应该在当前目录中查找模块吗?

Edit1:尝试导入模块:

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

它仍然失败,出现以下错误:

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

Edit2:从sys.path docs

If the script directory is not available (e.g. if the interpreter is
invoked interactively or if the script is read from standard input),
path[0] is the empty string, which directs Python to search modules
in the current directory first
.

不确定它的含义是不可用的,但如果我打印sys.path [0]它不是空的:

/usr/lib/pymodules/python2.7

解决方法:

您需要调用PySys_SetArgv(int argc,char ** argv,int updatepath)才能使相对导入生效.如果updatepath为0,这将把正在执行的脚本的路径添加到sys.path(有关更多信息,请参阅docs).

以下应该做的伎俩

#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;
}

标签:python,linux,python-2-7,python-embedding
来源: https://codeday.me/bug/20190928/1829663.html