Many attempts have been made in the past to add timeout functionality in Python such that when a specified time limit expired, waiting code could move on. Unfortunately, pre
The Pebble library was designed to offer cross-platform implementation capable of dealing with problematic logic which could crash, segfault or run indefinitely.
from pebble import concurrent
@concurrent.process(timeout=10)
def function(foo, bar=0):
return foo + bar
future = function(1, bar=2)
try:
result = future.result() # blocks until results are ready
except Exception as error:
print("Function raised %s" % error)
print(error.traceback) # traceback of the function
except TimeoutError as error:
print("Function took longer than %d seconds" % error.args[1])
The decorator works as well with static and class methods. I would not recommend to decorate methods nevertheless, as it is a quite error prone practice.