实验环境:TX2使用JetPack-L4T-3.3-linux-x64_b39进行环境安装
详情参考:Jetpack3.3刷机
安装的python版本为3.5.2
1.创建Qt工程
在Qt中创建一个Qt Console Application,工程名字随意
在项目中添加python文件test.py。
2.修改相应文件
添加test.py代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def hello():
print("hello world!")
修改main.cpp代码
#include <QCoreApplication>
#include <Python.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Py_Initialize();
if ( !Py_IsInitialized() )
{
return -1;
}
PyObject* pModule = PyImport_ImportModule("test"); // 这里的test就是创建的python文件
if (!pModule) {
cout<< "Cant open python file!\n" << endl;
return -1;
}
PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello"); // 这里的hello就是python文件定义的函数
if(!pFunhello){
cout<<"Get function hello failed"<<endl;
return -1;
}
PyObject_CallFunction(pFunhello,NULL);
Py_Finalize();
return a.exec();
}
完成工程文件修改后运行工程,提示main.cpp中的Python.h头文件找不到,所以需要修改工程中的.pro文件
QT += core
QT -= gui
TARGET = cpp_to_python
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
DISTFILES += \
test.py
INCLUDEPATH +=/usr/include/python3.5
LIBS += -L/usr/lib/python3.5/config-3.5m-aarch64-linux-gnu -lpython3.5m
最后两行的INCLUDEPATH为包含路径,找到python3的安装目录,我的是=/usr/include/python3.5
LIBS为动态库的路径,我的是/usr/lib/python3.5/config-3.5m-aarch64-linux-gnu,最后-lpython3.5m
为指定动态库名称
3.报错:意外的标记位于“;”之前
报错原因:由于QT中定义了slots,而python3中又使用slot作为变量,所以有冲突
找到object.h文件,使用sudo gedit object.h命令打开object.h文件,将
yType_Slot *slots; /* terminated by slot==0. */
改为
#undef slots
PyType_Slot *slots; /* terminated by slot==0. */
#define slots Q_SLOTS
保存退出,运行,报错问题解决。