博客
关于我
C++调用Python的方法以及问题集
阅读量:323 次
发布时间:2019-03-03

本文共 1717 字,大约阅读时间需要 5 分钟。

1. C++调用Python的方法

直接先上案例:

#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调用

2.调用过程中遇到的问题

1) 一开始调用python头文件就报错,提示说找不到

解决:用locate定位Python.h的位置,然后把绝对路径弄上去。
我之前试过调用没出现这个问题,迷惑,不知道怎么又出现这个问题,望有大佬路过,提点一下

#include 

修改后解决:

#include 

2)导入python脚本总是失败

pModele的返回值经常是0,这个问题是由于Python脚本中调用了很多包,而当前环境中没有安装成功,很多时候python都是在另一个环境中写好和测试的,anaconda这种,换了一个环境,忘了把原来的需要用的库和包装上。
解决:把python需要用到的库和包装上就解决了,用pipconda都是,如:
pip install sklearn pandas matplotlib joblib
安装完,最好先在当前环境中,测试一遍,看看是不是所有需要import的包都可以正常打开


Reference:

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

你可能感兴趣的文章
mysql-开启慢查询&所有操作记录日志
查看>>
MySQL-数据目录
查看>>
MySQL-数据页的结构
查看>>
MySQL-架构篇
查看>>
MySQL-索引的分类(聚簇索引、二级索引、联合索引)
查看>>
Mysql-触发器及创建触发器失败原因
查看>>
MySQL-连接
查看>>
mysql-递归查询(二)
查看>>
MySQL5.1安装
查看>>
mysql5.5和5.6版本间的坑
查看>>
mysql5.5最简安装教程
查看>>
mysql5.6 TIME,DATETIME,TIMESTAMP
查看>>
mysql5.6.21重置数据库的root密码
查看>>
Mysql5.6主从复制-基于binlog
查看>>
MySQL5.6忘记root密码(win平台)
查看>>
MySQL5.6的Linux安装shell脚本之二进制安装(一)
查看>>
MySQL5.6的zip包安装教程
查看>>
mysql5.7 for windows_MySQL 5.7 for Windows 解压缩版配置安装
查看>>
Webpack 基本环境搭建
查看>>
mysql5.7 安装版 表不能输入汉字解决方案
查看>>