如何使用pyinstaller打包资源到exe

pyinstaller说明

--add-data <SRC;DEST or SRC:DEST>
                        Additional non-binary files or folders to be added to
                        the executable. The path separator is platform
                        specific, ``os.pathsep`` (which is ``;`` on Windows
                        and ``:`` on most unix systems) is used. This option
                        can be used multiple times.
--add-binary <SRC;DEST or SRC:DEST>
                        Additional binary files to be added to the executable.
                        See the ``--add-data`` option for more details. This
                        option can be used multiple times.

添加资源文件时,需要注意以下几点,以下以 --add-data为例:

  • pyinstaller --add-data ‘src/README.txt:.’ myscript.py
  • 如果需要兼容windows, unix系统,需要将上述的:换成os.pathsep,在windows环境中为;, 在unix系统中为:
  • --add-data传入的数据相当于一个元组, os.pathsep前的为资源文件的绝对路径,后面的为打包时在exe文件中存放的相对路径
  • 如果需要添加多组资源文件,可以多次使用--add-data

使用资源文件时如何兼容python脚本和exe文件

  • 通过sys的frozen参变量可以区别python脚本和exe文件
    • python 脚本: getattr(sys, ‘frozen’, False) = False
    • Exe文件: getattr(sys, ‘frozen’, False) = True
  • 资源文件打包进exe之后,当运行的时候,会生成一个临时目录, 临时目录可以通过sys._MEIPASS获取

代码示例:

import os
import sys

def get_root_path():
    # determine if application is a script file or frozen exe
    if getattr(sys, 'frozen', False):
        return os.path.abspath(sys._MEIPASS)
    else:
        return os.path.dirname(os.path.abspath(__file__))

本文参考以下内容

https://www.programmersought.com/article/6945225630/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值