kbhit() and getch() question

Mark Hammond MarkH at ActiveState.com
Sun Mar 11 03:39:18 CET 2001

Jeremy Reed wrote:

> In a previous question, I asked how to get non-blocking input from the user.
> The answer proposed is as follows:
> import msvcrt
> ch = 0
> while ch != 'x':
>     if msvcrt.kbhit():
>         ch = msvcrt.getch()
>         print ch
> I have run into a few problems.  First of all, the kbhit() doesn't seem to
> work.  I am unable to find a way for the function to return true.
> Second, the getch() function is listed in the documentation as a blocking
> call, but it doesn't block when i run it in the following script.
> ch = 0
> while ch != 'x':
>     ch = mscvrt.getch()
>     print ch
> Instead, it prints the equivalent to chr(255) in an infinite loop.
> Is there some setup call or initialization function that I'm neglecting to
> call?  Why aren't these function working like the documentation says they
> should?

These functions will only work from a "console" program.  If you are in 
a GUI, keystrokes are delivered via the message loop, and life gets a 
little more difficult.  You will need to give more details about your 


More information about the Python-list mailing list