我正在编写一个脚本来使用 PyGithub 归档 github 存储库。
token = os.environ["GITHUB_TOKEN"]
g = github.Github(auth=github.Auth.Token(token))
repos = []
for reponame in repos:
try:
repo = g.get_repo(f"{org_name}/{reponame}")
repo.edit(archived=True)
except UnknownObjectException:
pass
except RateLimitExceededException:
print("Rate limited")
time.sleep(g.rate_limiting_resettime - time.time())
break
一旦达到速率限制,我想跳出 for 循环,休眠直到重置速率限制,然后再次继续循环。我该怎么做?
我知道我可以使用
g.rate_limiting_resettime - time.time()
获取睡眠时间
在这里使用
for
循环很麻烦,因为有时如果您受到速率限制,您想重试相同的存储库。如果您从头开始,您也不希望一遍又一遍地将相同的存储库存档在列表的开头。最好的方法是通过索引跟踪您正在处理的存储库,并仅在处理无误后才前进到下一个存储库。
repo_idx = 0
while repo_idx < len(repos):
reponame = repos[repo_idx]
try:
repo = g.get_repo(f"{org_name}/{reponame}")
repo.edit(archived=True)
except UnknownObjectException:
pass
except RateLimitExceededException:
print("Rate limited")
time.sleep(g.rate_limiting_resettime - time.time())
continue # try this repo again from the top
repo_idx += 1 # no error, so go to the next repo
考虑在睡眠时间中增加几秒钟的时间,作为安全缓冲,避免立即再次受到速率限制。