Python打包工具 Pyinstaller使用教程(将.py以及Python解释器和相关库打包可执行文件)

您所在的位置:网站首页 电脑文件打包是什么意思呀 Python打包工具 Pyinstaller使用教程(将.py以及Python解释器和相关库打包可执行文件)

Python打包工具 Pyinstaller使用教程(将.py以及Python解释器和相关库打包可执行文件)

2024-07-13 04:52| 来源: 网络整理| 查看: 265

文章目录 pyinstaller历史背景工作原理使用方法简介使用方法详解(请仔细阅读help文档中文翻译)help文档help文档中文翻译 简单使用示例1. 编译打包2. 拷贝到目标系统3. 运行(遇到问题) 如何使用xxx.spec文件重新编译配置项示例配置项解释重编译步骤 使用pyinstaller注意事项 参考文章 在这里插入图片描述

pyinstaller

PyInstaller是一个用于将Python脚本打包成独立可执行文件的工具。它的原理是将Python脚本及其依赖的库、资源文件等打包成一个单独的可执行文件,使得在其他机器上运行时不需要安装Python解释器和相关库,即可直接运行。

历史背景

PyInstaller的历史背景可以追溯到2008年,当时由Hartmut Goebel开发并发布了第一个版本。随着Python的流行和应用场景的增多,打包Python脚本成为一个重要的需求。PyInstaller应运而生,为Python开发者提供了一种简单、方便的方式来将Python脚本打包成可执行文件。随着时间的推移,PyInstaller不断更新和改进,支持了更多的特性和功能,成为Python打包工具中的一员。

工作原理

PyInstaller的工作原理可以简单概括为以下几个步骤:

分析脚本:PyInstaller会分析Python脚本,识别出脚本中所引用的库和资源文件。

创建打包规范:根据分析结果,PyInstaller会生成一个打包规范文件,其中包含了脚本的依赖关系、资源文件等信息。

打包依赖库:PyInstaller会将脚本所依赖的库文件进行打包,这些库文件会被嵌入到可执行文件中。

生成可执行文件:根据打包规范和打包的依赖库,PyInstaller会生成一个独立的可执行文件,该文件包含了Python解释器、脚本代码和依赖的库文件。

运行可执行文件:生成的可执行文件可以在其他机器上直接运行,无需安装Python解释器和相关库。

使用方法简介

PyInstaller的使用可以分为以下几个步骤:

安装PyInstaller:首先,需要使用pip命令安装PyInstaller。在命令行中执行以下命令即可: pip install pyinstaller

注意:请按需将pip替换成pip3。

打包脚本:在命令行中进入到要打包的Python脚本所在的目录。然后执行以下命令: pyinstaller your_script.py

这将会在当前目录下生成一个dist文件夹,其中包含了打包后的可执行文件。

自定义打包选项:PyInstaller提供了一些选项,可以用来自定义打包过程。例如,可以使用--onefile选项将所有的依赖库打包成一个单独的可执行文件,而不是多个文件。可以使用--name选项指定生成的可执行文件的名称。可以使用--icon选项指定生成的可执行文件的图标文件等等。具体的选项可以通过执行pyinstaller --help命令查看。

处理依赖:有些情况下,PyInstaller可能无法自动识别脚本的所有依赖库,或者依赖库的路径不正确。这时,可以使用--hidden-import选项手动添加缺失的依赖库。例如:

pyinstaller --hidden-import your_module your_script.py

这将会将your_module添加为脚本的依赖库。

处理资源文件:如果脚本中使用了一些外部的资源文件(如图片、配置文件等),这些文件也需要被打包进可执行文件中。可以使用--add-data选项来指定资源文件的路径和在可执行文件中的相对路径。例如: pyinstaller --add-data "path/to/resource.png:resource" your_script.py

这将会将path/to/resource.png文件添加为资源文件,并在可执行文件中的resource目录下。

运行可执行文件:生成的可执行文件可以在其他机器上直接运行,无需安装Python解释器和相关库。只需双击可执行文件或在命令行中执行即可运行脚本。

