QT 调用 python 模块

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!")

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值