如何自动触发Python在我的Google表格更新时运行某些脚本?

huangapple go评论71阅读模式
英文:

How to automatically TRIGGER python to do some script when my Google sheet is updated?

问题

我看过很多关于每10分钟或特定日期触发Python的视频,但是我找不到如何在我的表格更新时触发Python执行某项任务的方法,请提供一个简单的解决方案。

(*我在使用个人电脑而非云服务)
提前感谢您的帮助。

英文:

I saw hell a lot of videos where we can trigger python every 10min or a specific day BUT
I cant find how to trigger python to do something when my sheet is updated, pls provide a SIMPLE solution

(*I am using my personnel pc NOT cloud service)
thx in advance

help me please thx in advance

答案1

得分: 3

为了在Google表格更新时自动触发Python脚本,您可以使用Google Sheets API以及Webhook服务。以下是实现这一目标的逐步指南:

  1. 设置Google Sheets API:

    • 转到Google Cloud控制台
    • 创建一个新项目或选择现有项目。
    • 为您的项目启用Google Sheets API。
    • 为您的项目创建凭据(OAuth 2.0客户端ID)。
  2. 安装必要的包:

    • 通过运行 pip install gspread 安装gspread包。
    • 通过运行 pip install oauth2client 安装oauth2client包。
    • 通过运行 pip install google-auth 安装google-auth包。
  3. 创建Python脚本:

    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    import json
    import requests
    
    def main():
        # 用实际的JSON凭据文件路径替换 'path_to_credentials_file'。
        scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
        credentials = ServiceAccountCredentials.from_json_keyfile_name('path_to_credentials_file', scope)
        client = gspread.authorize(credentials)
    
        # 用您的Google表格的实际ID替换 'your_spreadsheet_id'。
        sheet = client.open_by_key('your_spreadsheet_id').sheet1
    
        # 定义要监视更改的范围,例如 'A1:C10'。
        range_to_monitor = 'A1:C10'
    
        # 获取范围内的当前值
        current_values = sheet.range(range_to_monitor)
    
        # 持续检查范围内的更改
        while True:
            # 获取最新值
            latest_values = sheet.range(range_to_monitor)
    
            # 将最新值与当前值进行比较
            if latest_values != current_values:
                # 值已更改,请在此处执行您希望的操作
    
                # 用Webhook服务的URL替换 'your_webhook_url'。
                webhook_url = 'your_webhook_url'
                payload = {
                    'values': [cell.value for cell in latest_values],
                }
                headers = {
                    'Content-Type': 'application/json',
                }
                response = requests.post(webhook_url, data=json.dumps(payload), headers=headers)
    
                # 更新当前值为最新值
                current_values = latest_values
    
    if __name__ == '__main__':
        main()
    
  4. 创建Webhook服务:

    • 创建一个可以接收来自Python脚本请求的Webhook服务或API端点。您可以使用诸如Flask或Django的框架来创建服务。
    • 在Webhook服务中实现必要的逻辑来处理来自Python脚本的数据。
  5. 设置触发器:

    • 使用第三方服务,如Zapier或IFTTT,设置一个触发器,以监听Google表格的更改。
    • 配置触发器,以在Google表格更新时向您的Webhook服务发送HTTP请求。

通过按照这些步骤操作,您可以在Google表格更新时自动触发Python脚本并执行操作。

英文:

To automatically trigger a Python script when your Google Sheet is updated, you can use the Google Sheets API along with a webhook service. Here's a step-by-step guide to achieving this:

  1. Set up the Google Sheets API:

    • Go to the Google Cloud Console.
    • Create a new project or select an existing project.
    • Enable the Google Sheets API for your project.
    • Create credentials (OAuth 2.0 client ID) for your project.
  2. Install necessary packages:

    • Install the gspread package by running pip install gspread.
    • Install the oauth2client package by running pip install oauth2client.
    • Install the google-auth package by running pip install google-auth.
  3. Create a Python script:

    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    import json
    import requests
    
    def main():
        # Replace 'path_to_credentials_file' with the actual path to your JSON credentials file.
        scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
        credentials = ServiceAccountCredentials.from_json_keyfile_name('path_to_credentials_file', scope)
        client = gspread.authorize(credentials)
    
        # Replace 'your_spreadsheet_id' with the actual ID of your Google Sheet.
        sheet = client.open_by_key('your_spreadsheet_id').sheet1
    
        # Define the range to monitor for changes, e.g., 'A1:C10'
        range_to_monitor = 'A1:C10'
    
        # Get the current values in the range
        current_values = sheet.range(range_to_monitor)
    
        # Continuously check for changes in the range
        while True:
            # Get the latest values
            latest_values = sheet.range(range_to_monitor)
    
            # Compare the latest values with the current values
            if latest_values != current_values:
                # Values have changed, perform your desired actions here
    
                # Replace 'your_webhook_url' with the URL of your webhook service
                webhook_url = 'your_webhook_url'
                payload = {
                    'values': [cell.value for cell in latest_values],
                }
                headers = {
                    'Content-Type': 'application/json',
                }
                response = requests.post(webhook_url, data=json.dumps(payload), headers=headers)
    
                # Update the current values to the latest values
                current_values = latest_values
    
    if __name__ == '__main__':
        main()
    
  4. Create a webhook service:

    • Create a webhook service or API endpoint that can receive the request from the Python script. You can use frameworks like Flask or Django to create the service.
    • Implement the necessary logic in the webhook service to handle the received data from the Python script.
  5. Set up the trigger:

    • Use a third-party service like Zapier or IFTTT to set up a trigger that listens for changes in your Google Sheet.
    • Configure the trigger to send an HTTP request to your webhook service whenever the Google Sheet is updated.

By following these steps, you can automatically trigger your Python script and perform actions whenever your Google Sheet is updated.

huangapple
  • 本文由 发表于 2023年5月25日 19:58:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定