这些是PyInstaller的基本使用方法。下面将讲述PyInstaller的高级功能和选项。

使用方法详解(请仔细阅读help文档中文翻译) help文档

我的系统是arm linux ubuntu20.04,pyinstaller版本是5.13.0,执行pyinstaller --help可获得pyinstaller帮助文档:

root@ubuntu:/# uname -a Linux ubuntu 5.10.104-tegra #1 SMP PREEMPT Wed Aug 10 20:17:07 PDT 2022 aarch64 aarch64 aarch64 GNU/Linux root@ubuntu:/# pyinstaller -v 5.13.0 root@ubuntu:/# pyinstaller --help usage: pyinstaller [-h] [-v] [-D] [-F] [--specpath DIR] [-n NAME] [--add-data ] [--add-binary ] [-p DIR] [--hidden-import MODULENAME] [--collect-submodules MODULENAME] [--collect-data MODULENAME] [--collect-binaries MODULENAME] [--collect-all MODULENAME] [--copy-metadata PACKAGENAME] [--recursive-copy-metadata PACKAGENAME] [--additional-hooks-dir HOOKSPATH] [--runtime-hook RUNTIME_HOOKS] [--exclude-module EXCLUDES] [--splash IMAGE_FILE] [-d {all,imports,bootloader,noarchive}] [--python-option PYTHON_OPTION] [-s] [--noupx] [--upx-exclude FILE] [-c] [-w] [-i ] [--disable-windowed-traceback] [--version-file FILE] [-m ] [--no-embed-manifest] [-r RESOURCE] [--uac-admin] [--uac-uiaccess] [--win-private-assemblies] [--win-no-prefer-redirects] [--argv-emulation] [--osx-bundle-identifier BUNDLE_IDENTIFIER] [--target-architecture ARCH] [--codesign-identity IDENTITY] [--osx-entitlements-file FILENAME] [--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, DEPRECATION, ERROR, FATAL (default: INFO). Also settable via and overrides the PYI_LOG_LEVEL environment variable. 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. Equivalent to supplying the ``pathex`` argument in the spec file. --hidden-import MODULENAME, --hiddenimport MODULENAME Name an import not visible in the code of the script(s). This option can be used multiple times. --collect-submodules MODULENAME Collect all submodules from the specified package or module. This option can be used multiple times. --collect-data MODULENAME, --collect-datas MODULENAME Collect all data from the specified package or module. This option can be used multiple times. --collect-binaries MODULENAME Collect all binaries from the specified package or module. This option can be used multiple times. --collect-all MODULENAME Collect all submodules, data files, and binaries from the specified package or module. This option can be used multiple times. --copy-metadata PACKAGENAME Copy metadata for the specified package. This option can be used multiple times. --recursive-copy-metadata PACKAGENAME Copy metadata for the specified package and all its dependencies. 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. --splash IMAGE_FILE (EXPERIMENTAL) Add an splash screen with the image IMAGE_FILE to the application. The splash screen can display progress updates while unpacking. 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. --python-option PYTHON_OPTION Specify a command-line option to pass to the Python interpreter at runtime. Currently supports "v" (equivalent to "--debug imports"), "u", and "W ". -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 has 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 this also triggers building a Mac OS .app bundle. On Windows this option is automatically set if the first script is a '.pyw' file. This option is ignored on *NIX systems. -i , --icon FILE.ico: apply the 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. If an image file is entered that isn't in the platform format (ico on Windows, icns on Mac), PyInstaller tries to use Pillow to translate the icon into the correct format (if Pillow is installed). Use "NONE" to not apply any icon, thereby making the OS show some default (default: apply PyInstaller's icon). This option can be used multiple times. --disable-windowed-traceback Disable traceback dump of unhandled exception in windowed (noconsole) mode (Windows and macOS only), and instead display a message that this feature is disabled. 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. --no-embed-manifest Generate an external .exe.manifest file instead of embedding the manifest into the exe. Applicable only to onedir mode; in onefile mode, the manifest is always embedded, regardless of this option. -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 that will request elevation upon application start. --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 specific options: --argv-emulation Enable argv emulation for macOS app bundles. If enabled, the initial open document/URL event is processed by the bootloader and the passed file paths or URLs are appended to sys.argv. --osx-bundle-identifier BUNDLE_IDENTIFIER Mac OS .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) --target-architecture ARCH, --target-arch ARCH Target architecture (macOS only; valid values: x86_64, arm64, universal2). Enables switching between universal2 and single-arch version of frozen application (provided python installation supports the target architecture). If not target architecture is not specified, the current running architecture is targeted. --codesign-identity IDENTITY Code signing identity (macOS only). Use the provided identity to sign collected binaries and generated executable. If signing identity is not provided, ad-hoc signing is performed instead. --osx-entitlements-file FILENAME Entitlements file to use when code-signing the collected binaries (macOS only). 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 for example a supervisor process signals both the bootloader and the child (e.g., via a process group) to avoid signalling the child twice. root@ubuntu:/# help文档中文翻译 root@ubuntu:/# pyinstaller --help 用法: pyinstaller [-h] [-v] [-D] [-F] [--specpath DIR] [-n NAME] [--add-data ] [--add-binary ] [-p DIR] [--hidden-import MODULENAME] [--collect-submodules MODULENAME] [--collect-data MODULENAME] [--collect-binaries MODULENAME] [--collect-all MODULENAME] [--copy-metadata PACKAGENAME] [--recursive-copy-metadata PACKAGENAME] [--additional-hooks-dir HOOKSPATH] [--runtime-hook RUNTIME_HOOKS] [--exclude-module EXCLUDES] [--splash IMAGE_FILE] [-d {all,imports,bootloader,noarchive}] [--python-option PYTHON_OPTION] [-s] [--noupx] [--upx-exclude FILE] [-c] [-w] [-i ] [--disable-windowed-traceback] [--version-file FILE] [-m ] [--no-embed-manifest] [-r RESOURCE] [--uac-admin] [--uac-uiaccess] [--win-private-assemblies] [--win-no-prefer-redirects] [--argv-emulation] [--osx-bundle-identifier BUNDLE_IDENTIFIER] [--target-architecture ARCH] [--codesign-identity IDENTITY] [--osx-entitlements-file FILENAME] [--runtime-tmpdir PATH] [--bootloader-ignore-signals] [--distpath DIR] [--workpath WORKPATH] [-y] [--upx-dir UPX_DIR] [-a] [--clean] [--log-level LEVEL] scriptname [scriptname ...] 位置参数: scriptname 要处理的脚本文件的名称或者一个.spec文件。如果指定了.spec文件,则大多数选项都是不必要的,会被忽略。 可选参数: -h, --help 显示帮助信息并退出 -v, --version 显示程序版本信息并退出。 --distpath DIR 指定打包应用的目录(默认为./dist) --workpath WORKPATH 指定所有临时工作文件(.log, .pyz等)的目录(默认为./build) -y, --noconfirm 替换输出目录(默认为SPECPATH/dist/SPECNAME)而不需要确认 --upx-dir UPX_DIR UPX工具的路径(默认为搜索执行路径) -a, --ascii 不包含Unicode编码支持(默认情况下如果可用则包含) --clean 在构建之前清理PyInstaller缓存和临时文件。 --log-level LEVEL 构建时控制台消息的详细程度。LEVEL可以是TRACE、DEBUG、INFO、WARN、DEPRECATION、ERROR、FATAL之一(默认为INFO)。也可以通过PYI_LOG_LEVEL环境变量进行设置。 生成内容: -D, --onedir 创建一个包含可执行文件的单文件夹捆绑包(默认) -F, --onefile 创建一个单文件捆绑的可执行文件。 --specpath DIR 存储生成的.spec文件的文件夹(默认为当前目录) -n NAME, --name NAME 分配给捆绑应用和.spec文件的名称(默认为第一个脚本的基本名称) 捆绑什么,搜索什么: --add-data 添加到可执行文件的附加非二进制文件或文件夹。路径分隔符是平台特定的,使用``os.pathsep``(在Windows上为``;``,在大多数Unix系统上为``:``)。此选项可以多次使用。 --add-binary 添加到可执行文件的附加二进制文件。有关详细信息,请参见``--add-data``选项。此选项可以多次使用。 -p DIR, --paths DIR 搜索导入的路径(类似于使用PYTHONPATH)。可以使用多个路径,用``':'``分隔,或多次使用此选项。相当于在.spec文件中提供``pathex``参数。 --hidden-import MODULENAME, --hiddenimport MODULENAME 指定在脚本代码中不可见的导入模块。此选项可以多次使用。 --collect-submodules MODULENAME 收集指定包或模块的所有子模块。此选项可以多次使用。 --collect-data MODULENAME, --collect-datas MODULENAME 收集指定包或模块的所有数据文件。此选项可以多次使用。 --collect-binaries MODULENAME 收集指定包或模块的所有二进制文件。此选项可以多次使用。 --collect-all MODULENAME 收集指定包或模块的所有子模块、数据文件和二进制文件。此选项可以多次使用。 --copy-metadata PACKAGENAME 复制指定包的元数据。此选项可以多次使用。 --recursive-copy-metadata PACKAGENAME 复制指定包及其所有依赖项的元数据。此选项可以多次使用。 --additional-hooks-dir HOOKSPATH 指定额外的钩子路径。此选项可以多次使用。 --runtime-hook RUNTIME_HOOKS 指定自定义运行时钩子文件的路径。运行时钩子是与可执行文件捆绑在一起的代码,在任何其他代码或模块之前执行,用于设置运行时环境的特殊功能。此选项可以多次使用。 --exclude-module EXCLUDES 忽略的可选模块或包(Python名称,而不是路径名称)。此选项可以多次使用。 --splash IMAGE_FILE (实验性功能) 向应用程序添加一个带有图像IMAGE_FILE的启动画面。启动画面可以在解压过程中显示进度更新。 如何生成: -d {all,imports,bootloader,noarchive}, --debug {all,imports,bootloader,noarchive} 提供用于调试冻结应用程序的帮助。此参数可以多次提供以选择以下选项之一。 - all: 以下所有选项。 - imports: 指定-v选项给底层Python解释器,导致它在每次初始化模块时打印一条消息,显示加载模块的位置(文件名或内置模块)。参见 https://docs.python.org/3/using/cmdline.html#id4。 - bootloader: 告诉引导加载程序在初始化和启动捆绑应用程序时发出进度消息。用于诊断缺少导入的问题。 - noarchive: 将所有冻结的Python源文件存储为结果可执行文件内的存档,而不是文件存储在结果输出目录中。 --python-option PYTHON_OPTION 指定要在运行时传递给Python解释器的命令行选项。目前支持"v"(等效于"--debug imports")、"u"和"W"。 -s, --strip 对可执行文件和共享库应用符号表剥离(不推荐在Windows上使用) --noupx 即使可用,也不使用UPX(在Windows和*nix之间的工作方式不同) --upx-exclude FILE 使用upx时防止对二进制文件进行压缩。如果upx在压缩过程中破坏某些二进制文件,通常会使用此选项。FILE是二进制文件的文件名,不包含路径。此选项可以多次使用。 仅适用于Windows和Mac OS X的选项: -c, --console, --nowindowed 为标准输入/输出打开控制台窗口(默认)。在Windows上,如果第一个脚本是'.pyw'文件,则此选项无效。 -w, --windowed, --noconsole Windows和Mac OS X:不为标准输入/输出提供控制台窗口。在Mac OS上,这还会触发构建Mac OS .app包。在Windows上,如果第一个脚本是'.pyw'文件,则此选项会自动设置。在*NIX系统上,此选项将被忽略。 -i , --icon FILE.ico:将图标应用于Windows可执行文件。FILE.exe,ID:从exe中提取具有ID的图标。FILE.icns:将图标应用于Mac OS上的.app包。如果输入的图像文件不是平台格式(Windows上的ico,Mac上的icns),PyInstaller将尝试使用Pillow将图标转换为正确的格式(如果安装了Pillow)。使用"NONE"来不应用任何图标,从而使操作系统显示一些默认图标(默认:应用PyInstaller的图标)。此选项可以多次使用。 --disable-windowed-traceback 禁用窗口模式(noconsole)下未处理异常的回溯转储(仅适用于Windows和macOS),并显示一个消息,说明此功能已禁用。 Windows特定选项: --version-file FILE 从FILE中添加版本资源到exe。 -m , --manifest 将manifest FILE或XML添加到exe。 --no-embed-manifest 生成外部的.exe.manifest文件,而不是将manifest嵌入到exe中。仅适用于onedir模式;在onefile模式下,无论此选项如何,manifest始终被嵌入。 -r RESOURCE, --resource RESOURCE 向Windows可执行文件添加或更新资源。RESOURCE是一个到四个项目,FILE[,TYPE[,NAME[,LANGUAGE]]]。FILE可以是数据文件或exe/dll。对于数据文件,至少必须指定TYPE和NAME。LANGUAGE默认为0,或可以指定为通配符*以更新给定TYPE和NAME的所有资源。对于exe/dll文件,如果省略了或指定为通配符*,则将添加/更新来自FILE的所有资源到最终的可执行文件中。此选项可以多次使用。 --uac-admin 使用此选项创建一个Manifest,将在应用程序启动时请求提升。 --uac-uiaccess 使用此选项允许提升的应用程序与远程桌面一起工作。 Windows并行程序集搜索选项(高级): --win-private-assemblies 将任何捆绑到应用程序中的共享程序集更改为私有程序集。这意味着始终使用这些程序集的确切版本,并忽略用户机器上系统级安装的任何更新版本。 --win-no-prefer-redirects 在搜索要捆绑到应用程序中的共享或私有程序集时,PyInstaller将不倾向于遵循重定向到更新版本的策略,并尝试捆绑程序集的确切版本。 Mac OS特定选项: --argv-emulation 启用macOS应用程序包的argv模拟。如果启用,启动时的初始打开文档/URL事件将由引导加载程序处理,并将传递的文件路径或URL附加到sys.argv。 --osx-bundle-identifier BUNDLE_IDENTIFIER Mac OS .app包标识符用作默认的唯一程序名称,用于代码签名目的。通常的形式是反向DNS表示法中的分层名称。例如:com.mycompany.department.appname(默认值:第一个脚本的基本名称) --target-architecture ARCH, --target-arch ARCH 目标架构(仅适用于macOS;有效值:x86_64,arm64,universal2)。启用在冻结应用程序的universal2和单架构版本之间切换(前提是Python安装支持目标架构)。如果未指定目标架构,则针对当前运行的架构。 --codesign-identity IDENTITY 代码签名身份(仅适用于macOS)。使用提供的身份对收集的二进制文件和生成的可执行文件进行签名。如果未提供签名身份,则执行自动签名。 --osx-entitlements-file FILENAME 用于在签署收集的二进制文件时使用的权限文件(仅适用于macOS)。 很少使用的特殊选项: --runtime-tmpdir PATH 在`onefile`模式下提取库和支持文件的位置。如果给出此选项,引导加载程序将忽略运行时操作系统定义的任何临时文件夹位置。在此处将创建``_MEIxxxxxx``文件夹。请仅在您知道自己在做什么的情况下使用此选项。 --bootloader-ignore-signals 告诉引导加载程序忽略信号而不是将其转发给子进程。在某些情况下很有用,例如监督进程通过进程组向引导加载程序和子进程发送信号,以避免向子进程发送两次信号。 root@ubuntu:/# 简单使用示例 1. 编译打包

