打包成 exe
最簡單的方法是用
PyInstaller
:
-
安裝 PyInstaller
-
python -m pip install pyinstaller
-
-
在專案資料夾執行
-
python -m PyInstaller --onefile secure_server.py
-
-
產生結果
-
dist\secure_server.exe
-
針對你目前的程式的補充
你的程式會動態 import
win32com.client
,所以建議加上 hidden import:
-
python -m PyInstaller --onefile secure_server.py --hidden-import=win32com --hidden-import=win32com.client
如果要保留 console 視窗,可直接如上;若想隱藏 console,改成:
-
python -m PyInstaller --onefile --noconsole secure_server.py --hidden-import=win32com --hidden-import=win32com.client
注意
-
PyInstaller會把 exe 跟相依套件打包到dist\內 -
若有額外資料檔(例如
.pem/.key),需另外處理 -
在執行前先確保
pywin32已安裝,因為你使用 Outlook COM 發信
如果你要,我也可以幫你寫一個
pyinstaller
的打包命令或
spec
檔。
## 讓不特定人士可執行的設計
### ✅ 最好方案:用 `PyInstaller --onefile`
這是最常見也最實用的做法:
- `python -m pip install pyinstaller`
- `python -m PyInstaller --onefile secure_server.py --hidden-import=win32com --hidden-import=win32com.client`
這樣會產生一個單一 `dist\secure_server.exe`,使用者只要執行這個 `.exe`,不需要自己另外放 `pythonXX.dll` 或其他套件檔案。
### ⚠️ 但要理解的事
- `--onefile` 只是把所有需要的 DLL / 模組打包到一個 exe 裡
- 這並不是「完全沒 DLL」,而是「不用你另外分發、管理 DLL」
- 如果真的希望完全不打包,則目標電腦必須已經有對應的 Python 與相依套件安裝好,這對不特定使用者通常不實際
### 其它可行方向
1. `Nuitka`
- 也能產生單一 exe,會編譯成 native code
- 但仍可能需要部分 runtime 檔案
2. 直接提供「便攜版 Python」
- 把 portable Python 與程式一起放在 ZIP
- 使用者解壓後執行 `python.exe secure_server.py`
- 這樣也不用他們自行安裝 Python,但依然是有多個檔案
### 建議
最簡單、最符合你需求的就是:
- 用 `PyInstaller --onefile`
- 不用讓使用者手動安裝 DLL
- 如果要更好,搭配一個簡單的 `README` 或桌面捷徑
> 結論:對不特定人士,`PyInstaller --onefile` 是最佳設計。
## 打包命令
在你的專案目錄下執行:
```powershell
python -m PyInstaller --onefile secure_server.py --hidden-import=win32com --hidden-import=win32com.client --add-data "secure_server.pem;." --add-data "secure_server.key;."
```
### 重點
- `--onefile`:產生單一 `dist\secure_server.exe`
- `--hidden-import=win32com --hidden-import=win32com.client`:保證 Outlook COM 相關模組被打包
- `--add-data "secure_server.pem;." --add-data "secure_server.key;."`:把 `.pem` 與 `.key` 一併打包進 exe
如果你也想隱藏 console 視窗,可以再加上 `--noconsole`。
沒有留言:
張貼留言