1 場景
python是一種腳本語言。運行環(huán)境安裝python環(huán)境,并且安裝程序相關(guān)依賴包的情況下,源碼可直接運行。
大部分情況下,開發(fā)者不希望源碼被運行者看到,并且不想再程序執(zhí)行環(huán)境安裝python環(huán)境和安裝依賴包,希望直接將python程序打包成可執(zhí)行文件,直接在運行環(huán)境執(zhí)行。
2 方案
采用pyinstaller將python程序和依賴環(huán)境一起打包成可執(zhí)行程序。
2.1 官網(wǎng)
2.2 注意事項
pyinstaller針對不同平臺(windows、linux...),需要打包成不同平臺的可執(zhí)行文件。
2.3 安裝
pip install pyinstaller
pyinstaller安裝時,會一同安裝其他依賴包,建議pip在線安裝。安裝成功后,在控制臺輸出一起安裝的包。提示如下:
Successfully installed altgraph-0.17 future-0.18.2 pefile-2019.4.18 pyinstaller-3.6 pywin32-ctypes-0.2.0
2.4 常用參數(shù)
4.1 常用參數(shù)
| 參數(shù) | 參數(shù)說明 |
|---|---|
| -F, --onefile | 創(chuàng)建單個可執(zhí)行文件 |
| -D, --onedir | 產(chǎn)生一個目錄(包含多個文件)作為可執(zhí)行程序(默認(rèn)參數(shù)) |
| -p DIR, --paths DIR | 添加搜索路徑,讓其找到對應(yīng)的庫,可以為多個值。(和使用PYTHONPATH效果相似,建議加上此參數(shù),否則可能依賴包無法打包) |
| --distpath DIR | 生成文件的路徑,默認(rèn)為.\dist
|
| --clean | 打包之前,刪除之前打包的目錄(建議加上,免去手動刪除之前編譯生成的目錄) |
3 打包可執(zhí)行程序
當(dāng)前操作系統(tǒng):win10,運行后生成exe程序。同理,linux可執(zhí)行程序,需要在linux環(huán)境下生成。
3.1 打包成單個文件
執(zhí)行命令:
pyinstaller -F xxx.py --clean
命令目錄下將生成如下文件和文件夾:
__pycache__ #緩存目錄,存儲的pyc格式的編譯后的程序,有python和依賴包的環(huán)境,可以直接執(zhí)行
build #打包過程的目錄,其中存儲了打包過程的相關(guān)日志和配置
dist #打包結(jié)果目錄,對應(yīng)生成的xxx.exe程序
baiduVoiceToZip.spec #打包配置文件,可手動編寫,通過其他方式打包
文件夾dist中存儲了打包生成的exe文件,命名和主python腳本的名字一致,如xxx.exe。
如python程序有其他依賴配置文件,需手動將配置文件,拷貝到.exe目錄下,直接發(fā)布到其他環(huán)境執(zhí)行即可。
參數(shù)--clean用于刪除之前打包生成的相關(guān)文件
3.2 指定包路徑
打包文件時,可手動指定python的本地安裝依賴包的路徑:
和使用PYTHONPATH效果相似,建議加上此參數(shù),否則可能依賴包無法打包
pyinstaller -F -p "D:\Program Files\Python\Python36\Lib\site-packages;" xxx.py
打包生成結(jié)果,仍然為單個.exe文件
3.3 生成一個執(zhí)行目錄
執(zhí)行如下命令:
pyinstaller xxx.py
或:
pyinstaller -D xxx.py
執(zhí)行完畢后,生成的目錄dist中,將生成一個入口執(zhí)行腳本同名的文件夾xxx,文件夾內(nèi),仍有一個執(zhí)行腳本同名的.exe文件xxx.exe。雙擊即可執(zhí)行。發(fā)布項目時,需將整個文件夾拷貝到執(zhí)行環(huán)境中,不可只拷貝exe文件。
同樣的,如果有外部配置文件等文件,也需要手動拷貝到指定目錄。
4 擴展
4.1 原理簡介
PyInstaller 輸入你指定的的腳本,首先分析腳本所依賴的其他腳本,然后去查找,復(fù)制,把所有相關(guān)的腳本收集起來,包括 Python 解析器,然后把這些文件放在一個目錄下,或者打包進(jìn)一個可執(zhí)行文件里面。
因此,只需要在命令中指定入口程序腳本即可。
4.2 執(zhí)行變慢
PyInstaller 是將“解釋器”、“程序腳本”、“程序依賴包”打成了可執(zhí)行文件。并非二進(jìn)制文件,執(zhí)行速度有可能比直接解釋執(zhí)行腳本文件要慢。
4.3 編碼建議
打包時,會將程序中依賴的包打包到程序中,因此需注意以下情況:
(1)如果包沒有用到,不要在程序中引入,即需要刪除程序中不需要的包引用。
(2)代碼里盡量不要直接用import,優(yōu)先用from xxx import yyy這種格式,盡量不要將整個外部包都引入進(jìn)來,縮小引入包的范圍。
4.4 打包前注意事項
打包前,如之前已經(jīng)打包過,建議清理之前打包生成的文件及文件夾,否則,打包可能出現(xiàn)問題。
命令中可加上參數(shù)--clean來實現(xiàn)此功能。
4.5 幫助信息
執(zhí)行以下命令,查看完整幫助信息:
pyinstaller -h
輸出幫助內(nèi)容:
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.