gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:10:14 25 4
gpt4 key购买 nike

我正在尝试运行 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) 才能使相关导入工作。如果 updatepath0,这会将正在执行的脚本的路径添加到 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 - 为什么 PyImport_Import 无法从当前目录加载模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13422764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com