Created
April 19, 2016 16:50
-
-
Save MOOOWOOO/1ede1a721555ad1eaef0dc5921a7df77 to your computer and use it in GitHub Desktop.
超时检测装饰器,给任意可能会hang住的函数添加超时功能
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,functools | |
| class TimeoutError(Exception): | |
| pass #定义一个Exception,后面超时抛出 | |
| 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