虛擬環境安裝 pyinstaller
pip install pyinstaller
打包exe命令:(具體的命令網上資料很多)
-
# 打包1個py文件,並隱藏執行窗口
-
pyinstaller -F -w main.py
-
# 打包1個py文件(-F),並隱藏執行窗口(-w),替換exe的ico圖標(-i img.ico)
-
pyinstaller -F -w -i img.ico main.py
以上的這種打包方式會將各種依賴庫都以源文件方式保存到文件夾中,大部分時候我們還是希望只有一個exe文件
將文件夾中所有依賴庫都打包進exe內:
-
# 合並到一個exe內(--onefile),替換exe圖標(--icon=img.ico),py源文件(main.py),隱藏執行(-w)
-
pyinstaller --onefile --icon=img.ico main.py -w
注意:當把所有依賴庫都打包進一個exe以后,且以隱藏CMD窗口方式執行時會出現錯誤,導致程序無法正常運行,所以需要用到
subprocess來執行CMD命令。這種方式來執行cmd命令就不會出現程序錯誤。
-
import subprocess
-
cmd = '你的CMD命令'
-
res = subprocess.call(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)