【问题标题】:Why does PyImport_Import fail to load a module from the current directory?为什么 PyImport_Import 无法从当前目录加载模块?
【发布时间】:2012-11-16 19:00:54
【问题描述】:

我正在尝试运行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.pathdocs

如果脚本目录不可用(例如,如果解释器是 以交互方式调用或者如果脚本是从标准输入中读取的), path[0] 是空字符串,指示Python搜索模块 首先在当前目录中

不确定不可用是什么意思,但如果我打印sys.path[0],它就不是空的:

/usr/lib/pymodules/python2.7

【问题讨论】:

  • python 应该,你有没有试过打印出os.getcwd() 来检查你在哪里?
  • 尝试from __main__ import multiply 假设multiply 是按照教程在文件中定义的函数

标签: python linux python-2.7 python-embedding


【解决方案1】:

您需要调用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;
}

【讨论】:

  • 我认为您应该包含文档中的以下句子并相应地修改您的示例:These parameters are similar to those passed to the program’s main() function with the difference that the first entry should refer to the script file to be executed rather than the executable hosting the Python interpreter.
【解决方案2】:

我对 python 3.5 所做的是 PySys_SetPath 能够从 cwd 位置导入:

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

里面的Qs是Qt。

【讨论】:

    【解决方案3】:

    我遇到了完全相同的问题,我通过添加 Py_Initialize();Py_Finalize(); 解决了它

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 2017-08-15
      相关资源
      最近更新 更多