有没有一种方法可以使For Loop迭代在一定时间后继续?

时间:2020-03-25 04:10:25

标签: python python-3.x

我有一个for循环正在发出POST请求。每个人大约需要1-8分钟才能完成,如果要经过一定的时间(例如15分钟),我希望我的循环继续进行并跳过。

什么是实现此目标的好方法?我已经研究了潜在使用异步函数的方法,但是我不确定该怎么做,或者它是否是正确的方法。

它是一个超级简单的循环,基本上是:

except ErrorWithCode as e:
    print("Received error with code:", e.code)
    pass

1 个答案:

答案 0 :(得分:0)

您可以使用请求的“超时”参数。如果请求的时间超过此秒数,它将引发异常,您可以轻松捕获:

for url in list_of_urls: 
    try:
        request = requests.post(url, timeout=60)
    except requests.exceptions.ReadTimeout:
        print("Timeout requesting %s, skipping..." % url)
        continue
    # do your stuff here
    pass