Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python kbhit() problems

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

like image 432
user2756892 Avatar asked Sep 07 '13 11:09

user2756892


1 Answers

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.

like image 122
Blckknght Avatar answered Oct 14 '22 05:10

Blckknght