code_junkie

How to limit execution time of a function call in Python

Nov 12th, 2011
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. import signal
  2.  
  3. def signal_handler(signum, frame):
  4. raise Exception("Timed out!")
  5.  
  6. signal.signal(signal.SIGALRM, signal_handler)
  7. signal.alarm(10) # Ten seconds
  8. try:
  9. long_function_call()
  10. catch Exception, msg:
  11. print "Timed out!"
  12.  
  13. from __future__ import with_statement # Required in 2.5
  14. import signal
  15. from contextlib import contextmanager
  16.  
  17. class TimeoutException(Exception): pass
  18.  
  19. @contextmanager
  20. def time_limit(seconds):
  21. def signal_handler(signum, frame):
  22. raise TimeoutException, "Timed out!"
  23. signal.signal(signal.SIGALRM, signal_handler)
  24. signal.alarm(seconds)
  25. try:
  26. yield
  27. finally:
  28. signal.alarm(0)
  29.  
  30.  
  31. try:
  32. with time_limit(10):
  33. long_function_call()
  34. except TimeoutException, msg:
  35. print "Timed out!"
  36.  
  37. def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
  38. '''This function will spwan a thread and run the given function using the args, kwargs and
  39. return the given default value if the timeout_duration is exceeded
  40. '''
  41. import threading
  42. class InterruptableThread(threading.Thread):
  43. def __init__(self):
  44. threading.Thread.__init__(self)
  45. self.result = default
  46. def run(self):
  47. try:
  48. self.result = func(*args, **kwargs)
  49. except:
  50. self.result = default
  51. it = InterruptableThread()
  52. it.start()
  53. it.join(timeout_duration)
  54. if it.isAlive():
  55. return it.result
  56. else:
  57. return it.result
  58.  
  59. def function_with_enforced_timeout():
  60. f = open_temporary_file()
  61. try:
  62. ...
  63. finally:
  64. here()
  65. unlink(f.filename)
Add Comment
Please, Sign In to add comment