Apr-10-2018, 03:46 PM
Ok, so I got a little distracted over
The
signal
and SIGALRM, and think we should just stop looking at them, since they don't work on Windows. I find it surprising that there isn't a built-in way to handle a timeout on input. I think one way could be to use msvcrt's methods to get one character at a time, as those return immediately if there isn't any keyboard input, but then it would ONLY work on Windows. So I think maybe the "best" way would be to spawn a new thread which tries to get the input, and the main thread will just move on if it takes too long.The
queue
has a timeout on it's .get()
method, so here, I used that to handle the timeout, and then just ignore the error raised when the queue is empty (it's empty, because the user never typed anything, so nothing was ever put in the queue):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__": print(input_with_timeout("Commands:", 2))