python打包可執行文件詳解(pyinstaller)
- 基本使用
- 常用參數及使用
- 全部參數及使用
- 常規選項 optional arguments
- 幫助 -h / --help
- 版本 -v / --version
- 設置exe生成位置 --distpath
- 設置中間文件位置 --workpath
- 詢問dist覆蓋意見 -y / --noconfirm
- 壓縮文件 --upx-dir
- 編碼模式 -a / --ascii
- 刪除緩存 --clean
- 打包顯示信息量 --log-level
- 產生什麼 What to generate
- 捆綁與搜索的地址 What to bundle, where to search
- 怎樣生成 How to generate
- 關於我在打包過程中遇到的問題
- 幫助信息 -h/--help
基本使用
安裝pyinstaller
pip install pyinstaller
命令行到達.py文件位置
cd D:\code
把zzz.py打包成exe文件(非獨立)
pyinstaller zzz.py
完成後生成三個文件夾“__pycache__”(緩存)、“build”(臨時文件)、“dist”(生成文件)和 一個文件“zzz.spec”(配置文件)
默認-D模式打成文件夾
打完包的exe在名爲"dist"文件夾下的“zzz”文件夾內,如果要給別人用,需要把整個"zzz"文件夾都打包送走
常用參數及使用
單個文件打包 -F
pyinstaller -F zzz.py
打完包的exe在"dist"文件夾下,可以直接運行
隱藏命令行運行窗口 -w
隱藏黑框框
pyinstaller -w zzz.py
如果寫了類似system pause之類的,那麼還是會出現命令行告訴你按任意鍵結束
和-F一起使用風味更佳
pyinstaller -F -w zzz.py
設置圖標 -i
-i後面一個空格加圖片地址,建議放在同一文件夾下,比較方便打個文件名就行了
pyinstaller -F -i pic.ico zzz.py
如果發現生成的exe圖標還是黑藍黃白的方框小蟒蛇,可以把exe複製黏貼一次,圖標就神奇的出現了
全部參數及使用
按照幫助信息順序嘗試後得出
因爲太麻煩,不包含任何需要其他程序輔助的功能,比如upx壓縮功能之類的,但是提供翻譯
常規選項 optional arguments
幫助 -h / --help
顯示pyinstaller的幫助信息,我複製下來放在最後一個大標題了
版本 -v / --version
顯示pyinstaller的版本
任何的pyinstaller加上它,都只顯示版本信息
比如下面這幾條,只顯示版本信息
pyinstaller -F -i pic.ico -v zzz.py
pyinstaller 6666-F -v 1.1.2 zzz.py 23333333333333
設置exe生成位置 --distpath
更改exe生成的位置
這裏我改成在當前文件夾下的”anotherpath“文件夾來存放生成的exe
pyinstaller -F -i icon04.ico --distpath .\anotherpath zzz.py
設置中間文件位置 --workpath
pyinstaller也不是直接一步到位打包完的,有許多中間文件,之前是放在“build”文件夾下,現在你可以設置它的位置
這裏我改成放在“anotheranotherpath”文件夾裏
pyinstaller -F -i icon04.ico --workpath .\anotheranotherpath zzz.py
詢問dist覆蓋意見 -y / --noconfirm
如果你的exe生成位置已經存在東西,那麼在打包過程中會問你這麼一句話(在-F條件下不會問這個問題)
WARNING: The output directory “D:\Code\dist\zzz” and ALL ITS CONTENTS will be REMOVED! Continue? (y/N)
大意是文件夾裏已經有東西了,要不要覆蓋他們呢?
如果加了-y那麼該情況下就不會問這個問題,直接覆蓋,比如下面這樣
pyinstaller -y zzz.py
壓縮文件 --upx-dir
用upx壓縮可執行文件,生成文件會比不壓縮的要小
沒試過
pyinstaller -F --upx-dir UPX_DIR zzz.py
編碼模式 -a / --ascii
不支持unicode編碼
沒試出來加不加有什麼區別,可能自動優化了?
留個空______________
刪除緩存 --clean
刪除pyinstaller的緩存和之前的臨時文件
假如依次執行一下三條
pyinstaller -F zzz.py
pyinstaller -F zzz.py
pyinstaller -F --clean zzz.py
你會發現第二條非常快,因爲它直接使用了第一條運行時產生的臨時文件,而第三條和第一條的執行速度差不多,因爲第三條將臨時文件刪除,自己重新再產生了,從執行時的信息也能看出,一三兩條明顯步驟更多
打包顯示信息量 --log-level
控制打包時控制檯的詳細信息量
在你的程序打包時出錯,然後消息太多,找不到報錯提示的時候比較有用
pyinstaller -F --clean --log-level LEVEL zzz.py
LEVEL的取值爲(DEBUG,INFO,WARN,ERROR,CRITICAL(默認值:INFO))
DEBUG會比INFO多更多的調試信息
WARN只顯示警告信息
ERROR只顯示錯誤信息
CRITICAL這個我還沒遇到過,緊急信息?留個空______________
產生什麼 What to generate
分散打包 -D/–onedir
前面提過,就默認的模式
單個文件 -F/–onefile
前面提過,打成單個文件
規範文件位置 --spacepath
設置用於存儲生成的規範文件(就是py文件同目錄下的.spec文件,主要存儲打包的設置)的文件夾
比如我這麼寫,.spec文件就會存儲到同目錄下的aaa文件夾下
pyinstaller -F --clean --specpath aaa zzz.py
改名 -n/–name
修改可執行文件的名字(默認是.py文件的名字)
比如
pyinstaller -F --clean -n hhh zzz.py
那麼build和dist文件夾下zzz的位置都會變成hhh,但是緩存文件的名字(__pycache__文件夾下)不會變
捆綁與搜索的地址 What to bundle, where to search
主要是用於打包的時候找不到庫
怎樣生成 How to generate
關於我在打包過程中遇到的問題
找不到nltk_data的位置
報錯是
Unable to find “C:\nltk_data” when adding binary and data files
一開始我真的以爲他提示的地方必須有nltkdata,就傻乎乎把所有報錯的位置都粘了一份nltk_data,直到第六個我才發現不對勁啊
解決方法
在你的pyinstaller安裝目錄(比如:D:\Anaconda\Lib\site-packages\PyInstaller\hooks)下找到一個叫“hook-nltk.py”的文件,打開更改
# loop through the data directories and add them
for p in nltk.data.path:
datas.append((p, “nltk_data”))
爲
# loop through the data directories and add them
datas.append((“NLTK_DATA_PATH”, “nltk_data”))
NLTK_DATA_PATH是你存放nltk_data的位置(比如:D:\Anaconda\Lib\site-packages\nltk\nltk_data)
打包後的exe報錯找不到模組
報錯信息是
ModuleNotFoundError: No module named ‘pkg_resources.py2_warn’
因爲我打包的程序運行時間比較長,所以一開始一直沒看到報錯信息,就知道過了很久莫名其妙閃退了,但是在編譯器裏運行一切正常
解決辦法
這裏推薦開另外一個命令行來運行exe,這樣就不會閃退看不到報錯
(曾經我也是會拍視頻來捕捉閃退的傻孩子啊)
(ps:如果時通過os.path讀取文件的,要先把另一個命令行的位置cd到程序所在的地址,不然os.path讀取的會是那個命令行的位置,VSCode的控制檯也是)
打開.spec文件,修改
hiddenimports=[],
爲
hiddenimports=[‘MODULE_NAME’],
MODULE_NAME填你缺失的模組名,缺失很多模組那麼就逗號隔開
打包時提示超過最大遞歸層數
原因大概是用的一個庫自己循環、遞歸太多了,超過python的默認棧深度,一般在IDE裏運行沒事兒,打包的時候會出錯
報錯信息是
RecursionError: maximum recursion depth exceeded while calling a Python object
解決辦法
打開.spec文件,在
# -*- mode: python ; coding: utf-8 -*-
的下一行,添加
import sys
sys.setrecursionlimit(1000000000)
意思是設置最大遞歸深度爲1000000000,這個數字隨你設置,稍微大一點就行,默認大小是1000
這兩行直接加載代碼裏會讓運行速度變快,類似於電腦增加了內存的感覺
但是加載代碼裏並不會在打包的時候生效,照樣報錯,所以一定要加載打包的配置文件裏。
編碼錯誤
錯誤提示
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xce in position 109: invalid continuation byte
解決方法
修改pyinstaller安裝目錄下的compat.py文件(這個文件的內容是處理各種兼容問題的,比如python2和python3的不同之類的,所以啥小事都要管)中的
out = out.decode(encoding)
爲
out = out.decode(encoding, errors=‘ignore’)
向我一樣用Anaconda的話,這個目錄在
D:\Anaconda\Lib\site-packages\PyInstaller
找不到的話在努力找找吧,或者下一個Everything查一下
幫助信息 -h/–help
usage: pyinstaller [-h] [-v] [-D] [-F] [--specpath DIR] [-n NAME]
[--add-data <SRC;DEST or SRC:DEST>]
[--add-binary <SRC;DEST or SRC:DEST>] [-p DIR]
[--hidden-import MODULENAME]
[--additional-hooks-dir HOOKSPATH]
[--runtime-hook RUNTIME_HOOKS] [--exclude-module EXCLUDES]
[--key KEY] [-d {all,imports,bootloader,noarchive}] [-s]
[--noupx] [--upx-exclude FILE] [-c] [-w]
[-i <FILE.ico or FILE.exe,ID or FILE.icns>]
[--version-file FILE] [-m <FILE or XML>] [-r RESOURCE]
[--uac-admin] [--uac-uiaccess] [--win-private-assemblies]
[--win-no-prefer-redirects]
[--osx-bundle-identifier BUNDLE_IDENTIFIER]
[--runtime-tmpdir PATH] [--bootloader-ignore-signals]
[--distpath DIR] [--workpath WORKPATH] [-y]
[--upx-dir UPX_DIR] [-a] [--clean] [--log-level LEVEL]
scriptname [scriptname ...]
positional arguments:
scriptname name of scriptfiles to be processed or exactly one
.spec-file. If a .spec-file is specified, most options
are unnecessary and are ignored.
optional arguments:
-h, --help show this help message and exit
-v, --version Show program version info and exit.
--distpath DIR Where to put the bundled app (default: .\dist)
--workpath WORKPATH Where to put all the temporary work files, .log, .pyz
and etc. (default: .\build)
-y, --noconfirm Replace output directory (default:
SPECPATH\dist\SPECNAME) without asking for
confirmation
--upx-dir UPX_DIR Path to UPX utility (default: search the execution
path)
-a, --ascii Do not include unicode encoding support (default:
included if available)
--clean Clean PyInstaller cache and remove temporary files
before building.
--log-level LEVEL Amount of detail in build-time console messages. LEVEL
may be one of TRACE, DEBUG, INFO, WARN, ERROR,
CRITICAL (default: INFO).
What to generate:
-D, --onedir Create a one-folder bundle containing an executable
(default)
-F, --onefile Create a one-file bundled executable.
--specpath DIR Folder to store the generated spec file (default:
current directory)
-n NAME, --name NAME Name to assign to the bundled app and spec file
(default: first script's basename)
What to bundle, where to search:
--add-data <SRC;DEST or SRC:DEST>
Additional non-binary files or folders to be added to
the executable. The path separator is platform
specific, ``os.pathsep`` (which is ``;`` on Windows
and ``:`` on most unix systems) is used. This option
can be used multiple times.
--add-binary <SRC;DEST or SRC:DEST>
Additional binary files to be added to the executable.
See the ``--add-data`` option for more details. This
option can be used multiple times.
-p DIR, --paths DIR A path to search for imports (like using PYTHONPATH).
Multiple paths are allowed, separated by ';', or use
this option multiple times
--hidden-import MODULENAME, --hiddenimport MODULENAME
Name an import not visible in the code of the
script(s). This option can be used multiple times.
--additional-hooks-dir HOOKSPATH
An additional path to search for hooks. This option
can be used multiple times.
--runtime-hook RUNTIME_HOOKS
Path to a custom runtime hook file. A runtime hook is
code that is bundled with the executable and is
executed before any other code or module to set up
special features of the runtime environment. This
option can be used multiple times.
--exclude-module EXCLUDES
Optional module or package (the Python name, not the
path name) that will be ignored (as though it was not
found). This option can be used multiple times.
--key KEY The key used to encrypt Python bytecode.
How to generate:
-d {all,imports,bootloader,noarchive}, --debug {all,imports,bootloader,noarchive}
Provide assistance with debugging a frozen
application. This argument may be provided multiple
times to select several of the following options.
- all: All three of the following options.
- imports: specify the -v option to the underlying
Python interpreter, causing it to print a message
each time a module is initialized, showing the
place (filename or built-in module) from which it
is loaded. See
https://docs.python.org/3/using/cmdline.html#id4.
- bootloader: tell the bootloader to issue progress
messages while initializing and starting the
bundled app. Used to diagnose problems with
missing imports.
- noarchive: instead of storing all frozen Python
source files as an archive inside the resulting
executable, store them as files in the resulting
output directory.
-s, --strip Apply a symbol-table strip to the executable and
shared libs (not recommended for Windows)
--noupx Do not use UPX even if it is available (works
differently between Windows and *nix)
--upx-exclude FILE Prevent a binary from being compressed when using upx.
This is typically used if upx corrupts certain
binaries during compression. FILE is the filename of
the binary without path. This option can be used
multiple times.
Windows and Mac OS X specific options:
-c, --console, --nowindowed
Open a console window for standard i/o (default). On
Windows this option will have no effect if the first
script is a '.pyw' file.
-w, --windowed, --noconsole
Windows and Mac OS X: do not provide a console window
for standard i/o. On Mac OS X this also triggers
building an OS X .app bundle. On Windows this option
will be set if the first script is a '.pyw' file. This
option is ignored in *NIX systems.
-i <FILE.ico or FILE.exe,ID or FILE.icns>, --icon <FILE.ico or FILE.exe,ID or FILE.icns>
FILE.ico: apply that icon to a Windows executable.
FILE.exe,ID, extract the icon with ID from an exe.
FILE.icns: apply the icon to the .app bundle on Mac OS
X
Windows specific options:
--version-file FILE add a version resource from FILE to the exe
-m <FILE or XML>, --manifest <FILE or XML>
add manifest FILE or XML to the exe
-r RESOURCE, --resource RESOURCE
Add or update a resource to a Windows executable. The
RESOURCE is one to four items,
FILE[,TYPE[,NAME[,LANGUAGE]]]. FILE can be a data file
or an exe/dll. For data files, at least TYPE and NAME
must be specified. LANGUAGE defaults to 0 or may be
specified as wildcard * to update all resources of the
given TYPE and NAME. For exe/dll files, all resources
from FILE will be added/updated to the final
executable if TYPE, NAME and LANGUAGE are omitted or
specified as wildcard *.This option can be used
multiple times.
--uac-admin Using this option creates a Manifest which will
request elevation upon application restart.
--uac-uiaccess Using this option allows an elevated application to
work with Remote Desktop.
Windows Side-by-side Assembly searching options (advanced):
--win-private-assemblies
Any Shared Assemblies bundled into the application
will be changed into Private Assemblies. This means
the exact versions of these assemblies will always be
used, and any newer versions installed on user
machines at the system level will be ignored.
--win-no-prefer-redirects
While searching for Shared or Private Assemblies to
bundle into the application, PyInstaller will prefer
not to follow policies that redirect to newer
versions, and will try to bundle the exact versions of
the assembly.
Mac OS X specific options:
--osx-bundle-identifier BUNDLE_IDENTIFIER
Mac OS X .app bundle identifier is used as the default
unique program name for code signing purposes. The
usual form is a hierarchical name in reverse DNS
notation. For example:
com.mycompany.department.appname (default: first
script's basename)
Rarely used special options:
--runtime-tmpdir PATH
Where to extract libraries and support files in
`onefile`-mode. If this option is given, the
bootloader will ignore any temp-folder location
defined by the run-time OS. The ``_MEIxxxxxx``-folder
will be created here. Please use this option only if
you know what you are doing.
--bootloader-ignore-signals
Tell the bootloader to ignore signals rather than
forwarding them to the child process. Useful in
situations where e.g. a supervisor process signals
both the bootloader and child (e.g. via a process
group) to avoid signalling the child twice.
持續更新。。。