pyinstaller 是python的一個打包工具,可以將python源文件打包成exe(windows系統)可執行程序。
安裝方法:
pip install pyinstaller
以hello.py舉例
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 16:26:58 2020
@author: matrix273
"""
print('Hello World!')
普通的打包方法爲
pyinstaller hello.py #打包到文件夾
以這種無參數方式打包的程序包含在 \dist\hello 目錄下,個人更傾向於添加 "-F"參數來打包到一個文件,即
pyinstaller -F hello.py #打包爲一個文件
在測試時發現雙擊運行打包的 hello.exe會一閃而過,特別是需要調試程序時,不能看到報錯排查起來比較麻煩,針對此,有兩個思路.
1:給python程序添加一個 input() 等待外部輸入的命令.這樣窗口就會等待鍵盤輸入.這樣就不會一閃而過.類似這樣:
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 16:26:58 2020
@author: matrix273
"""
print('Hello World!')
input()
2:在命令提示符裏面運行hello.py,這樣可以獲得所有輸出而不用擔心太快看不到報錯的問題.
進階部分:
1:添加外部文件
但是個別時候我們的代碼需要調用外部的文件,爲了打包後的程序在其他電腦可用,需要把這些外部文件一併打包.這裏需要一個函數來定位外部文件的位置
import os #導入os包
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
將這個函數放在讀取外部文件之前,且將外部文件的路徑修改爲 resource_path('external_file'),這樣打包後的文件就可以找到外部文件了,同時打包時需要添加額外的參數: --add-data external_file;.(注意後面有兩個符號一個分號";",一個點"." ,linux系統替換爲一個冒號":",一個點".")
pyinstaller -F hello.py --add-data external_file;.
相關幫助如下圖
2:修改默認程序圖標
打包時添加一個 -i icon.ico 參數,即
pyinstaller -F -i icon.ico hello.py
3,添加版本信息
這裏需要另外一個pyinstaller自帶的grab_version.py來獲取版本信息.查看的這個程序所在的路徑方法如下:
pip show pyinstaller
通過下圖得知pyinstaller包的路徑在 C:\ProgramData\Anaconda3\Lib\site-packages,對應的grab_version.py文件在:
C:\ProgramData\Anaconda3\Lib\site-packages\PyInstaller\utils\cliutils\grab_version.py
我們可以把grab_version.py複製到當前文件夾下,然後獲取一個包含版本信息的 exe程序文件的信息,然後修改爲自己的版本.
比如獲取chrome.exe的版本信息
python grab_version.py chrome.exe
操作如下圖:
修改file_version_info.txt爲自己想要的信息.然後在打包時添加參數 --version-file file_version_info.txt 即可完成添加版本信息
pyinstaller -F hello.py -i chrome.exe --version-file file_version_info.txt
通過上面的命令就可以打包一個包含chrome.exe 圖標以及版本信息的 hello.py文件
以上就是pyinstaller的常用操作,記錄一下,同時分享給有需要的同學.