Speno's Pythonic Avocado 12.10.2004

2004-10-12

Sorry, I timed out there...

Sometimes you don't have time to wait forever...

class TimeoutFunctionException(Exception): """Exception to raise on a timeout""" pass class TimeoutFunction: def __init__(self, function, timeout): self.timeout = timeout self.function = function def handle_timeout(self, signum, frame): raise TimeoutFunctionException() def __call__(self, *args): old = signal.signal(signal.SIGALRM, self.handle_timeout) signal.alarm(self.timeout) try: result = self.function(*args) finally: signal.signal(signal.SIGALRM, old) signal.alarm(0) return result if __name__ == '__main__': import sys stdin_read = TimeoutFunction(sys.stdin.readline, 1) try: line = stdin_read() except TimeoutFunctionException: print 'Too slow!' else: print 'You made it!'

Thanks to mjd for the original idea implemented in $@%.

I searched the Python Cookbook before writing this code and found nothing. The day after I wrote this TimeoutFunction class, I saw this python cookbook recipe on Daily Python -URL. D'oh!

This post references topics: python
posted at 15:20:32    #    comment []    trackback []
October 2004
MoTuWeThFrSaSu
     1 2 3
4 5 6 7 8 910
11121314151617
18192021222324
25262728293031
Sep
2004
 Feb
2005

One python programmer's search for understanding and avocados. This isn't personal, only pythonic.

XML-Image Letterimage

© 2004-2005, John P. Speno