我有文件get_jtop_info.py,在文件所在目录执行pyinstaller get_jtop_info.py,会生成以下目录及文件:

在这里插入图片描述

root@ubuntu:/userdata/testKYAI/ky_get_device_info# ll total 24 drwxrwxrwx 4 nobody nogroup 4096 Jun 30 13:36 ./ drwxrwxrwx 5 nobody nogroup 4096 Jun 29 20:02 ../ drwxr-xr-x 3 root root 4096 Jun 30 13:36 build/ drwxr-xr-x 3 root root 4096 Jun 30 13:38 dist/ -rwxrwxrwx 1 nobody nogroup 2068 Jun 29 23:19 get_jtop_info.py* -rw-r--r-- 1 root root 912 Jun 30 13:36 get_jtop_info.spec root@ubuntu:/userdata/testKYAI/ky_get_device_info#

生成的各个目录和文件的作用如下:

build/:该目录是pyinstaller生成的临时目录,用于存放编译过程中生成的中间文件和临时文件。

在这里插入图片描述

dist/:该目录是pyinstaller生成的最终目录,用于存放编译后生成的可执行文件或打包后的应用程序。

可以看到我们生成的可执行文件:

在这里插入图片描述

xxx.spec:pyinstaller的配置文件,用于指定编译的参数和选项。可以通过修改该文件来自定义编译过程中的一些设置。

