Skip to content

Instantly share code, notes, and snippets.

@kai5263499
Created September 27, 2017 16:22
Show Gist options
  • Save kai5263499/e0c980be5910db1c08138f6af4a9b871 to your computer and use it in GitHub Desktop.
Save kai5263499/e0c980be5910db1c08138f6af4a9b871 to your computer and use it in GitHub Desktop.
Timeout python function
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)
# Usage
# try:
# with timeout(10):
# possible_long_running_func()
# except TimeoutError:
# print "Timeout"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment