前言
总所周知,python作为脚本语言,胶水语言可以嵌入多种语言中使用,例如C++等,以下讲诉如何在QT中嵌入Python脚本进行编译运行。
1、下载miniconda3
链接:https://repo.anaconda.com/miniconda/
选择下载对应的你的系统安装的Python和电脑系统。
1.1下载完成后打开miniconda3所在的工作目录,随便一个地方新建一个文件夹(Python38),将miniconda3所在的工作目录中以下文件夹以及所有的后缀为.dll的文件复制进入你创建的文件夹下面。
1.2将Python38文件夹放到将要打包QT的目录下(QT打包方式请自行看其他文章),并将系统Python环境中两个.dll文件复制进入,并将你编写的Python脚本放入同一个文件夹下。
使用windeployqt main.exe生成依赖文件后,将以上文件都放入后,便可以使用EnigmaVirtualBox进行打包!
二、QT配置以及Python初始化代码
1.QT配置
代码如下(示例):
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp \
serialthread.cpp
HEADERS += \
mainwindow.h \
serialthread.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
win32:CONFIG(release, debug|release): LIBS += -LD:\Python_3\libs\ -lpython38
else:win32:CONFIG(debug, debug|release): LIBS += -LD:\Python_3\libs\ -lpython38d
INCLUDEPATH += D:\Python_3\libs
DEPENDPATH += D:\Python_3\libs
INCLUDEPATH += D:\Python_3\include
LIBS += -LD:\Python_3\libs -lpython38
DISTFILES += \
kingstcontrol.py
2.python配置初始化
代码如下(示例):
Py_SetPythonHome((const wchar_t*)(L"./Python38)"));
Py_Initialize();
if(!Py_IsInitialized())
{
qDebug() << "fail";
}
PyRun_SimpleString("impor sys");
PyRun_SimpleString("sys.path.append('./')");
将路径设置为绝对路径
总结
嵌套python脚本时要注意避免传递中文类型的数据。