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

PyInstaller打包exe运行报sheets v4 UnknownApiNameOrVersion错误

问题现象
  • 基于Google Sheet API搭配服务账号开发的Google Sheets写入脚本,直接用Python运行时完全正常
  • 用PyInstaller将脚本打包为exe后,运行exe触发报错,打包流程本身无异常,可正常生成build、dist文件夹
  • 核心报错提示:

googleapiclient.errors.UnknownApiNameOrVersion: name: sheets version: v4

  • 完整报错回溯:
Traceback (most recent call last):
  File "pygsheets\sheet.py", line 39, in __init__
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\DC\\AppData\\Local\\Temp\\_MEI165082\\pygsheets\\data\\sheets_discovery.json'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "script.py", line 50, in <module>
  File "Scrapers\showclix.py", line 15, in __init__
  File "pygsheets\authorization.py", line 131, in authorize
  File "pygsheets\client.py", line 61, in __init__
  File "pygsheets\sheet.py", line 43, in __init__
  File "googleapiclient\_helpers.py", line 130, in positional_wrapper
  File "googleapiclient\discovery.py", line 287, in build
  File "googleapiclient\discovery.py", line 404, in _retrieve_discovery_doc
googleapiclient.errors.UnknownApiNameOrVersion: name: sheets  version: v4
  • 已尝试操作:对应开源仓库issue中列出的两种解决方案均尝试过,问题未解决。
根因说明

报错的第一层FileNotFoundError已经点明核心问题:PyInstaller默认不会收集pygsheets包内data目录下的sheets_discovery.json静态文件,打包后的exe运行时会解压到系统临时目录(就是报错里的_MEI开头的文件夹),这个目录里没有对应的discovery文件,pygsheets就会回退到在线拉取Sheets API的discovery文档,一旦运行环境存在网络限制、API访问不通的情况,拉取失败就会抛出UnknownApiNameOrVersion的错误。

解决步骤
  1. 定位本地Python环境中pygsheets的安装目录,找到pygsheets/data/sheets_discovery.json文件,将该文件复制到待打包的Python脚本同级目录。
  2. 打包时通过PyInstaller的--add-data参数,显式指定将该json文件打包到exe内对应路径,Windows环境打包命令参考:
    pyinstaller --add-data "sheets_discovery.json;./pygsheets/data" your_script.py
    
    注意:Windows系统下--add-data参数的源路径和目标路径用分号;分隔,Linux/macOS系统下用冒号:分隔
  3. 在代码最开头、导入pygsheets相关模块之前,加入路径适配逻辑,手动指定discovery文件的加载路径,绕开pygsheets默认的路径查找逻辑:
    import sys
    import os
    
    # 适配PyInstaller打包后的临时运行路径
    if getattr(sys, 'frozen', False):
        runtime_path = sys._MEIPASS
    else:
        runtime_path = os.path.dirname(os.path.abspath(__file__))
    
    import pygsheets
    # 强制指定本地discovery文件路径,禁止在线拉取
    pygsheets.SheetApi.discoveryUrl = os.path.join(runtime_path, 'pygsheets', 'data', 'sheets_discovery.json')
    
  4. 重新执行打包命令,生成的exe即可正常运行,断网环境下也不会触发API版本找不到的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 05:48:43