Created
December 1, 2015 17:20
-
-
Save notgba/c68b6baca8c4925e3762 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 | |
| import functools | |
| # 定义一个Exception,后面超时抛出 | |
| class TimeoutError(Exception): | |
| pass | |
| def timeout(seconds, error_message='Function call timed out'): | |
| def decorated(func): | |
| def _handle_timeout(signum, frame): | |
| raise TimeoutError(error_message) | |
| def wrapper(*args, **kwargs): | |
| signal.signal(signal.SIGALRM, _handle_timeout) | |
| signal.alarm(seconds) | |
| try: | |
| result = func(*args, **kwargs) | |
| finally: | |
| signal.alarm(0) | |
| return result | |
| return functools.wraps(func)(wrapper) | |
| return decorated |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment