Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Timed Exit
#12
Here another option.
from threading import Thread

class Input:
    def __init__(self, message, timeout):
        self.response = None
        print('You have {0} seconds to answer'.format(timeout))
        thread = Thread(target=self.do_input, args=(message,))
        thread.start()
        # wait for a response
        thread.join(timeout)
        # closing input after timeout
        if self.response is None:
            print('\nTimes up. Press enter to continue')
            thread.join()
            # clear response from enter key
            self.response = None

    def do_input(self, message):
        self.response = input(message)

    # optional
    def get(self):
        return self.response

def main():
    r = Input('Type anything >> ', 2).get()
    print(r)
    r = Input('Type anything >> ', 3)
    print(r.response)

main()

Maybe better just use class method.
from threading import Thread

class Input:
    _response = None # internal use only

    @classmethod
    def timeout(cls, message, timeout):
        cls._response = None
        print('You have {0} seconds to answer'.format(timeout))
        thread = Thread(target=cls.do_input, args=(message,))
        thread.start()
        # wait for a response
        thread.join(timeout)
        # closing input after timeout
        if cls._response is None:
            print('\nTimes up. Press enter to continue')
            thread.join()
            # clear response from enter key
            cls._response = None
        return cls._response

    @classmethod
    def do_input(cls, message):
        cls._response = input(message)

def main():
    r = Input.timeout('Type anything >> ', 2)
    print(r)
    r = Input.timeout('Type anything >> ', 3)
    print(r)


main()
99 percent of computer problems exists between chair and keyboard.
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