簡體   English   中英

使用 C++ 項目運送 Python 解釋器

[英]Shipping Python interpreter with C++ project

問題描述:我有一個Visual Studio 2022 C++項目,涉及到live python腳本解釋。 當然,我需要一個有效的 Python 安裝來執行此操作。 但是,我打算將其作為應用程序發布,因此我希望進行本地化的 Python 安裝,以避免消費者端安裝,但這不會干擾 Windows 的環境變量。

我做了什么:我從我的 Python 安裝的“include”文件夾中包含了“Python.h”,我已經將它的“libs”文件夾添加到“Additional Library Directories”,我已經將“python311.lib”添加到“Additional”依賴項”,我記得將 Python311.dll 復制到我項目的解決方案目錄中。 一切都正確鏈接。 但是,當我運行編譯並執行我的程序時,我收到一長串錯誤,如下所示:

Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Python path configuration:
  PYTHONHOME = (not set)
  PYTHONPATH = (not set)
  program name = 'python'
  isolated = 0
  environment = 1
  user site = 1
  safe_path = 0
  import site = 1
  is in build tree = 0
  stdlib dir = 'C:\Coding Projects\MaSGE\Lib'
  sys._base_executable = 'C:\\Coding Projects\\MaSGE\\x64\\Release\\MaSGE.exe'
  sys.base_prefix = 'C:\\Coding Projects\\MaSGE'
  sys.base_exec_prefix = 'C:\\Coding Projects\\MaSGE'
  sys.platlibdir = 'DLLs'
  sys.executable = 'C:\\Coding Projects\\MaSGE\\x64\\Release\\MaSGE.exe'
  sys.prefix = 'C:\\Coding Projects\\MaSGE'
  sys.exec_prefix = 'C:\\Coding Projects\\MaSGE'
  sys.path = [
    'C:\\Coding Projects\\MaSGE\\python311.zip',
    'C:\\Coding Projects\\MaSGE\\Lib',
    'C:\\Coding Projects\\MaSGE\\DLLs',
  ]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

Current thread 0x0000399c (most recent call first):
  <no Python frame>

我特別感興趣的是前兩行,加上第 4 行和第 5 行的“PYTHONHOME =(未設置)”和“PYTHONPATH =(未設置)”,據我所知,它們是環境變量。

這讓我想到了問題的症結所在:是否有某種方法可以將便攜式 Python 解釋器安裝到特定文件夾以規避環境變量問題?

要將 python 嵌入到您的應用程序中,您需要做兩件事:

初始化隔離 python

這不會讓用戶的系統干擾您的應用程序。

https://docs.python.org/3/c-api/init_config.html#init-isolated-conf

使用您的應用程序部署 python 東西

在 windows 上,您需要:

  1. Python DLL ( python311.dll )。
  2. Python 標准庫。 從 python 安裝復制Lib文件夾,或 zip 其內容並將其命名為 python dll (例如python311.zip ),或使用相同的 zip 來自 887448143
  3. Python 個模塊( DLLs目錄)

在 linux 上,情況略有不同:

  1. Python 共享庫 ( libpython311.so )
  2. Python 標准庫(從 python 安裝復制lib/python311/文件夾,或 zip除了lib-dynload文件夾之外的內容並將其命名為lib/python311.zip
  3. (如果使用壓縮標准庫)將lib-dynload復制到lib/python3.11/lib-dynload

當然,您必須將3113.11替換為您的 python 版本。

暫無
暫無

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

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