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

Github Actions中Python脚本传值及counter更新失效问题求助

问题分析

GitHub Actions每次运行都会从仓库拉取全新的代码副本,你在runner环境里修改的File2.py只是临时文件,不会自动提交回仓库。下次运行时,脚本又会读取仓库里原始的counter值,导致更新无效。

解决方案

方案一:修复现有逻辑,将counter提交回仓库

既然你现在用修改File2.py的方式保存状态,那就需要在GitHub Actions运行脚本后,把修改后的文件提交并推回仓库。

步骤1:调整Python脚本路径

把r'File2.py'改成相对路径'File2.py',避免在runner环境里出现路径错误。

步骤2:更新GitHub Actions的YAML配置

在你的Workflow文件中,添加提交和推送的步骤:

name: Daily Wiki Email
on:
  schedule:
    - cron: '0 12 * * *' # 每天UTC时间12点运行,可根据需求调整时区
  workflow_dispatch: # 支持手动触发测试

jobs:
  send-email:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.10'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install wikipedia-api nltk

      - name: Download NLTK tokenizer data
        run: python -m nltk.downloader punkt

      - name: Run email script
        run: python File1.py

      - name: Commit and push counter update
        run: |
          git config --global user.name "GitHub Actions Bot"
          git config --global user.email "actions@github.com"
          git add File2.py
          git commit -m "Update counter to latest value" || echo "No changes to commit"
          git push
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

步骤3:开启仓库写入权限

进入你的GitHub仓库 → Settings → Actions → General → Workflow permissions,选择Read and write permissions并保存,确保runner有权限推送修改到仓库。

方案二:更优实现——用JSON文件管理状态(推荐)

直接修改Python文件保存状态不够规范,建议用独立的JSON文件存储当前进度,比如state.json:

1. 创建状态文件

在仓库根目录创建state.json,初始内容:

{"current_topic_index": 0, "counter": 0}

2. 修改Python脚本逻辑

替换原来读写File2.py的代码,改成读写JSON文件:

import json
import wikipedia
from nltk.tokenize import sent_tokenize
import sys
import smtplib

# 读取状态
def load_state():
    try:
        with open('state.json', 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return {"current_topic_index": 0, "counter": 0}

# 保存状态
def save_state(state):
    with open('state.json', 'w') as f:
        json.dump(state, f, indent=2)

# 替换成你的主题列表
listOfTopics = ["Python (programming language)", "Artificial Intelligence", "Machine Learning"]

state = load_state()
current_topic_idx = state["current_topic_index"]
counter = state["counter"]

while True:
    # 循环回到第一个主题
    if current_topic_idx >= len(listOfTopics):
        current_topic_idx = 0
        counter = 0
        save_state({"current_topic_index": current_topic_idx, "counter": counter})

    topic = listOfTopics[current_topic_idx]
    initialPage = wikipedia.page(topic)
    totalContent = initialPage.content
    sentences = sent_tokenize(totalContent)

    # 当前counter超出句子总数,切换到下一个主题
    if counter + 10 > len(sentences):
        current_topic_idx += 1
        counter = 0
        save_state({"current_topic_index": current_topic_idx, "counter": counter})
        continue

    # 获取10句内容
    tenSentences = sentences[counter:counter+10]
    # 发送邮件(建议用GitHub Secrets存储邮箱密码)
    server = smtplib.SMTP('smtp.your-email-provider.com', 587)
    server.starttls()
    server.login('your-email@example.com', '${{ secrets.EMAIL_PASSWORD }}')
    server.sendmail('sender@example.com', 'recipient@example.com', 
                    f"Subject: Daily Wiki Topic - {topic}\n\n{' '.join(tenSentences)}".encode('utf-8'))
    server.quit()

    # 更新状态
    counter += 10
    save_state({"current_topic_index": current_topic_idx, "counter": counter})
    sys.exit()

3. 更新GitHub Actions配置

把提交步骤中的File2.py换成state.json即可:

- name: Commit and push state update
  run: |
    git config --global user.name "GitHub Actions Bot"
    git config --global user.email "actions@github.com"
    git add state.json
    git commit -m "Update progress state" || echo "No changes to commit"
    git push
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

额外注意事项

  • 邮箱密码不要硬编码,存储在GitHub Secrets中,用${{ secrets.EMAIL_PASSWORD }}引用
  • 维基百科API有调用限制,建议添加重试逻辑避免请求失败
  • 处理脚本运行中的异常,比如网络错误、维基页面不存在等情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:08:23