准備工作
使用 pyinstaller 打包
pip install pyinstaller
詳細用法可參考 https://realpython.com/pyinstaller-python/
pyinstaller 網上教程一堆,這里只列常用命令供快速查閱
參數說明
--name -n 重命名,不需要加后綴,自帶.exe
pyinstaller cli.py --name realpython
--onefile -F 打包成一個文件。dist文件夾下只會出現一個exe文件
pyinstaller cli.py --onefile
--hidden-import 使函數內部的 import 依賴和 import() 方法可用
后面需要加模塊名稱,可以使用多次。如果是文件開頭使用 import 沒有影響。也就是說除非你在 main 函數里面寫一些 import,需要用到這個命令,正常在文件開頭 import 是不需要用的。
pyinstaller cli.py --hiddenimport=requests --hiddenimport=numpy
--add-data 和 --add-binary 打包附加數據或者lib
例如打包 configuration files examples, or other non-code data
重要參數,解決你打包以后代碼里面讀寫文件、引用js文件總是找不到路徑的問題。
(以下信息來自 StackOverflow)
- format:
{source}{os_separator}{destination}(destination 是文件夾路徑)- os_separator:
- Windows:
; - Mac/Linux/Unix:
:(Windows下是分號,Linux等是冒號)
- Windows:
- source and destination
- Logic:
- source: path to single or multiple files, supporting glob syntax. Tells PyInstaller where to find the file(s).
- destination file or files: destination folder which will contain your source files at run time. * NOTE: NOT the destination file name.
- folder: destination folder path, which is RELATIVE to the destination root, NOT an absolute path.
- Logic:
- os_separator:
- Examples:
- Single file:
src/README.txt:.(打包單個文件,相對路徑) - multiple files:
/mygame/sfx/*.mp3:sfx(打包多個依賴文件) - folder:
/mygame/data:data(打包文件夾)
- Single file:
打包外部 js、html的時候需要在py文件中使用相對路徑。(復制下面的代碼即可)
import os
import sys
# 獲取資源路徑
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
# 使用后,會自動獲取臨時文件夾下的資源文件,而不再需要外置靜態資源文件C:\Users\vana\AppData\Local\Temp\_MEI286322\./ids-encrypt.js
# windows系統下,當前文件夾內資源打包
pyinstaller cli.py --add-data ids-encrypt.js;.
--exclude-module 排除模塊
例如一些開發時依賴,比如 pytest 等
pyinstaller cli.py --exclude-module=pytest
-w 去掉運行時的cmd窗口。有界面的程序可使用,cmd程序勿用
pyinstaller cli.py -w
