【问题标题】:Is there a way to make a For Loop iteration continue after a certain time?有没有办法让 For Loop 迭代在一定时间后继续?
【发布时间】:2020-03-25 04:10:25
【问题描述】:

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

什么是完成此任务的好方法?我已经研究过可能使用异步函数,但我不确定如何去做,或者它是否是正确的方法。

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

for url in list_of_urls: 
   request = requests.post(url)
   excel_sheet = #write header, status code, etc to document

    #save excel

【问题讨论】:

标签: python python-3.x


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-06-20
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 2015-07-06
    相关资源
    最近更新 更多