C++调用python过程+Anaconda使用arcpy包踩的坑
C++调python(python文件包含第三方库):
工具:VS2017 QT5插件 Pycharm Anaconda
1.下载Anaconda,配置一个虚拟环境
2.将这个环境里的DLLs和Lib包以及相应py文件,放至C++项目生成.exe文件同级目录下
3.将include和libs放在项目某文件夹下,在VS里添加附加包含目录、附加库目录和附加依赖项
4.调用python代码
C++:
void Risk_HLProduct::PowerFit() {//调用py文件,获取拟合a,b
Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
QString str;
if (!Py_IsInitialized())
{
printf("初始化失败!");
//return res;
}
PyRun_SimpleString("import sys");
//PyRun_SimpleString("sys.path.append('./')");
PyRun_SimpleString("sys.path.append('E:/bin')");//.exe文件所在目录
PyRun_SimpleString("sys.path.append('E:/bin/DLLs')");//从anaconda复制来的DLLs
PyRun_SimpleString("sys.path.append('E:/bin/Lib')");//从anaconda复制来的Lib
PyRun_SimpleString("print(sys.path)");
PyObject * pModule = NULL;//声明变量
PyObject * pFunc = NULL;// 声明变量
pModule = PyImport_ImportModule("PowerFit");//这里是要调用的文件名PowerFit.py
if (pModule == NULL)
{
qDebug()<< "没找到" << endl;
}
pFunc = PyObject_GetAttrString(pModule, "power_fit");//这里是要调用的函数名
PyObject* pReturn = PyObject_CallObject(pFunc, NULL);//无参数调用
//直接解析
PyArg_ParseTuple(pReturn, "f|f", &a, &b);//返回两个float值 //这里的f|f是两个float的意思,返回值解析可参考https://blog.csdn.net/qq_38770597/article/details/128061813?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-5-128061813-blog-81224381.235%5Ev35%5Epc_relevant_increate_t0_download_v2&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-5-128061813-blog-81224381.235%5Ev35%5Epc_relevant_increate_t0_download_v2&utm_relevant_index=4
Py_Finalize(); // 与初始化对应
system("pause");
//return res;
}
Python:
# encoding: utf-8
from scipy.optimize import curve_fit
### 定义拟合函数, y = a * x^b ###
def target_func(x, a, b):
return a * (x ** b)
def power_fit():
# 幂函数拟合
xdata = [10, 4, 8.96, 7.5, 13.34, 10.8, 16.45, 15, 7.92, 18, 15, 13.75, 33.54, 30]
ydata = [28, 60, 134.4, 187.5, 200, 216, 246.75, 300, 318, 360, 630, 1265, 1509, 4500]
### 利用拟合函数求特征值 ###
popt, pcov = curve_fit(target_func, xdata, ydata)
# 拟合的值
y = [target_func(i, popt[0], popt[1]) for i in xdata]
return popt[0], popt[1]
if __name__ == '__main__':
popt = power_fit()
print("a = %f b = %f " % (popt[0], popt[1]))
Anaconda中使用arcpy:
1.创建新环境arcpyP27,可参考https://zhuanlan.zhihu.com/p/591010245
2.缺什么模块都在这下载,记得一定一定要把对应的依赖包也下载上
https://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib
记得选择对应位数和python版本的依赖包:比如netCDF4,我这边是python2.7和win32,下载了对应的netCDF4‑1.5.3‑cp27‑cp27m‑win32.whl(cp后面是python版本,win后面是位数)
3.把下载的whl文件放在D:\conda\envs\arcpyP27\Lib\site-packages下,打开Anaconda Prompt,先cd到这个文件夹下,然后activate arcpyP27环境:
4.运行对应的py文件:cd到py对应文件夹下,转arcpyP27环境:python xxx.py