(Python/C API) "ModuleNotFoundError" 对于子目录中的模块

(Python/C API) "ModuleNotFoundError" for modules in subdirectories

我在 C 程序中使用 Python 3。我想要做的是 "run" 单个 Python 文件 (.py),它将成为更大 Python 项目的主文件。

当我在这个 Python 文件中使用 import 时,它适用于同一目录中的其他 Python 文件。事实上,每当我在终端中使用 "Python" 运行 .py 文件时,import 也适用于子目录中的文件。

但是,如果我 运行 它在 C 中使用 PyRun_SimpleFile,我会收到一个 "ModuleNotFoundError" 错误。

这是我的目录设置:

Project/
|-- Program.cpp
|-- Program.exe
|-- __init__.py
|-- bla.py
|-- Test/
|   |-- __init__.py
|   |-- bla2.py

最好,我不想使用 sys.path.append('./Test'),这样我可以在导入中使用子目录名称。

以下是所有相关文件的内容:


bla.py

import Test.bla2

bla2.py

print("in bla2.py now!")

Program.cpp

#include <Python.h>
#include <iostream>

int main(int argc, char **argv)
{
    Py_Initialize();

    FILE *file = _Py_fopen( "bla.py", "r" ); 
    PyRun_SimpleFile(file, "bla.py");

    Py_Finalize();
    return 0;
}

您只需添加

PySys_SetArgv(1, argv);

Py_Initialize 之后(documentation)。这会将您的程序所在的目录添加到 Python 路径中。 (这相当于在路径前添加 .,而不是 ./Test,但它应该更可靠,例如,如果您的程序不是从其自己的目录启动的。它会获取有关位置的所需信息您的程序位于 C++ argv)

调用您的模块 Test 可能不是个好主意。有一个名为 test 的内置 Python 模块,在不区分大小写的 OS 上(如 Windows 可能会发生冲突并改为加载。