Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 13:32:32

0001 import signal, time
0002 
0003 class TimedOutExc(Exception):
0004     def __init__(self, value = "Timed Out"):
0005         self.value = value
0006     def __str__(self):
0007         return repr(self.value)
0008 
0009 def TimedOutFn(f, timeout, *args, **kwargs):
0010     def handler(signum, frame):
0011         raise TimedOutExc()
0012     
0013     old = signal.signal(signal.SIGALRM, handler)
0014     signal.alarm(timeout)
0015     try:
0016         result = f(*args, **kwargs)
0017     finally:
0018         signal.signal(signal.SIGALRM, old)
0019     signal.alarm(0)
0020     return result
0021 
0022 
0023 def timed_out(timeout):
0024     def decorate(f):
0025         def handler(signum, frame):
0026             raise TimedOutExc()
0027         
0028         def new_f(*args, **kwargs):
0029             old = signal.signal(signal.SIGALRM, handler)
0030             signal.alarm(timeout)
0031 
0032             time_up = True
0033             try:
0034                 result = f(*args, **kwargs)
0035                 time_up = False
0036             finally:
0037                 signal.signal(signal.SIGALRM, old)
0038                 signal.alarm(0)
0039                 if time_up:
0040                     raise TimedOutExc()
0041             return result
0042         
0043         new_f.__name__ = f.__name__
0044         return new_f
0045 
0046     return decorate