X

將 Python 程式編譯成 Windows 執行的 exe 擋

在 Linux 想要將 Python 程式編譯成 Windows 的執行檔,可以使用此篇(PyInstaller)的方式來達成

將 Python 程式編譯成 Windows 執行的 exe 擋

測試一樣可以用 wine 執行那個執行檔來測試

  • apt install python3-venv wine64

安裝步驟

  1. git clone https://github.com/noahbroyles/pyinstaller-wine/
    • 主要要安裝流程是這隻:https://github.com/noahbroyles/pyinstaller-wine/blob/master/main.py
  2. cd pyinstaller-wine
  3. python3 -m venv .
  4. . bin/activate
  5. pip3 install requests
  6. vim main.py # 裡面使用 32bits 的,新版 wine 支援 64bits,所以我改用 64bits (32bits 會安裝失敗)
    • https://www.python.org/ftp/python/ # 可在這邊找新版本
    • https://www.python.org/ftp/python/3.8.5/ # 太新版都有問題,最後維持這個版本
    • main.py 修改下述:
      • binary_data = requests.get('https://www.python.org/ftp/python/3.8.5/python-3.8.5.exe').content
    • 改成
      • binary_data = requests.get('https://www.python.org/ftp/python/3.8.5/python-3.8.5-amd64.exe').content
  7. python3 main.py # 裡面使用 32bits 的,新版 wine 支援 64bits,所以我改用 64bits (32bits 會安裝失敗)
  8. 會使用 wine 開始安裝 Python3.8 exe,視窗會出現安裝畫面,選擇:
    • 勾選最下方的 Add Python to PATH
    • 選 Customize installation → Next (主要要選擇安裝路徑)
    • C:\users\user-name\Local Settings\Application Data\Programs\Python\Python38-32
      改成
      C:\Python38
    • 安裝完成
  9. 安裝若出現下述錯誤:
    sys.argv[1] # 會出現錯誤
    Traceback (most recent call last):
    File "/home/user/pyinstaller-wine/main.py", line 50, in <module>
    fileToCompile = sys.argv[1]
    ~~~~~~~~^^^
    IndexError: list index out of range
    • 需要改下述兩個地方:
      • 將fileToCompile = sys.argv[1]
        • # 改成使用 PYINSTALLER_PATH = f'/home/{USER}/.wine/drive_c/Python38/Scripts/pyinstaller.exe
        • fileToCompile = PYINSTALLER_PATH # sys.argv[1] 改成 PYINSTALLER_PATH
      • 將 code = subprocess.call(['cp', f"{LIN_COMPILE_PATH}/dist/{file_exe}", f"{dist_path}/{file_exe}"])
        • # 改成 (cp ~/.wine/drive_c/users/{$USER}/PyinstallerBuilds/pyinstaller.exe C:/Python38/Scripts/pyinstaller.exe)
        • code = subprocess.call(['cp', f"{LIN_COMPILE_PATH}/{file_exe}", f"{dist_path}/{file_exe}"]) # 拿掉 dist/
  10. 再來應該就可以安裝完成
  11. 測試:
    • wine C:/Python38/Scripts/pyinstaller.exe --onefile -F /tmp/hello.py # hello.py 裡面就一行 print("hello")
    • wine C:/Python38/Scripts/pyinstaller.exe -p /home/user/.wine/drive_c/Python38/Lib/ --onefile -F /tmp/hello.py # 加載入 module
  12. 若 Windows 內 需要安裝其它套件(以 chardet 為例):
    • wine C:/Python38/Scripts/pip3.exe install chardet
  13. Compile 需要去看 compileMyProject.py # 於是可以找到 Compile 命令
  14. /home/user/dev/pyinstaller-wine
    • Compile Command:wine C:/Python38/Scripts/pyinstaller.exe -p /home/user/.wine/drive_c/Python38/Lib/ --onefile -F /home/user/hello.py
  15. 會產生在執行位置的 dist/ # *.exe
  16. 測試:wine dist/hello.exe

Tsung: 對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.
Related Post