Skip to content

Instantly share code, notes, and snippets.

@erogol
Created June 15, 2016 14:33
Show Gist options
  • Save erogol/9947f7438db0d13858bd9c5bc9d7908c to your computer and use it in GitHub Desktop.
Save erogol/9947f7438db0d13858bd9c5bc9d7908c to your computer and use it in GitHub Desktop.
How to define a timeout to custom functions
import errno
import os
import signal
import time
class TimeoutError(Exception):
pass
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment