Skip to content

Instantly share code, notes, and snippets.

@demonkit
Created September 17, 2018 10:14
Show Gist options
  • Save demonkit/a52dd24015f086b0ac301486e3c286a6 to your computer and use it in GitHub Desktop.
Save demonkit/a52dd24015f086b0ac301486e3c286a6 to your computer and use it in GitHub Desktop.
Run codes under timeout control. Modified based on: https://stackoverflow.com/a/22348885/2236070
import signal
class TimeoutError(Exception):
pass
class TimeoutHandler(object):
def __init__(self, seconds=60, 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 TimeoutHander():
run_your_function()
except TimeoutError, exp:
print exp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment