Electron调用PyInstaller打包的含rembg的Python可执行文件报错
解决Electron调用PyInstaller打包的rembg脚本出现EOFError的问题
这个错误的核心是numba缓存加载失败——Electron运行环境与终端的用户权限、工作目录、环境变量存在差异,导致打包后的Python脚本无法正常读取或写入numba的缓存文件。以下是针对性的解决方案:
1. 禁用numba JIT缓存
直接跳过numba的缓存机制,避免加载缓存时触发EOFError。在Python脚本开头添加:
import os # 禁用numba的JIT编译缓存 os.environ['NUMBA_DISABLE_JIT'] = '1' import rembg print("Hello World")
如果需要保留JIT功能,可以指定numba的缓存目录到Electron有权限读写的临时目录:
import os import tempfile # 创建临时缓存目录 numba_temp_cache = tempfile.mkdtemp() os.environ['NUMBA_CACHE_DIR'] = numba_temp_cache import rembg print("Hello World")
2. 修正PyInstaller打包配置
PyInstaller可能未正确打包numba的缓存相关依赖,需要手动修改spec文件补充配置:
- 生成spec文件:
pyinstaller --name test test.py - 编辑
test.spec,在Analysis部分添加hiddenimports和缓存文件路径:
from pathlib import Path a = Analysis( ['test.py'], hiddenimports=['numba.core', 'numba.core.caching', 'rembg'], # 如果本地已有numba缓存,可打包进程序 datas=[(Path.home() / '.cache' / 'numba', 'numba_cache')], ... )
- 重新打包:
pyinstaller test.spec
3. 指定Electron执行时的工作目录
Electron默认的工作目录可能与终端不同,导致脚本找不到依赖或缓存路径错误。在execFile调用中显式指定工作目录为可执行文件所在路径:
const { execFile } = require('child_process'); const path = require('path'); // 可执行文件的绝对路径 const exePath = path.join(__dirname, 'Depend', 'test'); // 指定工作目录为可执行文件所在目录 execFile(exePath, ['img2.jpg', '6'], { cwd: path.dirname(exePath) }, (error, stdout, stderr) => { if (error) { console.error('执行错误:', error); return; } console.log('输出:', stdout); });
4. 确保rembg模型文件可访问
rembg需要下载预训练模型,Electron环境可能无法自动读取默认模型路径。手动指定模型路径到有权限访问的位置:
from rembg import remove, new_session # 替换为你的模型文件绝对路径 model_path = "/home/your-user/.u2net/u2net.onnx" session = new_session(model_name="u2net", model_path=model_path) # 后续使用session进行背景移除操作
内容的提问来源于stack exchange,提问作者Thura Lin Htut
相关产品推荐
相关产品推荐

