Skip to content

Instantly share code, notes, and snippets.

@brejoc
Created March 29, 2016 13:38
Show Gist options
  • Select an option

  • Save brejoc/4cf2b224b94089ff7817 to your computer and use it in GitHub Desktop.

Select an option

Save brejoc/4cf2b224b94089ff7817 to your computer and use it in GitHub Desktop.
Example of a with-statement that allows to define a timeout for code execution.
#!/usr/bin/env python
"""timeout.py: Example of a with-statement that allows to define a timeout for code execution."""
__author__ = "Jochen Breuer"
__license__ = "Public Domain"
__email__ = "[email protected]"
import signal
from time import sleep
from contextlib import contextmanager
class TimeoutException(Exception): pass
@contextmanager
def time_limit(seconds):
def signal_handler(signum, frame):
raise TimeoutException, "Timed out!"
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
def takes_too_long():
"""\
This function will be interrupted, because it takes too long to finish.
"""
print("starting to sleep...")
sleep(5)
print("... and done!")
def fast_enough():
"""\
This function finishes in time.
"""
print "foo"
try:
with time_limit(2):
fast_enough()
takes_too_long()
except TimeoutException, msg:
print "message: %s" % (msg, )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment