3

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?

Community
  • 1
  • 1
5YrsLaterDBA
  • 29,380
  • 38
  • 121
  • 200

1 Answers1

2

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.

John La Rooy
  • 263,347
  • 47
  • 334
  • 476
  • I have been struggling with getting a keyboard input with timeout today. I just wanted a way to stop the reproduction of images from the hard-drive so that I can stop it just pressing a key, so I wanted a small timeout (33ms). I just want to point out that some solutions that you'll find on stackoverflow don't work on IDLE!! (I don't know why). You have to execute them on terminal. And also, the most helpful code I have found on internet is this one: http://home.wlu.edu/~levys/software/kbhit.py . The code is supposed to be multi-platform, but I only tested on Ubuntu 12.04. Good luck! – jespestana Jun 12 '13 at 23:48