Created
June 9, 2017 07:21
-
-
Save jixiaolong/764485a6dfc1e2694ffe89def6bbf663 to your computer and use it in GitHub Desktop.
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
| 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