博主首先參考了網上介紹的各種打包插件,只有三種被提及的比較多:
- pyinstaller
- py2exe
- cxfreeze
考慮到軟件運行的多平臺性,我首先使用了pyinstaller,可以在命令行通過pip install pyinstaller 安裝該插件
遺憾的是安裝過程很順利,打包的時候卻無法將腳本中導入的一些自定義本地模塊相應的提取爲依賴文件,例如自己寫的utils工具類,導致打包出來的exe文件因缺少模塊無法正確運行,閃退。谷歌百度無果,遂放棄。
失敗後我用到了cxfreeze,因爲相比較py2exe該插件始終持續更新:
pip安裝之後在本地的 Python27 下 Scripts 文件夾中缺少 cxfreeze.bat 文件,雖然已經將 Scripts路徑添加至系統環境變量 Path 中,依然無法找到 cxfreeze 命令
於是我在該文件夾下自行添加了一個 cxfreeze.bat 文件,用記事本編輯內容爲:
@ echo off
C:\Python27\python.exe C:\Python27\Scripts\cxfreeze %*
繼續運行 cxfeeze 命令,提示安裝成功。(此處是我自己的安裝路徑)
接着輸入命令進行打包:
cxfreeze D:\hello.py F:\666 dist
D盤下爲打包文件,F盤下爲存放exe的位置,如果希望打包成單個文件,可以選中所有文件右擊自解壓
問題在於打包好的exe文件夾大小過大,導入很多沒有必要的依賴文件,需要手動刪除,不是很方便
折騰了半天,最後還是選擇了py2exe:
如果通過 pip 源安裝報錯,可能是因爲python版本過低,可以選擇網上搜索2.7的exe安裝包
與之前不同的是,使用py2exe打包程序,需要準備一個setup.py文件放在需要打包的py文件相同目錄下,內容爲:
# coding=utf-8
from distutils.core import setup
import py2exe
options = {"py2exe": { "compressed": 1,
"optimize": 0,
"ascii": 0,
"bundle_files": 3,# 參數1不支持64位
'dist_dir': "F:/666",
#'build_dir':"D:/test/dir",
"includes":["sip"],
}
}
setup(options = options,
zipfile=None,
console = [{"script":r'D:\hello.py'}]
# console後爲需要打包的文件的路徑
)
以下爲options對應的指令,根據情況設置:
optimize (-O) :optimization level, -O1 for “python -O”, -O2 for
“python -OO”, and -O0 (default) to disableexcludes (-e) : comma-separated list of modules to exclude
dll-excludes : comma-separated list of DLLs to exclude
ignores : comma-separated list of modules to ignore if they are not found
includes (-i) : comma-separated list of modules to include
packages (-p) : comma-separated list of packages to include
xref (-x) : create and show a module cross reference
bundle-files (-b) : bundle dlls in the zipfile or the exe. Valid levels are 1, 2, or 3 (default)
skip-archive : do not place Python bytecode files in an archive, put them directly in the file system
ascii (-a) : do not automatically include encodings and codecs
custom-boot-script : Python file that will be run when setting up the runtime environment
準備就緒後在控制檯執行命令:
python setup.py py2exe
需要注意的是,如果python版本是2.7,運行時可能會報錯,需要手動添加一個 MSVCR90.dll 文件至dist中或者與setup.py放一起,也可以直接在setup.py中設置:
from glob import glob
data_files = [(“Microsoft.VC90.CRT”, glob(r’C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT*.*’))]
setup(
data_files=data_files,
etc
)
詳情請點擊這裏
但是這還不夠,運行打包出來的exe時可能還是出現閃退現象,需要將 C:\Windows\system32 下的 python27.dll 手動拷貝進dist文件夾,此時再運行 exe 就不會有問題了,以上