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

Pyinstaller打包Google Sheets API程序遇UnknownApiNameOrVersion错误求助

Google Sheets API + Pyinstaller打包后出现UnknownApiNameOrVersion错误的解决方案

原因分析

Pyinstaller打包时,默认不会包含google-api-python-client库中的API发现文档(如sheets_v4.json),导致程序运行时无法找到对应API的配置信息,触发该错误。


解决方案

1. 手动嵌入API发现文档(推荐离线场景)

  • 找到你的Python环境中googleapiclient的发现文档目录,路径一般为:Lib\site-packages\googleapiclient\discovery_cache\documents,复制其中的sheets_v4.json文件到你的项目根目录。
  • 修改代码中构建Sheets服务的逻辑,指定本地发现文档路径:
import sys
import os
from googleapiclient.discovery import build

# 判断当前是否为打包后的运行环境
if getattr(sys, 'frozen', False):
    base_path = sys._MEIPASS  # Pyinstaller打包后的临时目录
else:
    base_path = os.path.dirname(os.path.abspath(__file__))

# 拼接本地sheets_v4.json的路径
sheets_docs_path = os.path.join(base_path, 'sheets_v4.json')
# 构建服务时指定本地发现文档
service = build(
    'sheets',
    'v4',
    credentials=your_credentials_object,
    discoveryServiceUrl=f'file://{sheets_docs_path}'
)
  • 打包时使用--add-data参数将sheets_v4.json包含进程序:
# Windows系统
pyinstaller --add-data "sheets_v4.json;." your_script.py

# Mac/Linux系统
pyinstaller --add-data "sheets_v4.json:." your_script.py

2. 禁用发现文档缓存(依赖网络)

如果程序运行时可以联网,直接在构建服务时禁用缓存,强制在线获取API配置:

from googleapiclient.discovery import build

service = build(
    'sheets',
    'v4',
    credentials=your_credentials_object,
    cache_discovery=False
)

3. 强制导入缺失的依赖模块

部分场景下Pyinstaller会遗漏googleapiclient的子模块,打包时添加--hidden-import参数强制导入:

pyinstaller --hidden-import googleapiclient.discovery --hidden-import googleapiclient.errors your_script.py

如果使用了服务账号密钥文件,记得同时用--add-data包含密钥文件:

pyinstaller --add-data "credentials.json;." --hidden-import googleapiclient.discovery your_script.py

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:30:56