/*网上有许多文章讲的都太繁琐了,我来做一个简要的代码模板总结*/
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的接口
}
其他细节自己想办法补充了。