pyinstaller 如何打包python 代码

本次文章主要介绍,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 这个目录
因为其中包含了一些库
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值