在这里插入图片描述

2. 拷贝到目标系统

有时我们编译可执行程序和运行可执行程序,不在同一台主机上。

如果要将生成的应用程序拷贝到目标系统运行,可以删除以下文件:

build/目录:该目录是编译过程中生成的临时目录,不需要在目标系统中运行应用程序时使用。

get_jtop_info.py:原始的Python脚本文件,生成的可执行文件已经包含了脚本的功能,所以可以删除该文件。

需要拷贝的文件包括:

dist/目录:该目录是生成的最终目录,包含了编译后生成的可执行文件或打包后的应用程序,需要将该目录完整地拷贝到目标系统。

get_jtop_info.spec:pyinstaller的配置文件,如果在目标系统中需要重新编译应用程序,可以将该文件一同拷贝过去。

3. 运行(遇到问题)

我把dist目录的get_jtop_info拷贝到目标目录:

在这里插入图片描述

在这里插入图片描述

然后我运行,怎么还报错了?提示找不到jtop

在这里插入图片描述 原因: jtop是一个隐藏模块,可能需要在打包过程中显式地导入该模块。可以使用--hidden-import jtop参数来指定需要导入的隐藏模块。

然后我用pyinstaller --onefile --hidden-import jtop ./get_jtop_info.py命令重新打包,但是还是报错:

