本文共 1717 字,大约阅读时间需要 5 分钟。
直接先上案例:
#include using namespace std;int main(int argc, char **argv){ Py_Initialize(); //这个是初始化python调用程序,必须 string path = "/media/will/Will/MyOpenFace-2019-1-30/exe/py_script"; string chdir_cmd = string("sys.path.append(\"") + path + "\")"; const char* cstr_cmd = chdir_cmd.c_str(); PyRun_SimpleString("import sys");//使用python语句 PyRun_SimpleString(cstr_cmd); PyObject* moduleName = PyUnicode_FromString("LeastSquare"); //将string类型转换成unicode类型 PyObject* pModule = PyImport_Import(moduleName);// name of python file 导入名为‘LeastSquare’的python脚本 // 判断pModule是否为0,是0就报错 cout << pModule << endl; //20201127 0 if (!pModule){ cout << "[ERROR] Python get module failed." << endl; return 0; } cout << "[INFO] Python get module succeed." << endl; PyObject* pv = PyObject_GetAttrString(pModule, "predict");// get function from python file 使用python脚本中的函数 if (!pv || !PyCallable_Check(pv)){ cout << "[ERROR] Can't find funftion (test_add)" << endl; return 0; } cout << "[INFO] Get function (test_add) succeed." << endl; Py_Finalize();// 结束Python调用
1) 一开始调用python头文件就报错,提示说找不到
解决:用locate
定位Python.h
的位置,然后把绝对路径弄上去。 我之前试过调用没出现这个问题,迷惑,不知道怎么又出现这个问题,望有大佬路过,提点一下 #include
修改后解决:
#include
2)导入python脚本总是失败
pModele
的返回值经常是0
,这个问题是由于Python脚本中调用了很多包,而当前环境中没有安装成功,很多时候python都是在另一个环境中写好和测试的,anaconda这种,换了一个环境,忘了把原来的需要用的库和包装上。 解决:把python需要用到的库和包装上就解决了,用pip
和conda
都是,如: pip install sklearn pandas matplotlib joblib
安装完,最好先在当前环境中,测试一遍,看看是不是所有需要import的包都可以正常打开 https://blog.csdn.net/lichkingyang/article/details/52061051
https://www.cnblogs.com/betterwgo/p/8176525.html 例程: https://www.jianshu.com/p/c9f5f4ce3e7a?utm_campaign=maleskine https://blog.csdn.net/qq_41433316/article/details/97141318