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/