【Qt】Qt中调用python接口

在Qt程序中调用python函数从步骤

1、在pro中添加python的头文件路径和库
INCLUDEPATH += /usr/include/python3.4
LIBS += -L /usr/lib/python3.4/config-3.4m-x86_64-linux-gnu -lpython3.4
2、添加python头文件
#undef slots
#include 
#define slots Q_SLOTS

注意,在Python.h中定义了slots和Qt的槽定义冲突,使用#undef来解决该冲突,否则会报错:/usr/include/python3.4/object.h:435: error: expected unqualified-id before ‘;’ token
PyType_Slot slots; / terminated by slot==0. */

typedef struct{
	const char* name;
 	int basicsize;
	int itemsize;
	unsigned int flags;
	PyType_Slot *slots; /* terminated by slot==0. */
} PyType_Spec;
3、hello.py
# -*- coding: utf-8 -*-
def printHello():
    print("hello world")
4、Qt中调用python的基本步骤
	//【1】初始化python模块
	Py_Initialize();
	if ( !Py_IsInitialized() ){
		return -1;
	}

	//【2】设置将要加载的python脚本的路径,否则在运行时找不到
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('/home/workspace/tmp/python')");

	//【3】导入hello.py模块
	PyObject* pModule = PyImport_ImportModule("hello");
	if (!pModule) {
		qDebug()<< "Can't open python file!";
		return -1;
	}

	//【4】获取hello模块中的printHello函数
	PyObject* pFunhello= PyObject_GetAttrString(pModule,"printHello");
	
	if(!pFunhello){
		qDebug() <<"Get function hello failed" ;
		return -1;
	}

	//【5】调用printHello函数
	PyObject_CallObject(pFunhello,NULL);

	//【6】结束,释放python
	Py_Finalize();
5、注意事项

1)如果python脚本中有错误,PyImport_ImportModule函数将加载python模块失败;
即PyObject* pModule = PyImport_ImportModule(“hello”),返回的pModule==NULL。
2)python脚本找不到时,也会报python模块加载失败

你可能感兴趣的:(Qt,Python)