Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save jixiaolong/764485a6dfc1e2694ffe89def6bbf663 to your computer and use it in GitHub Desktop.

Select an option

Save jixiaolong/764485a6dfc1e2694ffe89def6bbf663 to your computer and use it in GitHub Desktop.
Timeout
import signal
class TimeoutError(Exception):
pass
class Timeout(object):
def __init__(self, seconds):
self.seconds = seconds
def __enter__(self):
signal.signal(signal.SIGALRM, self.raise_timeout)
signal.alarm(self.seconds)
def __exit__(self, *args):
signal.alarm(0)
def raise_timeout(self, *args):
raise TimeoutError()
with Timeout(5):
do_long_request()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment