Qt調用Python並打包發佈

原文鏈接Qt調用Python並打包發佈

工作中突然遇到 Qt 調用 Python 腳本的情況,研究下並記錄填坑記錄

必備步驟

  1. 引入頭文件和庫
  2. 在代碼中引入 python.h
  3. 初始化代碼,並調用 PyRun_SimpleString 系列函數

新建一個 pri 工程

爲啥要弄個 pri 包含呢?這樣可以很好的實現代碼分離

INCLUDEPATH += $$PWD

HEADERS += \
    $$PWD/callpython.h

SOURCES += \
    $$PWD/callpython.cpp

INCLUDEPATH += "c:/python34/include"
LIBS += "c:/python34/libs/python34.lib"

調用示例

#include <Python.h>

//.......
{
    Py_Initialize();   //初始化

    if(!Py_IsInitialized())
        return;
    PyRun_SimpleString("print('hello python from Qt')");
}

填坑記錄

python 和 Qt 的 slot 衝突

  1. 錯誤爲
object.h:435: error: expected unqualified-id before ';' token
     PyType_Slot *slots; /* terminated by slot==0. */
                       ^
  1. 解決方法:
  • 方案 1: 避免使用 QObject 及子類
  • 方案 2: 在引用 ptyhon.h 的位置前重新定義 slots,詳見文末代碼工程
//注意人引入位置
#undef slots
#include <Python.h>
#define slots Q_SLOTS
  • 方案 3: 網上一般做法修改 python 的頭文件(不推薦)

打包後運行崩潰

  1. 崩潰爲
Fatal Python error: Py_Initialize: unable to load the file system codec ImportError: No module named 'encodings'
  1. 經過一陣亂擼想到以前用pyinstaller發佈程序明明可以不需要 python 環境啊,經測試可行的方法爲:
    • 先隨便寫個.py 代碼,使用 pyinstaller 發佈
    pyinstaller test.py
    
  • 拷貝 dist 目錄下得所有文件到要打包 qt 的目錄下
  • 將 base_library.zip 解壓到要打包的 qt 目錄下
    不崩潰了
  1. 繼續報錯
Failed to import the site module
ImportError: No module named 'site'

搜索 site.py 文件也放到 qt 打包目錄下,打完收招

示例工程

文末還是給出示例工程,外加打包好的程序哦代碼和可執行程序

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章