我正在使用Python C API,并且不断遇到错误
ModuleNotFoundError: No module named '/home/user_1/project/ml/multiply
。这是我的c++文件,它的路径是/home/user_1/project/ml/testcapi.cpp
,改编自Python C API文档:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
int
main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pValue;
int i;
if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
return 1;
}
Py_Initialize();
pName = PyUnicode_FromString("/home/user_1/project/ml/multiply.py");
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(argc - 3);
for (i = 0; i < argc - 3; ++i) {
pValue = PyLong_FromLong(atoi(argv[i + 3]));
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, i, pValue);
}
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result of call: %ld\n", PyLong_AsLong(pValue));
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return 1;
}
}
else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
return 1;
}
if (Py_FinalizeEx() < 0) {
return 120;
}
return 0;
}
这是我的 python 脚本,直接取自 C API 文档:
def multiply(a,b):
print("Will compute", a, "times", b)
c = 0
for i in range(0, a):
c = c + b
return c
现在,由于某种原因,当我运行程序时,出现“找不到模块”错误。我的编译命令是
g++ testcapi.cpp -I /usr/include/python3.10 -L usr/lib/python3.10 -lpython -o a
,我正在运行最新稳定版 Ubuntu 的 VM 上。没有编译错误。
我正在使用
./a multiply multiply 3 2
运行程序(也直接取自 Python C API 文档)。
我是Python新手(通常是C/C++/Java),我不明白为什么它找不到脚本。我首先尝试使用
pName = PyUnicode_DecodeFSDefault(argv[1]);
而不是 pName = PyUnicode_FromString("/home/user_1/project/ml/multiply.py");
加载它,但这也不起作用,同样的错误。
我用过
python -c "import sys; print(sys.path)"
它显示了 python 用于搜索模块的路径列表。我结束了将脚本移动到
usr/lib/python3.10
的操作,它能够找到模块并按预期运行程序。
如果有人知道如何使用 Python C API 从 C++ 代码中设置路径,那将是更理想的解决方案。我尝试使用 Py_SetProgramName 和 Py_SetPath 无济于事。