Reputation: 34770
want to ask user to input something but not want to wait forever. There is a solution for Linux, Keyboard input with timeout in Python, but I am in windows environment. anybody can help me?
Upvotes: 3
Views: 579
Reputation: 304225
Credit to Alex Martelli
Unfortunately, on Windows, select.select works only on sockets, not ordinary files nor the console. So, if you want to run on Windows, you need a different approach. On Windows only, the Python standard library has a small module named msvcrt, including functions such as msvcrt.kbhit which tells you whether any keystroke is waiting to be read. Here, you might sys.stdout.write the prompt, then enter a small loop (including a time.sleep(0.2) or so) which waits to see whether the user is pressing any key -- if so then you can sys.stdin.readline etc, but if after your desired timeout is over no key has been hit, then just return the empty string from your function.
All of this assumes that if the user has STARTED typing something then you want to wait indefinitely (not timeout in the middle of their entering their answer!). Otherwise, you have more work to do, since you must ensure that the user has hit a Return (which means you must peek at exactly what's in sys.stdin, resp. use msvcrt.getch, one character at a time). Fortunately, the slightly simpler approach of waiting indefinitely if the user has started entering seems to be the preferable one from a user interface viewpoint -- it lets you deal with unattended consoles as you desire, yet IF the user is around at all it gives the user all the time they want to COMPLETE their answer.
Upvotes: 2