1

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?

  • [There's no good way to do this](https://stackoverflow.com/q/6947065/364696). Best you can do is making a `multiprocessing.Process` which you can kill if it doesn't complete in time. – ShadowRanger Jan 30 '23 at 18:43
  • I was just about to edit the post with that exact question, thanks – user12969777 Jan 30 '23 at 18:44

0 Answers0