Apr-08-2018, 02:38 PM
If seen this question one time before. The solution was a trick.
You can use signaling to enforce calling some function and
finally this function raises an TimeoutError which bubbles up.
The minimal implementation as a context manager:
You can use signaling to enforce calling some function and
finally this function raises an TimeoutError which bubbles up.
The minimal implementation as a context manager:
class TimeOut: def __init__(self, timeout): self.timeout = timeout self._orig_handler = signal.signal(signal.SIGALRM, self._timeout) def __enter__(self): signal.alarm(self.timeout) return self def __exit__(self, *args): signal.signal(signal.SIGALRM, self._orig_handler) def _timeout(self, *args): raise TimeoutErrorUsing the context manager:
with TimeOut(5): input('Answer in 5 seconds: ')
Error:---------------------------------------------------------------------------
TimeoutError Traceback (most recent call last)
<ipython-input-38-304f3fa31b18> in <module>()
1 with TimeOut(5):
----> 2 input('Answer in 5 seconds: ')
3
<ipython-input-32-8635f61b6ed0> in _timeout(self, *args)
9 signal.signal(signal.SIGALRM, self._orig_handler)
10 def _timeout(self, *args):
---> 11 raise TimeoutError
12
TimeoutError:
Now you have to catch the TimoutError Exception, which bubbles up:with TimeOut(5): try: input('Answer in 5 seconds: ') except TimeoutError: print('\nTime is up!')
Output:Answer in 5 seconds:
Time is up!
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!