Last active
September 12, 2016 16:01
-
-
Save a-hisame/c0865eafadf6e2e166d17b49b8379148 to your computer and use it in GitHub Desktop.
タイムアウト付き標準入力モジュール
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
''' | |
stdin reader with timeout implementation | |
タイムアウト付き標準入力モジュール | |
c.f. http://qiita.com/siroken3/items/4bb937fcfd4c2489d10a | |
''' | |
import sys | |
from functools import wraps | |
class TimeoutException(Exception): | |
def __init__(self, message): | |
self.message = message | |
def __str__(self): | |
return self.message | |
def timeout(seconds, timeout_value=None): | |
def _interrupt(signum, frame): | |
raise TimeoutException('Timeout!') | |
def _decorator(func): | |
def _wrapper(*args, **kwargs): | |
import signal | |
signal.signal(signal.SIGALRM, _interrupt) | |
signal.alarm(seconds) | |
try: | |
result = func(*args, **kwargs) | |
except TimeoutException: | |
result = timeout_value | |
signal.alarm(0) | |
return result | |
return wraps(func)(_wrapper) | |
return _decorator | |
@timeout(seconds=10) | |
def stdin_read(): | |
return sys.stdin.readline() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment