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

使用PyInstaller生成可执行文件时遇NameError问题求解决

解决PyInstaller打包LayoutParser模型时的NameError问题

问题根源

PyInstaller的静态代码分析无法识别LayoutParser(尤其是基于Detectron2的模型)内部的动态引用逻辑,导致打包后运行时缺失内部变量name。

可行解决方案

1. 显式声明隐藏依赖

在主脚本开头添加必要的显式导入,同时打包时指定需要包含的隐藏模块:

  • 主脚本头部补充代码:
import layoutparser as lp
from detectron2.config import get_cfg
from detectron2.modeling import build_model
  • 执行打包命令时加入--hidden-import参数:
pyinstaller --hidden-import=detectron2 --hidden-import=layoutparser --hidden-import=detectron2.config your_script.py

2. 通过.spec文件手动配置依赖

如果命令行参数无效,生成并修改.spec文件:

  1. 生成基础.spec文件:
pyinstaller your_script.py
  1. 打开生成的your_script.spec,在hiddenimports列表中补充依赖:
hiddenimports=['detectron2', 'layoutparser', 'detectron2.config', 'detectron2.modeling', 'detectron2.checkpoint']
  1. 用修改后的.spec文件重新打包:
pyinstaller your_script.spec

3. 本地加载模型配置

避免使用lp://快捷方式,手动下载配置文件后本地加载:

  1. 手动下载PubLayNet的配置文件保存到本地(例如命名为publaynet_config.yaml)
  2. 修改模型初始化代码:
model = lp.Detectron2LayoutModel(
    './publaynet_config.yaml',
    extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.8],
    label_map={0: "Text", 1: "Title", 2: "List", 3: "Table", 4: "Figure"}
)

打包完成后,将配置文件放在可执行文件同目录下。

4. 关闭打包优化并排查导入问题

PyInstaller的优化可能误删未显式引用的代码,尝试关闭优化并排查导入日志:

pyinstaller --noupx --debug=imports --hidden-import=detectron2 your_script.py

--debug=imports会输出详细的导入过程,帮助定位缺失的依赖模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 03:12:06