I'm trying to write a very simple program that will wait for x seconds before checking to see it a key has been pressed then, depending on this outcome will go into a different loop further down the code. I have this code:
import msvcrt
import time
import sys
time.sleep(1)
if msvcrt.kbhit():
sys.stdout.write('y')
else:
sys.stdout.write('n')
So I press any key when it first starts (making kbhit ==true) but it always just falls to the second statement and prints 'n'. Any suggestions what I'm doing wrong?
{Using Python 2.7 and IDLE}
Thanks
The msvcrt.kbhit()
function will only work if the program it is in has been run from the windows command line (or if a console window is opened for its input and output when you double click on its .py
file).
If you run from IDLE or using the pythonw.exe
interpreter, the program won't be connected to a console window and the console-IO commands from msvcrt
won't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With