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

Mac用户使用Sublime Text遇ModuleNotFoundError:找不到Google模块

解决from Google import Create_Service模块找不到问题

核心问题原因

你代码里的Create_Service并非Google官方库自带的方法,而是自定义的封装函数,且代码中引用的Google(大写G)模块也不是你通过pip安装的官方google(小写g)库。

具体解决方案

1. 创建自定义Google.py模块

Create_Service是很多Google API教程里常用的辅助工具函数,需要你手动创建一个名为Google.py的文件,放在当前代码的同一目录下,内容如下:

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os

def Create_Service(client_secret_file, api_name, api_version, *scopes):
    CLIENT_SECRET_FILE = client_secret_file
    API_SERVICE_NAME = api_name
    API_VERSION = api_version
    SCOPES = [scope for scope in scopes[0]]

    creds = None
    # token.json存储用户的访问和刷新令牌,首次运行会自动创建
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 如果没有有效凭据,引导用户登录授权
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
            creds = flow.run_local_server(port=0)
        # 保存凭据供下次使用
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build(API_SERVICE_NAME, API_VERSION, credentials=creds)
        print(f'{API_SERVICE_NAME} {API_VERSION} service created successfully')
        return service
    except Exception as e:
        print('Unable to connect.')
        print(e)
        return None

2. 统一Sublime Text与终端的Python环境

Mac系统常存在多个Python版本,你用pip3安装的库可能不在Sublime Text默认使用的Python环境中:

  • 打开终端输入which python3,复制输出的路径(比如/usr/local/bin/python3)
  • 在Sublime Text中点击Tools > Build System > New Build System
  • 粘贴以下内容(替换成你刚才复制的Python路径):
    {
        "cmd": ["/usr/local/bin/python3", "-u", "$file"],
        "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
        "selector": "source.python"
    }
    
  • 保存为Python3.sublime-build,运行代码时选择这个构建系统。

3. 验证库安装路径(可选)

如果仍有问题,可检查库的安装路径是否在Python解释器的搜索路径中:

  • 终端运行pip3 show google-api-python-client,复制Location字段的路径
  • 在你的代码开头添加:
    import sys
    sys.path.append("复制的Location路径")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:48:47