python程序打包成可执行文件

1 场景

python是一种脚本语言。运行环境安装python环境,并且安装程序相关依赖包的情况下,源码可直接运行

大部分情况下,开发者不希望源码被运行者看到,并且不想再程序执行环境安装python环境和安装依赖包,希望直接将python程序打包成可执行文件,直接在运行环境执行。

2 方案

采用pyinstallerpython程序依赖环境一起打包成可执行程序。

2.1 官网

http://www.pyinstaller.org

2.2 注意事项

pyinstaller针对不同平台(windows、linux...),需要打包成不同平台可执行文件

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 常用参数

4.1 常用参数

参数 参数说明
-F, --onefile 创建单个可执行文件
-D, --onedir 产生一个目录(包含多个文件)作为可执行程序(默认参数
-p DIR, --paths DIR 添加搜索路径,让其找到对应的库,可以为多个值。(和使用PYTHONPATH效果相似,建议加上此参数,否则可能依赖包无法打包
--distpath DIR 生成文件的路径,默认为.\dist
--clean 打包之前,删除之前打包的目录(建议加上,免去手动删除之前编译生成的目录

3 打包可执行程序

当前操作系统:win10,运行后生成exe程序。同理,linux可执行程序,需要在linux环境下生成。

3.1 打包成单个文件

执行命令:

pyinstaller -F xxx.py --clean

命令目录下将生成如下文件和文件夹:

__pycache__ #缓存目录,存储的pyc格式的编译后的程序,有python和依赖包的环境,可以直接执行
build #打包过程的目录,其中存储了打包过程的相关日志和配置
dist #打包结果目录,对应生成的xxx.exe程序
baiduVoiceToZip.spec #打包配置文件,可手动编写,通过其他方式打包

文件夹dist中存储了打包生成的exe文件,命名和主python脚本的名字一致,如xxx.exe。

如python程序有其他依赖配置文件需手动将配置文件,拷贝到.exe目录下,直接发布到其他环境执行即可。

参数--clean用于删除之前打包生成的相关文件

3.2 指定包路径

打包文件时,可手动指定python的本地安装依赖包的路径:

和使用PYTHONPATH效果相似,建议加上此参数,否则可能依赖包无法打包

pyinstaller -F -p "D:\Program Files\Python\Python36\Lib\site-packages;" xxx.py

打包生成结果,仍然为单个.exe文件

3.3 生成一个执行目录

执行如下命令:

pyinstaller xxx.py

或:

pyinstaller -D xxx.py

执行完毕后,生成的目录dist中,将生成一个入口执行脚本同名的文件夹xxx,文件夹内,仍有一个执行脚本同名的.exe文件xxx.exe。双击即可执行。发布项目时,需将整个文件夹拷贝到执行环境中,不可只拷贝exe文件。

同样的,如果有外部配置文件等文件也需要手动拷贝到指定目录

4 扩展

4.1 原理简介

PyInstaller 输入你指定的的脚本,首先分析脚本所依赖的其他脚本,然后去查找,复制,把所有相关的脚本收集起来,包括 Python 解析器,然后把这些文件放在一个目录下,或者打包进一个可执行文件里面。

因此,只需要在命令中指定入口程序脚本即可。

4.2 执行变慢

PyInstaller 是将“解释器”、“程序脚本”、“程序依赖包”打成了可执行文件。并非二进制文件,执行速度有可能比直接解释执行脚本文件要慢

4.3 编码建议

打包时,会将程序中依赖的包打包到程序中,因此需注意以下情况:

(1)如果包没有用到,不要在程序中引入,即需要删除程序中不需要的包引用。

(2)代码里尽量不要直接用import,优先用from xxx import yyy这种格式,尽量不要将整个外部包都引入进来,缩小引入包的范围。

4.4 打包前注意事项

打包前,如之前已经打包过,建议清理之前打包生成的文件及文件夹,否则,打包可能出现问题。

命令中可加上参数--clean来实现此功能。

4.5 帮助信息

执行以下命令,查看完整帮助信息:

pyinstaller -h

输出帮助内容:

usage: pyinstaller [-h] [-v] [-D] [-F] [--specpath DIR] [-n NAME]
                   [--add-data ]
                   [--add-binary ] [-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 ]
                   [--version-file FILE] [-m ] [-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 
                        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 
                        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 , --icon 
                        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 , --manifest 
                        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.

你可能感兴趣的:(python程序打包成可执行文件)