Qt调用python有参函数,并取函数返回值,并多次调用python模型
根据之前博客的配置已经将python环境以及qt成功调用python模块,此处需要调用模块内部的函数并取得函数返回值:
首先,新建python文件:
首先看一下函数接口以及调用方式,可以看到参数全部都为string类型:
print(soh_estimation('C:/Users/lzg/Desktop/model/charge_device/file/data/Table_DataSOC50-90.csv','LLL',train_feature_path,processed_data_dir,feature_dir,'3420','3465'))
根据参数类型构建调用方式:
//设置主目录,就是python的主目录
Py_SetPythonHome(L"D:\\conda\\envs\\model");
//初始化python模块
Py_Initialize();
if(!Py_IsInitialized())
{
return -1;
}
PyRun_SimpleString("import numpy as np"); //加载相关模块
PyRun_SimpleString("import pandas as pd");
PyRun_SimpleString("import os");
PyRun_SimpleString("from scipy import interpolate");
PyRun_SimpleString("from datetime import datetime, time");
PyRun_SimpleString("import torch");
PyRun_SimpleString("import gpytorch");
PyObject* pModule = PyImport_ImportModule("charge"); //加载自定义模块
PyObject* pFun= PyObject_GetAttrString(pModule,"soh_estimation"); //加载方法,也就是函数
PyObject* args = PyTuple_New(7); //构建元组,存放函数参数
PyObject* arg1 = PyUnicode_FromString("C:/Users/lzg/Desktop/qt_python/python_test/charge_device/file/data/Table_DataSOC50-90.csv");
PyObject* arg2 = PyUnicode_FromString("LLL");
PyObject* arg3 = PyUnicode_FromString("C:/Users/lzg/Desktop/qt_python/python_test/charge_device/file/tmp/HIs.csv");
PyObject* arg4 = PyUnicode_FromString("C:/Users/lzg/Desktop/qt_python/python_test/charge_device/file/tmp/processed_data/");
PyObject* arg5 = PyUnicode_FromString("C:/Users/lzg/Desktop/qt_python/python_test/charge_device/file/tmp/feature/");
PyObject* arg6 = PyUnicode_FromString("3420");
PyObject* arg7 = PyUnicode_FromString("3465");
PyTuple_SetItem(args, 0, arg1); //将参数都放到元组中
PyTuple_SetItem(args, 1, arg2);
PyTuple_SetItem(args, 2, arg3);
PyTuple_SetItem(args, 3, arg4);
PyTuple_SetItem(args, 4, arg5);
PyTuple_SetItem(args, 5, arg6);
PyTuple_SetItem(args, 6, arg7);
PyObject* fshowc = PyObject_CallObject(pFun, args); //调用函数
if(fshowc) {
//将返回值转化为string类型
PyObject* repr = PyObject_Repr(fshowc);
PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
char* result = PyBytes_AsString(str);
qDebug() << "result:" << result;
}
Py_Finalize();
成功运行:
以上程序还存在bug,那就是无法多次调用,多次调用内存会急剧上升直至崩溃,因此还需要在后面增加垃圾回收函数:
PyGC_Collect();
只有这样,在多次调用python模型的同时程序占用内存也不会增加。