对于这样的东西,我通常使用以下构造:
from threading import Timer
import thread
def run_with_timeout( timeout, func, *args, **kwargs ):
""" Function to execute a func for the maximal time of timeout.
[IN]timeout Max execution time for the func
[IN]func Reference of the function/method to be executed
[IN]args & kwargs Will be passed to the func call
"""
try:
# Raises a KeyboardInterrupt if timer triggers
timeout_timer = Timer( timeout, thread.interrupt_main )
timeout_timer.start()
return func( *args, **kwargs )
except KeyboardInterrupt:
print "run_with_timeout timed out, when running '%s'" % func.__name__
#Normally I raise here my own exception
finally:
timeout_timer.cancel()
然后电话会:
timeout = 5.2 #Time in sec
for i in range(len(arr1)):
res1 = run_with_timeout(timeout, foo1,arr1[i]))