Simple Python Watchdog Timer
Join the DZone community and get the full member experience.Join For Free
Easily interrupt long portions of code if they take too long to run.
#!/usr/bin/python # file: watchdog.py # license: MIT License import signal class Watchdog(Exception): def __init__(self, time=5): self.time = time def __enter__(self): signal.signal(signal.SIGALRM, self.handler) signal.alarm(self.time) def __exit__(self, type, value, traceback): signal.alarm(0) def handler(self, signum, frame): raise self def __str__(self): return "The code you executed took more than %ds to complete" % self.timeExample:
#!/usr/bin/python # import the class from watchdog import Watchdog # don't allow long_function to take more than 5 seconds to complete try: with Watchdog(5): long_function() except Watchdog: print "long_function() took too long to complete"
Opinions expressed by DZone contributors are their own.