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

求Google Workspace服务(如DriveApp)可运行完整示例及运行方法

Google Workspace 完整运行指南及代码片段整合方案

一、Google Drive 示例的运行方式

不管是Sheets还是Drive,Google Workspace服务的代码既可以本地运行,也可以在Google云端环境(比如Google Apps Script)运行,两种方式都可行:

  • 本地运行:先安装对应语言的Google客户端库(比如Python用pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib),再从Google Cloud控制台获取OAuth2凭据,编写完整的授权+调用代码结构,即可本地执行。
  • 云端运行(Google Apps Script):直接在Google Drive里创建脚本文件,无需本地环境,代码可直接调用Drive服务(无需额外安装库),写完保存后直接运行或部署为触发器。

二、零散函数的可运行改造

要让零散函数跑起来,必须补全授权初始化和主调用逻辑,以Python为例:

  1. 完成基础授权配置:
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os.path

# 定义Drive API的权限范围,按需调整
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']

def get_drive_service():
    creds = None
    # 本地保存的凭据文件,首次运行会弹出授权页面
    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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # 保存凭据供下次使用
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    # 返回Drive服务实例
    return build('drive', 'v3', credentials=creds)
  1. 结合零散函数与服务实例,比如原函数是获取文件列表,改造后:
def list_files(service, folder_id):
    # 替换为你找到的零散函数逻辑
    results = service.files().list(
        q=f"'{folder_id}' in parents",
        pageSize=10, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])
    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print(f"{item['name']} ({item['id']})")

# 主逻辑调用
if __name__ == '__main__':
    drive_service = get_drive_service()
    # 替换为你的目标文件夹ID
    list_files(drive_service, 'your-folder-id-here')
  1. 执行步骤:
    • 从Google Cloud控制台下载credentials.json到本地代码目录
    • 安装依赖库
    • 运行脚本,首次会跳转浏览器授权,完成后自动生成token.json,后续运行无需重复授权

三、Google Apps Script 端的Drive示例(无需本地环境)

如果不想折腾本地环境,直接用Google Apps Script:

  1. 打开Google Drive,右键→更多→Google Apps Script
  2. 粘贴以下完整代码:
function listDriveFiles() {
    const folderId = "your-folder-id-here"; // 替换为你的文件夹ID
    const files = DriveApp.getFolderById(folderId).getFiles();
    while (files.hasNext()) {
        const file = files.next();
        Logger.log(file.getName() + " (" + file.getId() + ")");
    }
}
  1. 点击运行按钮,首次需授权,完成后即可在日志里查看结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:33:28