环境配置
.pro文件中添加python环境
INCLUDEPATH += /usr/include/python2.7
LIBS += /usr/lib/x86_64-linux-gnu/libpython2.7.so
编写python脚本zytest.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def hello():
print("hello world")
在mianwindow.cpp中测试
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <Python.h>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
Py_Initialize();
if (!Py_IsInitialized()) {
return;
}
PyRun_SimpleString("import sys");
// /home/qt_project/untitled/为qt项目路径,zytest.py就在这个路径下
PyRun_SimpleString("sys.path.append('/home/qt_project/untitled/')");
PyObject* pModule = PyImport_ImportModule("zytest");
if (!pModule) {
qDebug()<<"cant open python file";
return;
}
PyObject* pFunHello = PyObject_GetAttrString(pModule,"hello");
if (!pFunHello) {
qDebug("get function hello failed");
return;
}
PyObject_CallFunction(pFunHello,NULL);
Py_Finalize();
}
MainWindow::~MainWindow()
{
delete ui;
}
成功运行!!