Files
dragonpilot/common/timeout.py
Dragonpilot Team 4d7a40310f dragonpilot 2022-08-11T09:38:43 for EON/C2
version: dragonpilot v0.8.16 beta for EON/C2
date: 2022-08-11T09:38:43
dp-dev(priv2) master commit: c6cd233f23f60e7a6055d42850bc593c0e69082e
2022-08-11 09:48:37 +00:00

28 lines
699 B
Python

import signal
class TimeoutException(Exception):
pass
class Timeout:
"""
Timeout context manager.
For example this code will raise a TimeoutException:
with Timeout(seconds=5, error_msg="Sleep was too long"):
time.sleep(10)
"""
def __init__(self, seconds, error_msg=None):
if error_msg is None:
error_msg = f'Timed out after {seconds} seconds'
self.seconds = seconds
self.error_msg = error_msg
def handle_timeout(self, signume, frame):
raise TimeoutException(self.error_msg)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, exc_type, exc_val, exc_tb):
signal.alarm(0)