一种PyInstaller中优雅的控制包巨细的方法

打印 上一主题 下一主题

主题 901|帖子 901|积分 2703

PyInstaller会在打包时自动为我们收集一些依赖项,特别是我们在打包PyQt/PySide相关的应用时,PyInstaller会自动包含我们步伐通常不必要的文件,如'tanslations'文件夹,'plugins/imageformats'等,通常这些文件会使我们最终的exe文件变大。在网上没有找任何好的方法来排除这些文件,从这个Issue https://github.com/pyinstaller/pyinstaller/issues/5503 里我们可以看到一种方法就是在打包之前先删除PyQt安装目次中的不必要文件,这种做法能达到目的,但在我看来实在是不够优雅。
PyInstaller其实最终都依赖spec文件来获取依赖及其它配置项,而天生spec文件内容是由一个模板(https://github.com/pyinstaller/pyinstaller/blob/develop/PyInstaller/building/templates.py)控制, 以是我们可以在天生之前去修改(patch)下这个模板,就可以达到控制依赖项的目的。
以下假设我们是通过代码方式来调用Pyinstaller,并使用onefile模式(onedir模块可参照修改).
注意以下Analysis语句后面的代码即为处理惩罚datas和binaries的代码,在这里可以添加任何过滤逻辑
  1. import PyInsatller.building.templates as pyi_spec_templates
  2. from PyInstaller.__main__ import run as pyi_build
  3. # copy from PyInsatller.building.templates.py
  4. # add datas and binaries filter after Analysis
  5. onefiletmplate = """# -*- mode: python ; coding: utf-8 -*-
  6. %(preamble)s
  7. a = Analysis(
  8.     %(scripts)s,
  9.     pathex=%(pathex)s,
  10.     binaries=%(binaries)s,
  11.     datas=%(datas)s,
  12.     hiddenimports=%(hiddenimports)s,
  13.     hookspath=%(hookspath)r,
  14.     hooksconfig={},
  15.     runtime_hooks=%(runtime_hooks)r,
  16.     excludes=%(excludes)s,
  17.     noarchive=%(noarchive)s,
  18.     optimize=%(optimize)r,
  19. )
  20. # begin filter any datas you want
  21. datas = []
  22. for dest_name, src_name, res_type in a.datas:
  23.     # 在这里添加过滤逻辑
  24.     datas.append((dest_name, src_name, res_type))
  25. a.datas = datas
  26. # end filter datas
  27. # begin filter any binaries you want
  28. binaries = []
  29. for dest_name, src_name, res_type in a.binaries:
  30.     # 在这里添加过滤逻辑
  31.     binaries.append((dest_name, src_name, res_type))
  32. a.binaries = binaries
  33. # end filter datas
  34. pyz = PYZ(a.pure)
  35. %(splash_init)s
  36. exe = EXE(
  37.     pyz,
  38.     a.scripts,
  39.     a.binaries,
  40.     a.datas,%(splash_target)s%(splash_binaries)s
  41.     %(options)s,
  42.     name='%(name)s',
  43.     debug=%(debug_bootloader)s,
  44.     bootloader_ignore_signals=%(bootloader_ignore_signals)s,
  45.     strip=%(strip)s,
  46.     upx=%(upx)s,
  47.     upx_exclude=%(upx_exclude)s,
  48.     runtime_tmpdir=%(runtime_tmpdir)r,
  49.     console=%(console)s,
  50.     disable_windowed_traceback=%(disable_windowed_traceback)s,
  51.     argv_emulation=%(argv_emulation)r,
  52.     target_arch=%(target_arch)r,
  53.     codesign_identity=%(codesign_identity)r,
  54.     entitlements_file=%(entitlements_file)r,%(exe_options)s
  55. )
  56. """
  57. pyi_spec_templates.onefiletmplt = onefiletmplate  # ==> patch the template string here
  58. # build exe
  59. pyi_build(['main.py', '--onefile', ...])
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

大号在练葵花宝典

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表