引言:大模型是個好工具,盡管好多內容都是拼湊的,但是整理學到的就是自己的。因工作需要隱藏python源代碼,方法有PyInstaller 、Cpython等多種方法,PyInstaller更為常用,PyInstaller打包 Python 工程步驟整理如下:
一、確保系統環境準備就緒
-
安裝 Python 和 pip
確認版本(建議 Python 3.6+):python3 --version pip3 --version
若未安裝,則根據使用系統情況進行安裝。
-
安裝 PyInstaller
通過 pip 安裝最新版 PyInstaller:pip install pyinstaller==4.10
二、打包 Python 工程
1. 最簡打包(生成單個可執行文件)
-
打包并保留控制臺窗口(適用于命令行程序)
pyinstaller your_script.py
2.常用選項
-
進入工程根目錄,執行:
pyinstaller --onefile your_script.py
--onefile
: 生成單個可執行文件,將所有依賴打包成單個.exe
(Windows)或無后綴文件(Linux/macOS)。your_script.py
:替換為你的主程序入口文件。- 輸出目錄:
dist/
下生成可執行文件。
-
打包 GUI 程序(隱藏控制臺)
pyinstaller --onefile --windowed your_script.py
--windowed
: 適用于 PyQt/Tkinter 等 GUI 程序,運行時不顯示命令行窗口。 -
使用
--debug
參數生成詳細日志:pyinstaller --debug your_script.py
三、打包高級選項
1. 添加數據文件(如配置文件、圖片)
pyinstaller --onefile --add-data "data/config.json:data" your_script.py
- 格式:
源路徑;目標路徑
(Windows 用;
,Linux/macOS 用:
)。 - 示例:將
data/config.json
打包到程序內的data
目錄。
2. 指定程序圖標
pyinstaller --onefile --icon=app.ico your_script.py
- 支持
.ico
(Windows)、.icns
(macOS)、.png
(部分系統)。
3. 排除不必要的模塊(減小體積)
pyinstaller --onefile --exclude-module matplotlib your_script.py
- 避免打包大型但未使用的庫(如
matplotlib
、numpy
)。
4. 隱藏導入的模塊(解決 ModuleNotFoundError
)
pyinstaller --onefile --hidden-import=pandas --hidden-import=numpy your_script.py
- 或通過
.spec
文件配置(見下文)。
5. 啟用 UPX 壓縮(需安裝 UPX)
pyinstaller --onefile --upx-dir=/path/to/upx your_script.py
<