在这里插入图片描述

尴尬了。。。

算了,就这样了,先不弄这个了,反正直接用python脚本也能跑。。。(20230630)

如何使用xxx.spec文件重新编译 配置项示例

以我的这个get_jtop_info.spec配置文件为例:

# -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis( ['get_jtop_info.py'], pathex=[], binaries=[], datas=[], hiddenimports=[], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False, ) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE( pyz, a.scripts, [], exclude_binaries=True, name='get_jtop_info', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=True, disable_windowed_traceback=False, argv_emulation=False, target_arch=None, codesign_identity=None, entitlements_file=None, ) coll = COLLECT( exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='get_jtop_info', ) 配置项解释

该.spec配置文件用于指定pyinstaller的编译参数和选项。下面是各个配置项的作用解释:

block_cipher:用于指定加密算法,如果不需要加密可以设置为None。

Analysis:分析器,用于指定需要编译的Python脚本文件、路径、二进制文件、数据文件等。

['get_jtop_info.py']:需要编译的Python脚本文件列表。

pathex=[]:额外的模块搜索路径。

binaries=[]:需要包含的二进制文件。

datas=[]:需要包含的数据文件。

hiddenimports=[]:需要导入的隐藏模块。

hookspath=[]:自定义的钩子文件路径。

hooksconfig={}:自定义的钩子配置。

