如何在Google Sheet新增数据时运行本地Python脚本?
实现方案
方案一:实时触发(推荐)
1. 用Google Apps Script监听Sheet数据变化
打开目标Google Sheet,点击「扩展程序」→「Apps Script」,粘贴以下代码:
function onEdit(e) { var range = e.range; var sheet = range.getSheet(); // 判定是否为新增行(可根据你的Sheet结构调整逻辑,这里默认新增行是当前最后一行) if (range.getRow() === sheet.getLastRow()) { // 替换为你的内网穿透公网地址 var url = "https://xxxx.ngrok.io/run-script"; UrlFetchApp.fetch(url, { method: "POST", contentType: "application/json", payload: JSON.stringify({ sheetName: sheet.getName(), rowData: sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).getValues()[0] }) }); } }
如果数据是通过API/自动化工具追加的,手动编辑触发的onEdit可能不生效,需要在Apps Script的「编辑」→「当前项目的触发器」中添加可安装触发器,选择「更改」事件触发。
2. 本地搭建Web服务接收触发请求
用Python Flask写一个简单服务,接收请求后运行你的业务脚本:
from flask import Flask, request import subprocess app = Flask(__name__) @app.route('/run-script', methods=['POST']) def run_script(): # 可选:获取Sheet传递的新增数据 data = request.get_json() print("收到新数据:", data) # 替换为你的业务脚本路径 subprocess.run(["python3", "/path/to/your/business_script.py"]) return {"status": "success"}, 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
3. 内网穿透暴露本地服务
Google Apps Script只能访问公网地址,用ngrok将本地5000端口暴露到公网:
ngrok http 5000
执行后会得到类似https://xxxx.ngrok.io的地址,替换到Apps Script的url变量中。免费版ngrok地址重启后会变化,需要固定地址可选用付费版或其他内网穿透工具。
方案二:定时轮询(备选)
如果不想用内网穿透,可定期检查Sheet是否有新数据,触发脚本运行。
1. 编写Python轮询脚本
先安装依赖:
pip install gspread oauth2client
脚本逻辑:记录上次检查的最后行数,对比当前行数,有新增则运行业务脚本:
import gspread from oauth2client.service_account import ServiceAccountCredentials import subprocess import time # 配置API权限(需先创建服务账号密钥,保存为credentials.json) scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope) client = gspread.authorize(creds) # 替换为你的Sheet名称/ID sheet = client.open("你的Sheet名称").sheet1 last_row_record = "last_row.txt" def get_saved_last_row(): try: with open(last_row_record, 'r') as f: return int(f.read().strip()) except FileNotFoundError: return sheet.get_last_row() def save_last_row(row_num): with open(last_row_record, 'w') as f: f.write(str(row_num)) def check_and_run(): current_last = sheet.get_last_row() saved_last = get_saved_last_row() if current_last > saved_last: subprocess.run(["python3", "/path/to/your/business_script.py"]) save_last_row(current_last) # 每10分钟检查一次(根据数据追加频率调整) while True: check_and_run() time.sleep(600)
注意:需将服务账号邮箱添加到Sheet的共享权限列表中。
2. 设置本地定时任务
- Windows:用「任务计划程序」定期运行轮询脚本
- Linux/macOS:用cron添加定时任务,例如每10分钟执行一次:
*/10 * * * * python3 /path/to/your/polling_script.py
内容的提问来源于stack exchange,提问作者aitor
相关产品推荐
相关产品推荐

