步骤
目的
将Python 源代码转成可执行的文件
重要文件解析
- .spec 配置文件:打包时的详细配置<当涉及资源文件txt, json时,打包后无法正常引用
- build 文件夹
- dist 文件夹:最后可执行文件存放处
选项配置
资源文件如何放置
- 使用相/绝对路径可能会导致打包后的程序找不到资源文件,可以采用setting.py 解析项目根目录文件
.spec 文件内容讲解
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['main.py'], # 要打包的源码文件,第一个必须是项目的主程序文件
pathex=[],
binaries=[],
datas=[('d:/temp/data','data')], # 元组第一个元素是原项目中需要拷贝的目录or文件,第二个元素是打包程序后的目录文件,两个目录名最好保持一致
hiddenimports=[], # 设置一些解析不出的依赖包,在写代码时,涉及第三方库最好使用from ... import ..., 可以大大降低程序包exe的大小
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='main', # 可执行文件的名字
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=True,
disable_windowed_traceback=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='main') # 打包后的目录名
修改.spec后运行
pyinstaller xxx.spec