http://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish
# 1
# 2
import signal
from time import sleep
class TimeoutError(Exception):
pass
class timeout:
def __init__(self, seconds=1, error_message='Error Message: Timeout - The process is taking longer than expected.'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
#print 'Time Out'
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)
with timeout(seconds=10):
a = 50
while a > 0:
print 'OK'
sleep(5)
No comments:
Post a Comment