本次文章主要介绍,pyinstaller 打包 python 常见的问题,以及解决办法
1、安装
pip install pyinstaller
2、使用最全面的 spec 配置文件方法打包
介绍:
root
|_ test
| |_ main.py
|_custom_module
|_config
如上:
在 root 下有 test, custom_module config 3个目录
test 下有 main.py 是入口脚本
custom_module 下包含自定的脚本
config 是一些配置文件
现在打包需要以 main.py 作为入口, custom_module 作为自定义依赖模块路径,
config 作为额外的资源文件
2.1 生成 .spec 文件
cd test
pyinstaller main.py
# 将会生成 main.spec
2.2 main.spec
# -*- mode: python ; coding: utf-8 -*-
a = Analysis(
['main.py'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
noarchive=False,
)
pyz = PYZ(a.pure)
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,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='main',
)
重点介绍几个配置:
pathex 指定额外的模块路径
datas 指定额外资源文件路径
所以修改如下
# -*- mode: python ; coding: utf-8 -*-
a = Analysis(
['main.py'],
pathex=['../../root'],
binaries=[],
datas=[('config/*','config')],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
noarchive=False,
)
pyz = PYZ(a.pure)
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,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='main',
)
2.3 运行 pyinstaller
pyinstaller main.spec --distpath=install # distpath 指定输出的路径
#输出结果将会在
install/main/ 这个目录中
拷贝到其他路径的时候,需要直接拷贝 install/main 这个目录
因为其中包含了一些库