简体   繁体   中英

for-loop with a timeout inside the loop?

I'm trying to find a way to do a for loop, and if the iteration of the for loop is more than the timeout, then it break and go to the next iteration.

Example :

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

I think you can use the time module as shown here:

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

Assuming that a single iteration doesn't take so much, just use time module and a while loop as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM