Sometimes we have a function running too long more than we expect, we want to kill it after a certain time. For example, we have a function connecting to a remote share, the function we use to connect does not provide a timeout or we can’t change its timeout.

Our solution is to build a timeout function to kill the function if it runs too long. I found this good and simple code:

import signal

class timeout:
    def __init__(self, seconds):
        self._seconds = seconds

    def __enter__(self):
        # Register and schedule the signal with the specified time
        signal.signal(signal.SIGALRM, timeout._raise_timeout)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        # Unregister the signal so it won't be triggered if there is
        # no timeout
        signal.signal(signal.SIGALRM, signal.SIG_IGN)

    def _raise_timeout(signum, frame):
        raise TimeoutError

How do i use it?

import time

if __name__ == '__main__':
        with timeout(seconds=5):
    except TimeoutError:
        print('The function timed out')