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

如何在PyGithub脚本中正确处理GitHub速率限制休眠时间

解决PyGithub速率限制后继续归档仓库的问题

原代码触发速率限制时用break直接终止循环,导致剩余仓库无法处理。要实现休眠后继续处理,可调整遍历逻辑,确保遇到限制时休眠后重试当前仓库,处理完成再推进到下一个:

import os
import time
from github import Github, Auth
from github.exceptions import UnknownObjectException, RateLimitExceededException

token = os.environ["GITHUB_TOKEN"]
org_name = "你的组织名"  # 替换为实际组织名称
repos = ["仓库1", "仓库2"]  # 替换为需要归档的仓库列表

g = Github(auth=Auth.Token(token))
i = 0
while i < len(repos):
    reponame = repos[i]
    try:
        repo = g.get_repo(f"{org_name}/{reponame}")
        repo.edit(archived=True)
        print(f"已归档仓库:{reponame}")
        i += 1  # 成功归档后,处理下一个仓库
    except UnknownObjectException:
        print(f"仓库 {reponame} 不存在,跳过")
        i += 1
    except RateLimitExceededException:
        sleep_duration = g.rate_limiting_resettime - time.time()
        # 避免休眠时长为负数
        sleep_duration = max(sleep_duration, 0)
        print(f"触发GitHub API速率限制,将休眠 {sleep_duration:.2f} 秒")
        time.sleep(sleep_duration)
        # 不递增索引,休眠后重新尝试当前仓库

关键细节

  • 改用while循环+索引遍历,解决for循环无法重试当前元素的问题;
  • 仅在成功归档或仓库不存在时,才推进到下一个仓库;
  • rate_limiting_resettime是PyGithub中Github类的属性,返回Unix时间戳,代表GitHub API速率限制的重置时间点,通过与当前时间的差值可计算出准确的休眠时长。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 03:52:19