welcom ! Handel home

2025年4月10日 星期四

Python 專案結構(py ,pyc,exe ) CLI 範例

 

  1. ✅ 範例 Python 專案結構

  2. 🧰 py → pyc 一鍵編譯腳本(單檔 & 整個資料夾)

  3. 🧱 pyinstaller 打包範例(CLI 與 GUI)


✅ 1. 範例專案結構

這是你的一個簡單 Python 專案結構:

arduino
my_project/ ├── main.py ├── utils.py ├── config/ │ └── settings.py ├── modules/ │ ├── mathlib.py │ └── strlib.py └── compile_all.py ← 工具:一鍵編譯 .py → .pyc

🧰 2. compile_all.py:一鍵將專案中所有 .py 轉成 .pyc

python
# compile_all.py import compileall import os # 自動取得當前目錄 project_dir = os.path.dirname(os.path.abspath(__file__)) print(f"🔧 正在編譯:{project_dir}") success = compileall.compile_dir(project_dir, force=True) if success: print("✅ 所有 .py 檔案已成功編譯為 .pyc") else: print("❌ 編譯時發生錯誤,請檢查原始碼")

📌 使用方法:

bash
python compile_all.py
  • 會遞迴編譯所有子目錄 .py 檔,產生 .pyc__pycache__/ 中。


🧱 3. 打包成 EXE:使用 pyinstaller

📦 安裝 PyInstaller

bash
pip install pyinstaller

🛠️ CLI 工具打包(有命令列視窗)

bash
pyinstaller -F main.py

🖼️ GUI 程式打包(無命令列視窗)

bash
pyinstaller -F -w main.py
  • 產出在 dist/main.exe

  • 若有資源檔案、圖示可用:

    bash
    pyinstaller -F -w --icon=myicon.ico main.py

📁 補充:.pyc 編譯後的位置與命名

若你有這個檔案:

my_project/ └── utils.py

編譯後會產生這個:

markdown
my_project/ └── __pycache__/ └── utils.cpython-311.pyc ← Python 3.11 的編譯版本

📝 小提醒

  • .pyc 只是提高模組載入速度,不會加速運算執行效能

  • 若你要保護原始碼但又不想打包 .exe,只釋出 .pyc 是個折衷方案。

  • GUI 用 .pyw 啟動 .pyc 可以避免跳出 DOS 視窗。

沒有留言: