博客
关于我
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

你可能感兴趣的文章
nmap 使用方法详细介绍
查看>>
nmap使用
查看>>
nmap使用实战(附nmap安装包)
查看>>
Nmap哪些想不到的姿势
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
nmap指纹识别要点以及又快又准之方法
查看>>
Nmap渗透测试指南之指纹识别与探测、伺机而动
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>