C++无参调用python的代码片段

/*网上有许多文章讲的都太繁琐了,我来做一个简要的代码模板总结*/

qt_test.py

class Tester:
def test(self) -> None:
print("Test Qt connecting");

def hello():
print("hello world!!")

callPython.cpp

//自己的无参调用python代码的案例
CallPython::CallPython():
        m_judgment(false)
{
    Py_Initialize();
    if (!Py_IsInitialized()) {
        qDebug() << "Python初始化失败!!!";
        return -1;
    }

    m_judgment = Py_IsInitialized();

//这部分注释掉的是单纯调用函数的代码
//    PyRun_SimpleString("import sys");
//    PyRun_SimpleString("sys.argv = ['qt_test.py']");
//    PyRun_SimpleString("sys.path.append('../Script')");
//    PyObject* pModule = PyImport_ImportModule("qt_test");
//    if(!pModule){
//        qDebug("init error!\n");
//        exit(-1);
//    }
//
//    PyObject* pHello = PyObject_GetAttrString(pModule,"hello");
//    if(!pHello){
//        qDebug("Can't open python file!\n");
//        exit(-1);
//    }
//
//    PyObject_CallFunction(pHello,NULL);

//这部分是调用类内成员函数的代码
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.argv = ['qt_test.py']");
    PyRun_SimpleString("sys.path.append('../Script')");//这个是相对路径,绝对路径就不展示了
    PyObject* pModule = PyImport_ImportModule("qt_test");
    if(!pModule){
        qDebug("Can't open python file!\n");
        exit(-1);
    }

    PyObject* pDict = PyModule_GetDict(pModule);
    if(!pDict) {
        qDebug("Can't find dictionary.\n");
        exit(-1);
    }

    PyObject* pClass = PyDict_GetItemString(pDict, "Tester");
    if (!pClass) {
        qDebug("Can't find class.\n");
        exit(-1);
    }

    PyObject* pConstruct = PyInstanceMethod_New(pClass);
    if (!pConstruct) {
        qDebug("Can't find construct./n");
        exit(-1);
    }
   
    PyObject* pInstance=PyObject_CallObject(pConstruct,NULL);
    if (!pInstance) {
        qDebug("Can't find instance./n");
        exit(-1);
    }

    PyObject* pRet=PyObject_CallMethod(pInstance,"test",NULL);
    if (!pRet)
    {
        qDebug("Cant find pRet");
        exit(-1);
    }

    int info;
    PyArg_Parse(pRet, "i", &info);
    qDebug()<<"result="<<info<<endl;

    Py_DECREF(pRet);
    Py_DECREF(pInstance);
    Py_DECREF(pConstruct);
    Py_DECREF(pModule);

}

CallPython::~CallPython()
{
    Py_Finalize();//关闭python解释器,或者是关掉python的接口
}

其他细节自己想办法补充了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值