Difference between revisions of "Implementing Timers in Python"
Jump to navigation
Jump to search
PeterHarding (talk | contribs) (New page: <pre> import signal, time class TimedOutExc(Exception): def __init__(self, value = "Timed Out"): self.value = value def __str__(self): return repr(self.value) def...) |
PeterHarding (talk | contribs) |
||
Line 1: | Line 1: | ||
=Using UNIX Like Functionality= | |||
This script makes use of UNIX derived signal methods. | |||
<pre> | <pre> | ||
import signal, time | import signal, time | ||
Line 50: | Line 54: | ||
</pre> | </pre> | ||
[[ | |||
[[ | [[Category:Python]] | ||
[[ | [[Category:Testing]] | ||
[[Category:Development]] |
Revision as of 19:18, 30 April 2008
Using UNIX Like Functionality
This script makes use of UNIX derived signal methods.
import signal, time class TimedOutExc(Exception): def __init__(self, value = "Timed Out"): self.value = value def __str__(self): return repr(self.value) def TimedOutFn(f, timeout, *args, **kwargs): def handler(signum, frame): raise TimedOutExc() old = signal.signal(signal.SIGALRM, handler) signal.alarm(timeout) try: result = f(*args, **kwargs) finally: signal.signal(signal.SIGALRM, old) signal.alarm(0) return result def timed_out(timeout): def decorate(f): def handler(signum, frame): raise TimedOutExc() def new_f(*args, **kwargs): old = signal.signal(signal.SIGALRM, handler) signal.alarm(timeout) try: result = f(*args, **kwargs) finally: signal.signal(signal.SIGALRM, old) signal.alarm(0) return result new_f.func_name = f.func_name return new_f return decorate def fn_1(secs): time.sleep(secs) return "Finished" @timed_out(4)