You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyInstaller打包单EXE遇FileNotFoundError问题求助

解决PyInstaller打包单文件exe时palettable资源文件缺失问题

这个问题是因为PyInstaller默认不会自动打包依赖包中的非Python资源文件(比如colorbrewer_all_schemes.json这类配置文件),导致程序运行时在临时目录找不到对应路径。以下是几种可行的解决办法:

方法一:直接用--add-data参数打包资源

先确认虚拟环境中colorbrewer_all_schemes.json的路径,一般是venv\Lib\site-packages\palettable\colorbrewer\data\colorbrewer_all_schemes.json。修改打包命令:

pyinstaller --onefile -w --add-data "venv\Lib\site-packages\palettable\colorbrewer\data\colorbrewer_all_schemes.json;palettable\colorbrewer\data" main.py

Windows系统下--add-data用分号分隔源路径和目标路径,目标路径要和代码中预期的文件结构一致,这样程序运行时就能在临时目录的对应位置找到该json文件。

方法二:通过.spec文件配置资源

  1. 先生成基础的spec文件:
pyinstaller --onefile -w main.py
  1. 打开生成的main.spec,找到datas字段,添加资源映射:
datas = [('venv\\Lib\\site-packages\\palettable\\colorbrewer\\data\\colorbrewer_all_schemes.json', 'palettable\\colorbrewer\\data')]
  1. 用spec文件重新打包:
pyinstaller main.spec

方法三:修改代码动态获取资源路径

如果允许修改代码,可以用Python的importlib.resources模块动态获取资源文件路径,这样PyInstaller会自动识别并打包该资源:

from importlib.resources import files

# 获取json文件的正确路径
json_file = files('palettable.colorbrewer.data').joinpath('colorbrewer_all_schemes.json')

# 读取文件内容
with open(json_file, 'r', encoding='utf-8') as f:
    scheme_data = f.read()

补充说明

  • 打包前确保激活虚拟环境,让PyInstaller能正确识别虚拟环境内的依赖
  • 如果用auto-py-to-exe,在「Additional Files」选项中添加该json文件,设置「Destination」为palettable\colorbrewer\data即可

内容的提问来源于stack exchange,提问作者brj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 18:39:28