timeout.py 699 B

123456789101112131415161718192021222324252627
  1. import signal
  2. class TimeoutException(Exception):
  3. pass
  4. class Timeout:
  5. """
  6. Timeout context manager.
  7. For example this code will raise a TimeoutException:
  8. with Timeout(seconds=5, error_msg="Sleep was too long"):
  9. time.sleep(10)
  10. """
  11. def __init__(self, seconds, error_msg=None):
  12. if error_msg is None:
  13. error_msg = f'Timed out after {seconds} seconds'
  14. self.seconds = seconds
  15. self.error_msg = error_msg
  16. def handle_timeout(self, signume, frame):
  17. raise TimeoutException(self.error_msg)
  18. def __enter__(self):
  19. signal.signal(signal.SIGALRM, self.handle_timeout)
  20. signal.alarm(self.seconds)
  21. def __exit__(self, exc_type, exc_val, exc_tb):
  22. signal.alarm(0)