runtime_hooks=[]:运行时钩子。

excludes=[]:需要排除的模块。

win_no_prefer_redirects=False:在Windows上禁用优先重定向。

win_private_assemblies=False:在Windows上使用私有程序集。

cipher=block_cipher:加密算法。

noarchive=False:是否生成归档文件。

PYZ:生成的Python字节码文件。

pyz:纯净的Python字节码文件。

a.zipped_data:压缩的数据。

cipher=block_cipher:加密算法。

EXE:生成的可执行文件。

pyz:Python字节码文件。

a.scripts:附加的脚本文件。

exclude_binaries=True:是否排除二进制文件。

name='get_jtop_info':生成的可执行文件的名称。

debug=False:是否启用调试模式。

bootloader_ignore_signals=False:是否忽略引导程序的信号。

strip=False:是否剥离调试符号。

upx=True:是否使用UPX压缩。

console=True:是否为控制台应用程序。

disable_windowed_traceback=False:是否禁用窗口化的回溯。

argv_emulation=False:是否启用命令行参数模拟。

target_arch=None:目标架构。

codesign_identity=None:代码签名标识。

entitlements_file=None:授权文件。

COLLECT:收集生成的文件。

exe:可执行文件。

a.binaries:附加的二进制文件。

a.zipfiles:附加的压缩文件。

