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

Python导入Google模块报ModuleNotFoundError,安装相关依赖后仍无法解决

问题根源

你遇到的报错核心原因是:官方Google API相关依赖包没有提供名为Google的顶层模块,Create_Service也不是官方库的内置方法,这个方法是网络上部分旧教程作者自行封装的工具函数,需要对应自定义的Google.py文件才能导入使用。你安装的google==3.0.0是无实际功能的空包,和Google API能力没有关联。

解决方法

方案1:使用官方标准认证流程(推荐)

你已经安装的google-api-python-client、google-auth-oauthlib等依赖完全可以直接实现Gmail API调用,不需要依赖第三方封装的Create_Service,替换为以下代码即可:

import os
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build

# 调整SCOPES后需要删除本地生成的token.json重新授权
SCOPES = ['https://mail.google.com/']
CLIENT_SECRET_FILE = 'client_secret.json'

def get_gmail_service():
    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())
    return build('gmail', 'v1', credentials=creds)

# 调用方法获取Gmail服务实例,和原代码中的service功能完全一致
service = get_gmail_service()

首次运行代码会自动唤起浏览器授权,授权完成后会在项目目录生成token.json,后续运行无需重复授权。

方案2:保留原代码写法

如果你坚持要使用原有的Create_Service写法,只需要把你参考的教程中配套的Google.py文件放到你当前运行脚本的同级目录即可,注意Python导入对大小写敏感,如果本地文件命名为小写的google.py,需要把导入语句改为from google import Create_Service。

额外优化建议

可以执行pip uninstall -y google卸载无用的google==3.0.0空包,不会影响任何Google API相关功能的正常使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:45:02