当前位置:   article > 正文

python第三方库——pyinstaller_pyinstaller 第三方库

pyinstaller 第三方库

puinstaller是一个phthon库,可以将不同平台上的python文件打包为独立的可执行文件(如exe),即可以将python文件或python项目及其依赖项打包到单独的可执行文件中,从而可以在其它机器上运行,而无需为其配置相关环境。

同时有些工具的分发如果不想让第三方看到源代码,或者有些涉密需求的话,也可以使用该工具对原始代码进行隐藏。

项目地址:PyInstaller Manual — PyInstaller 6.3.0 documentation

常见参数

  1. usage: pyinstaller [-h] [-v] [-D] [-F] [--specpath DIR] [-n NAME]
  2. [--add-data <SRC;DEST or SRC:DEST>]
  3. [--add-binary <SRC;DEST or SRC:DEST>] [-p DIR]
  4. [--hidden-import MODULENAME]
  5. [--collect-submodules MODULENAME]
  6. [--collect-data MODULENAME] [--collect-binaries MODULENAME]
  7. [--collect-all MODULENAME] [--copy-metadata PACKAGENAME]
  8. [--recursive-copy-metadata PACKAGENAME]
  9. [--additional-hooks-dir HOOKSPATH]
  10. [--runtime-hook RUNTIME_HOOKS] [--exclude-module EXCLUDES]
  11. [--splash IMAGE_FILE]
  12. [-d {all,imports,bootloader,noarchive}]
  13. [--python-option PYTHON_OPTION] [-s] [--noupx]
  14. [--upx-exclude FILE] [-c] [-w]
  15. [-i <FILE.ico or FILE.exe,ID or FILE.icns or Image or "NONE">]
  16. [--disable-windowed-traceback] [--version-file FILE]
  17. [-m <FILE or XML>] [--no-embed-manifest] [-r RESOURCE]
  18. [--uac-admin] [--uac-uiaccess] [--win-private-assemblies]
  19. [--win-no-prefer-redirects] [--argv-emulation]
  20. [--osx-bundle-identifier BUNDLE_IDENTIFIER]
  21. [--target-architecture ARCH] [--codesign-identity IDENTITY]
  22. [--osx-entitlements-file FILENAME] [--runtime-tmpdir PATH]
  23. [--bootloader-ignore-signals] [--distpath DIR]
  24. [--workpath WORKPATH] [-y] [--upx-dir UPX_DIR] [-a]
  25. [--clean] [--log-level LEVEL]
  26. scriptname [scriptname ...]
  27. positional arguments:
  28. scriptname Name of scriptfiles to be processed or exactly one
  29. .spec file. If a .spec file is specified, most options
  30. are unnecessary and are ignored.
  31. optional arguments:
  32. -h, --help show this help message and exit
  33. -v, --version Show program version info and exit.
  34. --distpath DIR Where to put the bundled app (default: ./dist)
  35. --workpath WORKPATH Where to put all the temporary work files, .log, .pyz
  36. and etc. (default: ./build)
  37. -y, --noconfirm Replace output directory (default:
  38. SPECPATH\dist\SPECNAME) without asking for
  39. confirmation
  40. --upx-dir UPX_DIR Path to UPX utility (default: search the execution
  41. path)
  42. -a, --ascii Do not include unicode encoding support (default:
  43. included if available)
  44. --clean Clean PyInstaller cache and remove temporary files
  45. before building.
  46. --log-level LEVEL Amount of detail in build-time console messages. LEVEL
  47. may be one of TRACE, DEBUG, INFO, WARN, DEPRECATION,
  48. ERROR, FATAL (default: INFO). Also settable via and
  49. overrides the PYI_LOG_LEVEL environment variable.
  50. What to generate:
  51. -D, --onedir Create a one-folder bundle containing an executable
  52. (default)
  53. -F, --onefile Create a one-file bundled executable.
  54. --specpath DIR Folder to store the generated spec file (default:
  55. current directory)
  56. -n NAME, --name NAME Name to assign to the bundled app and spec file
  57. (default: first script's basename)
  58. What to bundle, where to search:
  59. --add-data <SRC;DEST or SRC:DEST>
  60. Additional non-binary files or folders to be added to
  61. the executable. The path separator is platform
  62. specific, ``os.pathsep`` (which is ``;`` on Windows
  63. and ``:`` on most unix systems) is used. This option
  64. can be used multiple times.
  65. --add-binary <SRC;DEST or SRC:DEST>
  66. Additional binary files to be added to the executable.
  67. See the ``--add-data`` option for more details. This
  68. option can be used multiple times.
  69. -p DIR, --paths DIR A path to search for imports (like using PYTHONPATH).
  70. Multiple paths are allowed, separated by ``';'``, or
  71. use this option multiple times. Equivalent to
  72. supplying the ``pathex`` argument in the spec file.
  73. --hidden-import MODULENAME, --hiddenimport MODULENAME
  74. Name an import not visible in the code of the
  75. script(s). This option can be used multiple times.
  76. --collect-submodules MODULENAME
  77. Collect all submodules from the specified package or
  78. module. This option can be used multiple times.
  79. --collect-data MODULENAME, --collect-datas MODULENAME
  80. Collect all data from the specified package or module.
  81. This option can be used multiple times.
  82. --collect-binaries MODULENAME
  83. Collect all binaries from the specified package or
  84. module. This option can be used multiple times.
  85. --collect-all MODULENAME
  86. Collect all submodules, data files, and binaries from
  87. the specified package or module. This option can be
  88. used multiple times.
  89. --copy-metadata PACKAGENAME
  90. Copy metadata for the specified package. This option
  91. can be used multiple times.
  92. --recursive-copy-metadata PACKAGENAME
  93. Copy metadata for the specified package and all its
  94. dependencies. This option can be used multiple times.
  95. --additional-hooks-dir HOOKSPATH
  96. An additional path to search for hooks. This option
  97. can be used multiple times.
  98. --runtime-hook RUNTIME_HOOKS
  99. Path to a custom runtime hook file. A runtime hook is
  100. code that is bundled with the executable and is
  101. executed before any other code or module to set up
  102. special features of the runtime environment. This
  103. option can be used multiple times.
  104. --exclude-module EXCLUDES
  105. Optional module or package (the Python name, not the
  106. path name) that will be ignored (as though it was not
  107. found). This option can be used multiple times.
  108. --splash IMAGE_FILE (EXPERIMENTAL) Add an splash screen with the image
  109. IMAGE_FILE to the application. The splash screen can
  110. display progress updates while unpacking.
  111. How to generate:
  112. -d {all,imports,bootloader,noarchive}, --debug {all,imports,bootloader,noarchive}
  113. Provide assistance with debugging a frozen
  114. application. This argument may be provided multiple
  115. times to select several of the following options.
  116. - all: All three of the following options.
  117. - imports: specify the -v option to the underlying
  118. Python interpreter, causing it to print a message
  119. each time a module is initialized, showing the
  120. place (filename or built-in module) from which it
  121. is loaded. See
  122. https://docs.python.org/3/using/cmdline.html#id4.
  123. - bootloader: tell the bootloader to issue progress
  124. messages while initializing and starting the
  125. bundled app. Used to diagnose problems with
  126. missing imports.
  127. - noarchive: instead of storing all frozen Python
  128. source files as an archive inside the resulting
  129. executable, store them as files in the resulting
  130. output directory.
  131. --python-option PYTHON_OPTION
  132. Specify a command-line option to pass to the Python
  133. interpreter at runtime. Currently supports "v"
  134. (equivalent to "--debug imports"), "u", and "W
  135. <warning control>".
  136. -s, --strip Apply a symbol-table strip to the executable and
  137. shared libs (not recommended for Windows)
  138. --noupx Do not use UPX even if it is available (works
  139. differently between Windows and *nix)
  140. --upx-exclude FILE Prevent a binary from being compressed when using upx.
  141. This is typically used if upx corrupts certain
  142. binaries during compression. FILE is the filename of
  143. the binary without path. This option can be used
  144. multiple times.
  145. Windows and Mac OS X specific options:
  146. -c, --console, --nowindowed
  147. Open a console window for standard i/o (default). On
  148. Windows this option has no effect if the first script
  149. is a '.pyw' file.
  150. -w, --windowed, --noconsole
  151. Windows and Mac OS X: do not provide a console window
  152. for standard i/o. On Mac OS this also triggers
  153. building a Mac OS .app bundle. On Windows this option
  154. is automatically set if the first script is a '.pyw'
  155. file. This option is ignored on *NIX systems.
  156. -i <FILE.ico or FILE.exe,ID or FILE.icns or Image or "NONE">, --icon <FILE.ico or FILE.exe,ID or FILE.icns or Image or "NONE">
  157. FILE.ico: apply the icon to a Windows executable.
  158. FILE.exe,ID: extract the icon with ID from an exe.
  159. FILE.icns: apply the icon to the .app bundle on Mac
  160. OS. If an image file is entered that isn't in the
  161. platform format (ico on Windows, icns on Mac),
  162. PyInstaller tries to use Pillow to translate the icon
  163. into the correct format (if Pillow is installed). Use
  164. "NONE" to not apply any icon, thereby making the OS
  165. show some default (default: apply PyInstaller's icon).
  166. This option can be used multiple times.
  167. --disable-windowed-traceback
  168. Disable traceback dump of unhandled exception in
  169. windowed (noconsole) mode (Windows and macOS only),
  170. and instead display a message that this feature is
  171. disabled.
  172. Windows specific options:
  173. --version-file FILE Add a version resource from FILE to the exe.
  174. -m <FILE or XML>, --manifest <FILE or XML>
  175. Add manifest FILE or XML to the exe.
  176. --no-embed-manifest Generate an external .exe.manifest file instead of
  177. embedding the manifest into the exe. Applicable only
  178. to onedir mode; in onefile mode, the manifest is
  179. always embedded, regardless of this option.
  180. -r RESOURCE, --resource RESOURCE
  181. Add or update a resource to a Windows executable. The
  182. RESOURCE is one to four items,
  183. FILE[,TYPE[,NAME[,LANGUAGE]]]. FILE can be a data file
  184. or an exe/dll. For data files, at least TYPE and NAME
  185. must be specified. LANGUAGE defaults to 0 or may be
  186. specified as wildcard * to update all resources of the
  187. given TYPE and NAME. For exe/dll files, all resources
  188. from FILE will be added/updated to the final
  189. executable if TYPE, NAME and LANGUAGE are omitted or
  190. specified as wildcard *. This option can be used
  191. multiple times.
  192. --uac-admin Using this option creates a Manifest that will request
  193. elevation upon application start.
  194. --uac-uiaccess Using this option allows an elevated application to
  195. work with Remote Desktop.
  196. Windows Side-by-side Assembly searching options (advanced):
  197. --win-private-assemblies
  198. Any Shared Assemblies bundled into the application
  199. will be changed into Private Assemblies. This means
  200. the exact versions of these assemblies will always be
  201. used, and any newer versions installed on user
  202. machines at the system level will be ignored.
  203. --win-no-prefer-redirects
  204. While searching for Shared or Private Assemblies to
  205. bundle into the application, PyInstaller will prefer
  206. not to follow policies that redirect to newer
  207. versions, and will try to bundle the exact versions of
  208. the assembly.
  209. Mac OS specific options:
  210. --argv-emulation Enable argv emulation for macOS app bundles. If
  211. enabled, the initial open document/URL event is
  212. processed by the bootloader and the passed file paths
  213. or URLs are appended to sys.argv.
  214. --osx-bundle-identifier BUNDLE_IDENTIFIER
  215. Mac OS .app bundle identifier is used as the default
  216. unique program name for code signing purposes. The
  217. usual form is a hierarchical name in reverse DNS
  218. notation. For example:
  219. com.mycompany.department.appname (default: first
  220. script's basename)
  221. --target-architecture ARCH, --target-arch ARCH
  222. Target architecture (macOS only; valid values: x86_64,
  223. arm64, universal2). Enables switching between
  224. universal2 and single-arch version of frozen
  225. application (provided python installation supports the
  226. target architecture). If not target architecture is
  227. not specified, the current running architecture is
  228. targeted.
  229. --codesign-identity IDENTITY
  230. Code signing identity (macOS only). Use the provided
  231. identity to sign collected binaries and generated
  232. executable. If signing identity is not provided, ad-
  233. hoc signing is performed instead.
  234. --osx-entitlements-file FILENAME
  235. Entitlements file to use when code-signing the
  236. collected binaries (macOS only).
  237. Rarely used special options:
  238. --runtime-tmpdir PATH
  239. Where to extract libraries and support files in
  240. `onefile`-mode. If this option is given, the
  241. bootloader will ignore any temp-folder location
  242. defined by the run-time OS. The ``_MEIxxxxxx``-folder
  243. will be created here. Please use this option only if
  244. you know what you are doing.
  245. --bootloader-ignore-signals
  246. Tell the bootloader to ignore signals rather than
  247. forwarding them to the child process. Useful in
  248. situations where for example a supervisor process
  249. signals both the bootloader and the child (e.g., via a
  250. process group) to avoid signalling the child twice.

上面的参数比较多,在实际的使用过程中并不是所有的参数都会用到。

单个python文件打包

最简单的就是:

pyinstaller xxx.py

这种打包方式会在当前的目录下生成一些目录和文件,其中打包完成的可执行程序在dist目录下。默认该目录下会生成很多的配置文件,比如dll库和依赖库等内容,对应的可执行文件也在该目录下。同时执行后会启动一个cmd窗口用来打印标准输出。

如果不需要生成很多的配置文件,或者不需要启动cmd窗口的话,可以使用下面的形式:

pyinstaller -F -w xxx.py

这种形式打包没有多余的依赖文件,只有一个exe文件,并且程序执行后不会启动cmd窗口,比较简洁。

python项目打包

 对于python项目来说,可能涉及到多个文件,不同文件可能有不同的依赖关系,就需要首先设置spec文件:

pyi-makespec xxx.spec

然后再设置spec文件:

  1. # -*- mode: python ; coding: utf-8 -*-
  2. block_cipher = None
  3. a = Analysis(
  4. ['xxx.spec'], # 需要包含项目中的所有文件,当前目录下的可以直接填写文件名,其它目录下的需要填写绝对路径
  5. pathex=[], # 项目路径
  6. binaries=[],
  7. datas=[], # 非py文件,多个文件使用(),其中分隔的第一个参数为文件路径,第二个参数为打包后的路径
  8. hiddenimports=[],
  9. hookspath=[],
  10. hooksconfig={},
  11. runtime_hooks=[],
  12. excludes=[],
  13. win_no_prefer_redirects=False,
  14. win_private_assemblies=False,
  15. cipher=block_cipher,
  16. noarchive=False,
  17. )
  18. pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
  19. exe = EXE(
  20. pyz,
  21. a.scripts,
  22. [],
  23. exclude_binaries=True,
  24. name='xxx', # 可执行文件exe的名称
  25. debug=False,
  26. bootloader_ignore_signals=False,
  27. strip=False,
  28. upx=True, # 表示打包的时候是否进行压缩
  29. console=True, # 表示可执行文件执行后是否会出现cmd窗口,该窗口仅用于标准输出,不影响源程序运行
  30. disable_windowed_traceback=False,
  31. argv_emulation=False,
  32. target_arch=None,
  33. codesign_identity=None,
  34. entitlements_file=None,
  35. icon='icon.ico', # 程序图标
  36. )
  37. coll = COLLECT(
  38. exe,
  39. a.binaries,
  40. a.zipfiles,
  41. a.datas,
  42. strip=False,
  43. upx=True,
  44. upx_exclude=[],
  45. name='xxx', # 打包文件的目录名称
  46. )

spec文件配置完成后,执行如下命令即可打包python项目,生成对应的可执行文件。

pyinstaller xxx.spec
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/630682
推荐阅读
相关标签
  

闽ICP备14008679号