Skip to content

Instantly share code, notes, and snippets.

@r0dn0r
Created September 15, 2019 17:19
Show Gist options
  • Save r0dn0r/d75b22a45f064b24e42585c4cc3a30a0 to your computer and use it in GitHub Desktop.
Save r0dn0r/d75b22a45f064b24e42585c4cc3a30a0 to your computer and use it in GitHub Desktop.
Python: wait for input(), else continue after x seconds
# 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()
import threading
import queue
import time
def get_input(message, channel):
response = input(message)
channel.put(response)
def input_with_timeout(message, timeout):
channel = queue.Queue()
message = message + " [{} sec timeout] ".format(timeout)
thread = threading.Thread(target=get_input, args=(message, channel))
# by setting this as a daemon thread, python won't wait for it to complete
thread.daemon = True
thread.start()
try:
response = channel.get(True, timeout)
return response
except queue.Empty:
pass
return None
if __name__ == "__main__":
a = input_with_timeout("Commands:", 5)
time.sleep(3)
print(a)
@deivixadams
Copy link

Well good

@Lestibournes
Copy link

The problem is what happens when there is no input but you want to receive another input after this. Then the thread that's waiting for input will "eat" the input that someone else is waiting for. The solution that was pointed out to me is to use select.select() to wait until there is input. If there isn't, it will stop waiting after a timeout. If there is input, then it will return a list of objects from which input can be read, and only then you read the input. Here:

def _wait_for_enter(channel: queue.Queue, timeout: int = None):
    (rlist, wlist, xlist) = select([stdin], [], [], timeout)

    if len(rlist):
        line = stdin.readline()
        channel.put(line)

All this does is wait for a line to be entered, then return that line. If no line is entered, it won't try to read the input. This allows the next call to input() to actually work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment