我认为您可以使用时间模块,如下所示:import time#get the time at the start of the programx = time.localtime(time.time())start_time = time.strftime('%S', x)#the looptimeout = 5for 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 timetimeout = 60time_start = time.time()i = 0while i < len(mylist) and time.time() - time_start < timeout: # do your stuff i += 1if i == len(mylist): # this code runs if the iteration has completed, pass does nothing passelse: # and this code runs if there was a timeout pass