Skip to content

Instantly share code, notes, and snippets.

@mydreambei-ai
Created July 27, 2016 07:03
Show Gist options
  • Save mydreambei-ai/79cd5d6e5e88d4296c2eb7f518035abd to your computer and use it in GitHub Desktop.
Save mydreambei-ai/79cd5d6e5e88d4296c2eb7f518035abd to your computer and use it in GitHub Desktop.
python signal timeout
# encoding=utf8
import signal
import time
class TimeoutError(Exception):
pass
class Timeout(object):
def __init__(self, seconds):
self.seconds = seconds
self._default = None
def _add_signal(self):
def handler(error, frame):
raise TimeoutError
self._default = signal.getsignal(signal.SIGALRM)
signal.signal(signal.SIGALRM, handler)
signal.alarm(self.seconds)
def __enter__(self):
self._add_signal()
def __exit__(self, exc_type, exc_val, exc_tb):
signal.alarm(0)
signal.signal(signal.SIGALRM, self._default)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment