windows 下 QT调用python
.pro 文件加上python的库
win32: LIBS += -L E:/third_party/Python310/libs/ -lpython310
INCLUDEPATH += E:/third_party/Python310/include
DEPENDPATH += E:/third_party/Python310/include
调用模块:
#include "Python.h"
void Widget::on_pushButton_clicked()
{
qDebug() <<"qt python pid = "<< QCoreApplication::applicationPid() << " tid = "<< QThread::currentThreadId();
Py_Initialize();
if(!Py_IsInitialized())
{
PyErr_Print();
qDebug() << "Can't Initialize python!\n" ;
return ;
}
PyRun_SimpleString("import sys");
//QString curPath = QDir::currentPath();
QString curPath = "E:/Code/tcpTest";
//qDebug()<<curPath;
QString strModuleName = "qt_to_python_test";
QString strFunctionName = "qt_to_python_test";
QString strSys = QString("sys.path.append('%1')").arg(curPath);
PyRun_SimpleString(strSys.toStdString().c_str());
PyObject* pModule = PyImport_ImportModule(strModuleName.toStdString().c_str());
if(!pModule)
{
qDebug()<<"pModule fail";
}
PyObject* pFunc = PyObject_GetAttrString(pModule,strFunctionName.toStdString().c_str());
if(pFunc==NULL)
{
qDebug()<<"pFunc fail";
}
PyObject* pArg= PyTuple_New(2);
PyTuple_SetItem(pArg,0,Py_BuildValue("i",4));
PyTuple_SetItem(pArg,1,Py_BuildValue("i",5));
char* pStuName;
try
{
PyObject* pReturn = PyObject_CallObject(pFunc,pArg);
int retok = PyArg_Parse(pReturn,"s",&pStuName);
}//catch (std::exception& e)
catch (std::invalid_argument e)
{
}catch(...)
{
}
Py_Finalize();
qDebug()<<"run python end res = " << pStuName;
}
还有更多参数类型