Skip to content

Instantly share code, notes, and snippets.

@a-hisame
Last active September 12, 2016 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-hisame/c0865eafadf6e2e166d17b49b8379148 to your computer and use it in GitHub Desktop.
Save a-hisame/c0865eafadf6e2e166d17b49b8379148 to your computer and use it in GitHub Desktop.
タイムアウト付き標準入力モジュール
#!/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