Created
July 27, 2016 07:03
-
-
Save mydreambei-ai/79cd5d6e5e88d4296c2eb7f518035abd to your computer and use it in GitHub Desktop.
python signal timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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