Python: Timeout a function

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)
        signal.alarm(self._seconds)
        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)

    @staticmethod
    def _raise_timeout(signum, frame):
        raise TimeoutError

How do i use it?

import time


if __name__ == '__main__':
    try:
        with timeout(seconds=5):
            time.sleep(10)
    except TimeoutError:
        print('The function timed out')

    print('Done.')

			

Leave a Reply

Your email address will not be published. Required fields are marked *