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

Inquirer库与PyInstaller兼容问题:打包后导入失败

解决PyInstaller打包inquirer脚本时readchar元数据缺失问题

问题原因

readchar作为inquirer的依赖库,会通过importlib.metadata.version("readchar")获取自身版本信息。但PyInstaller使用--hidden-import导入依赖时,不会自动打包该库的元数据文件(存放在readchar-<版本号>.dist-info目录下),导致可执行文件运行时触发PackageNotFoundError。

解决方案

方案1:通过spec文件添加元数据

  1. 生成基础spec配置文件:
pyinstaller --onefile test.py
  1. 打开生成的test.spec文件,找到Analysis模块的datas参数,添加readchar的dist-info目录:
    • 先定位虚拟环境中readchar的dist-info路径,例如venv/Lib/site-packages/readchar-3.0.0.dist-info
    • 修改spec文件中的datas字段:
      a = Analysis(
          ['test.py'],
          pathex=[],
          binaries=[],
          datas=[('venv/Lib/site-packages/readchar-3.0.0.dist-info', 'readchar-3.0.0.dist-info')],
          # 其余参数保持不变
      )
      
  2. 基于修改后的spec文件重新打包:
pyinstaller test.spec

方案2:直接用--add-data参数打包元数据

在PyInstaller命令中添加--add-data指定readchar的元数据目录(Windows系统用;分隔路径,Linux/macOS用:):

pyinstaller --onefile --hidden-import=inquirer --hidden-import=readchar --add-data "venv/Lib/site-packages/readchar-3.0.0.dist-info;readchar-3.0.0.dist-info" test.py

方案3:临时修改readchar源码(不推荐)

打开虚拟环境中readchar/__init__.py文件,将第6行的动态版本获取代码:

__version__ = version("readchar")

替换为固定版本号(例如你安装的readchar版本3.0.0):

__version__ = "3.0.0"

之后再用原打包命令重新生成可执行文件即可。

内容的提问来源于stack exchange,提问作者Jhorman Traslaviña

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 02:33:24