a.datas:附加的数据文件。

strip=False:是否剥离调试符号。

upx=True:是否使用UPX压缩。

upx_exclude=[]:需要排除的UPX压缩文件。

name='get_jtop_info':生成的应用程序的名称。

这些配置项可以根据需要进行修改,以满足特定的编译需求。

重编译步骤

要使用.spec文件重新编译应用程序,可以按照以下步骤进行操作:

在目标系统上安装好Python和pyinstaller。

将原始的Python脚本文件和.spec文件拷贝到目标系统的同一个目录下。

打开终端或命令提示符,进入到该目录。

运行以下命令来重新编译应用程序:

pyinstaller get_jtop_info.spec

其中,get_jtop_info.spec是你的.spec文件的名称。

等待编译过程完成,编译成功后,会在当前目录下生成build/和dist/目录,其中dist/目录中包含了重新编译后生成的可执行文件或打包后的应用程序。

注意:重新编译应用程序时,可能需要在目标系统上安装一些依赖的库或模块,以确保应用程序能够正常运行。如果在编译过程中遇到了缺少依赖的错误,可以根据错误提示进行相应的安装。

使用pyinstaller注意事项

在使用pyinstaller进行应用程序的打包时,有一些注意事项需要注意:

版本兼容性:确保使用的pyinstaller版本与Python版本兼容。不同版本的pyinstaller可能有不同的特性和支持。

依赖管理:确保所有的依赖库都已经正确安装,并且在打包过程中能够被正确识别和包含。可以使用--hidden-import参数来指定需要导入的隐藏模块。

文件路径:在打包过程中,pyinstaller会将所有的依赖文件打包到一个目录中,因此需要确保应用程序中的文件路径是正确的。可以使用sys._MEIPASS来获取打包后的文件路径。

打包选项:根据应用程序的需求,选择合适的打包选项。例如,使用--onefile参数可以将应用程序打包成一个单独的可执行文件,而使用--windowed参数可以将应用程序打包成一个没有控制台窗口的GUI应用程序。

调试模式:在开发和调试阶段,可以使用--debug参数来启用调试模式,以便在运行时查看更多的调试信息。

平台兼容性:如果需要在不同的操作系统上运行应用程序,需要确保打包的应用程序在目标系统上能够正常运行。可以使用--target参数来指定目标系统的架构。

防病毒软件:一些防病毒软件可能会将打包后的应用程序误报为恶意软件。如果遇到这种情况,可以尝试使用pyinstaller的--upx-exclude参数来排除UPX压缩,或者将应用程序添加到防病毒软件的信任列表中。

测试和验证:在打包完成后,建议在目标系统上进行测试和验证,确保应用程序能够正常运行,并且所有的功能都能够正常使用。

这些注意事项可以帮助您更好地使用pyinstaller进行应用程序的打包和部署。

参考文章

参考文章:Python 脚本打包为可执行文件(pyinstaller;ELF;PE)



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3