Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Timed Exit
#2
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:

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 TimeoutError
Using 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!
Reply


Messages In This Thread
Timed Exit - by Tbot - Apr-08-2018, 01:38 PM
RE: Timed Exit - by DeaD_EyE - Apr-08-2018, 02:38 PM
RE: Timed Exit - by Tbot - Apr-08-2018, 03:06 PM
RE: Timed Exit - by DeaD_EyE - Apr-09-2018, 06:18 AM
RE: Timed Exit - by Tbot - Apr-09-2018, 12:22 PM
RE: Timed Exit - by nilamo - Apr-09-2018, 07:08 PM
RE: Timed Exit - by Tbot - Apr-10-2018, 12:09 AM
RE: Timed Exit - by nilamo - Apr-10-2018, 01:06 AM
RE: Timed Exit - by DeaD_EyE - Apr-10-2018, 08:16 AM
RE: Timed Exit - by Tbot - Apr-10-2018, 12:46 PM
RE: Timed Exit - by nilamo - Apr-10-2018, 03:46 PM
RE: Timed Exit - by Windspar - Apr-10-2018, 10:45 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020