![](/img/trans.png)
[英]Why do I get an error message of NoneType object is not callable when I try to call this function?
[英]why i get "no attirubute error" when i try to call python function from c++
嗨,我按照本教程从 c++ 代码调用 python function。
这是 embeddedPython.cpp
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <iostream>
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_DecodeFSDefault(argv[1]);
/* Error checking of pName left out */
std::cout << pName << std::endl;
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */
// didn't add the all code
}
return 0;
}
和测试.py
def multiply(a,b):
print("Will compute", a, "times", b)
c = 0
for i in range(0, a):
c = c + b
return c
最后是 CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(demo)
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
add_executable(demo embeddedPython.cpp)
target_link_libraries(demo ${PYTHON_LIBRARIES})
当我尝试运行以下命令时:
./demo test multiply 3 2
我收到以下错误。
AttributeError: module 'test' has no attribute 'multiply'
Cannot find function "multiply"
可能是什么问题呢? 我认为; 我可以访问该文件,但代码找不到 function。
您的 Python 文件的名称是test.py
,但已经有一个用于回归测试的 Python 模块test
(请参阅 Python 文档),其中不包含 multiply() function。重命名您的 python 文件以避免与现有模块发生冲突。 本教程中的示例使用有效的multiply.py
。 我使用test1.py
也可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.