If you want to add a timeout to a function you use contextlib
and signal
like so:
import signal
from contextlib import contextmanager
class FunctionTimeout(Exception): pass
@contextmanager
def time_limit(seconds):
def signal_handler(signum, frame):
raise FunctionTimeout()
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
def long_function():
import time
time.sleep(15)
with time_limit(5):
long_function()
However this only works in the main thread due to signal only allowing the main thread to accept signals. I'm wondering if there's a way to accomplish the same task while not in the main thread?