Skip to content

Instantly share code, notes, and snippets.

@Sumukh
Created September 30, 2016 23:22
Show Gist options
  • Select an option

  • Save Sumukh/5236df478c98fa462cefa22d3ed4f9f9 to your computer and use it in GitHub Desktop.

Select an option

Save Sumukh/5236df478c98fa462cefa22d3ed4f9f9 to your computer and use it in GitHub Desktop.
Easy Timeouts in Python (works on Unix)
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)
try:
with timeout(seconds=3):
do_the_thing()
except TimeoutError as t:
print("It has a timeout error -.-")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment