簡體   English   中英

將 python 完全嵌入到 Qt 應用程序中

[英]Fully embedding python into Qt application

我正在尋找一種將 python 完全嵌入 Qt 應用程序的方法。 With this, I mean that I want to build a Qt application that executes python code and I can fully distribute without having to care about which python version is installed in the target machine, or without having to ask the future user to install python by him /她自己。

I've checked the libraries PythonQt, PyBind11, Boost.Python, and the native python libraries, and they are good to link C++ to Python, but any of them do what I want to do.

我在 Linux 中嘗試了以下操作,並且我計划在 Windows 和 Mac 上執行相同(或至少類似的方法):

  1. 下載 Python 的源代碼(在我的例子中,Python 3.9)。

  2. 構建 python。

     mkdir build cd build../configure --enable-optimizations --enable-shared make make install DESTDIR=installed/
  3. 將安裝的內容復制到我的項目的依賴項文件夾中。 安裝程序的內容是以下文件夾:

     - bin: Contains python executable and some tools like pip. - include: Contains all of the headers of python. - lib: Contains the.so libraries and the python modules (if you install a new python module using pip, it will be installed here in python3.9/site-packages/). - shared: Contains the man entries of python.

構建 Python3.9 后,我還沒有安裝任何庫,以測試這是否是 C++ 正在調用的 python。

我已將其從 my.pro 文件中的 Qt 應用程序中鏈接,如下所示:

INCLUDEPATH += $$PWD/../dependencies/python3.9/linux/include/python3.9
DEPENDPATH += $$PWD/../dependencies/python3.9/linux/include/python3.9


LIBS += -L$$PWD/../dependencies/python3.9/linux/lib/ -lpython3.9

鏈接后,我像這樣調用 python :

Py_SetPythonHome(L"/link/to/dependencies/python3.9/linux/lib/python3.9/");
Py_SetPath(L"/link/to/dependencies/python3.9/linux/lib/python3.9/");

wchar_t *program = Py_DecodeLocale("", NULL);
if (program == NULL) {
    fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
    exit(1);
}
Py_SetProgramName(program);  /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("import pgmpy");
if (Py_FinalizeEx() < 0) {
    exit(120);
}
PyMem_RawFree(program);

在這段代碼中,我正在導入庫pgmpy 這個 package 沒有安裝在我構建的 python 版本中。 但是,它安裝在我的本地版本 python 中,這意味着它沒有使用我構建的 python,即使這是鏈接的那個。

是否有任何配置步驟或我缺少的東西? 這可行嗎? 我對不是特定於 Qt 但可以應用於任何 C++ 項目的解決方案更感興趣,這就是我使用 pybind11 而不是 pythonQt 的原因之一

謝謝你。

我終於找到了解決方法。

我從終端執行了 python 解釋器,並打印了 sys.path,顯示了正確的路徑。

然后,在 C++ 中,我將正確的路徑附加到 sys.path,刪除了錯誤的路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM