QT 调用 python 模块
linux环境下 python2.7 Qt 5.10.0
1 testPy.pro
QT += core
QT -= gui
CONFIG += c++11
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
TARGET = testPy
DESTDIR = $$PWD/../bin
SOURCES += main.cpp
DEFINES += QT_DEPRECATED_WARNINGS
#-- add python2.7 lib--
INCLUDEPATH += -I /usr/include/python2.7
LIBS += -L /usr/lib/python2.7 -lpython2.7
#--test.py file
OTHER_FILES += test.py\
#copy files
{
unix{
system(cp -rv $$OTHER_FILES $$DESTDIR)
}
}
2 main.cpp
#include <QCoreApplication>
#include <Python.h>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//初始化python模块
Py_Initialize();
if ( !Py_IsInitialized() )
{
return -1;
}
//导入test.py模块
PyObject* pModule = PyImport_ImportModule("test");
if (!pModule) {
qDebug("Cant open python file!\n");
return -1;
}
//获取test模块中的hello函数
PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello");
//注释掉的这部分是另一种获得test模块中的hello函数的方法
// PyObject* pDict = PyModule_GetDict(pModule);
// if (!pDict) {
// qDebug("Cant find dictionary.\n");
// return -1;
// }
// PyObject* pFunhello = PyDict_GetItemString(pDict, "hello");
if(!pFunhello){
qDebug()<<"Get function hello failed";
return -1;
}
//调用hello函数
PyObject_CallFunction(pFunhello,NULL);
//结束,释放python
Py_Finalize();
return a.exec();
}
3 test.py
#!/usr/bin/env python
def hello():
print("qt invoke python!")