for循环内有超时?

问题描述

我正在尝试找到一种进行for循环的方法,如果for循环的迭代次数超过了超时时间,则它将中断并转到下一次迭代。 / p>

示例:

timeout = 60
for i in mylist:
   i += 1
   if time > timeout:
       break

解决方法

我认为您可以使用 time 模块,如下所示:

import time

#get the time at the start of the program
x = time.localtime(time.time())
start_time = time.strftime('%S',x)

#the loop
timeout = 5
for i in range(10000000):
   i += 1
   y = time.localtime(time.time())
   now_time = time.strftime('%S',y)
   run_time = int(now_time) - int(start_time)
   print(run_time) #to see the run_time
   if run_time > timeout:
       break
,

假设一次迭代不需要那么多,只需使用time模块和以下while循环即可:

mylist = [1,2,3]
import time
timeout = 60
time_start = time.time()
i = 0
while i < len(mylist) and time.time() - time_start < timeout:
    # do your stuff
    i += 1
if i == len(mylist):
    # this code runs if the iteration has completed,pass does nothing
    pass
else:
    # and this code runs if there was a timeout
    pass

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...