Menu Close

How to time out function if it takes too long to finish with Python?

Sometimes, we want to time out function if it takes too long to finish with Python.

In this article, we’ll look at how to time out function if it takes too long to finish with Python.

How to time out function if it takes too long to finish with Python?

To time out function if it takes too long to finish with Python, we can use the signal module.

For instance, we write

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message

    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)

    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)

    def __exit__(self, type, value, traceback):
        signal.alarm(0)

with timeout(seconds=3):
    time.sleep(4)

to create the timeout class.

It has the handle_timeout method that raises a TimeoutError.

And it has the __enter__ method that calls signal.signal to listen for the the signal.SIGALRM signal and calls handle_timeout if it’s emitted.

And then we call signal.alarm with the timeout value to emit the signal.SIGALRM signal after seconds has elapsed.

In __exit__ we call signal_alarm with with 0 to reset the alarm.

Then we call timeout with the seconds argument to raise a TimeoutError if the code in the with block has timed out.

Conclusion

To time out function if it takes too long to finish with Python, we can use the signal module.

Posted in Python, Python Answers