Home PyInstaller 打包 python App (中文)
Post
Cancel

PyInstaller 打包 python App (中文)

PyInstaller

python 有很多非常便利的地方和很強大的模組,因此很多人都會使用 python 寫些小工具。但是,如果寫完後,如果要給其他人用,那該怎麼辦? 在其他的電腦上裝 python ? 太麻煩了。pyinstaller 可以解決這樣的問題!!

PyInstaller 是一個將 Python 應用程序打包成獨立可執行文件的工具。它支持 Windows、Linux 和 macOS。

下面我將介紹 PyInstaller 的基本使用方式以及一些常見選項。

我們直接示範打包過程吧

無 GUI 的應用

以下有兩個 py, main import MyClass 使用

my_class.py

1
2
3
4
5
class MyClass():
    def __init__(self, name):
        self.name = name
    def showName(self):
        print(self.name)

main.py

1
2
3
4
5
6
from my_class import MyClass

obj = MyClass("ABC")
obj.showName()

input("Wait for user input")

使用以下指令打包

1
pyinstaller --onefile --name myapp --add-data "my_class.py:." main.py

Desktop View

執行結果

Desktop View

有 GUI 的應用

以下的 code 示範使用 python 中最常用的 matplotilb 去化簡單的圖

1
2
3
4
5
6
7
8
9
10
11
# main.py
import matplotlib.pyplot as plt

def main():
    # 繪製簡單的圖表
    plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
    plt.title('Simple Plot')
    plt.show()

if __name__ == "__main__":
    main()

使用指令

打包腳本: 使用 –onefile 和 –noconsole 選項打包你的腳本

1
pyinstaller --onefile --noconsole main.py

比較特別的就是 --noconsole ,說明你的應用沒有 console 的使用。

打包完成生成執行檔

Desktop View

執行結果

Desktop View

說明

假設你的文件結構(都在資料夾同一層):

  1. main.py
  2. module1.py
  3. module2.py
  4. myicon.ico
  5. config.txt

你希望將這些文件打包成一個單獨的可執行文件,並添加圖標和隱藏控制台窗口。可以使用以下命令:

1
pyinstaller --onefile --icon=myicon.ico --noconsole --add-data "module1.py:." --add-data "module2.py:." --add-data "config.txt:." main.py

眼尖的人可能發現,打包完成後,資料夾內會多了一個 main.spec(會根據你的設定檔名不同)

main.spec 的內容可以讓你更精細的控制打包的過程,修改 main.spec 後 可直接使用以下指令去打包

1
pyinstaller main.spec

以上!

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