[Tutor] How to use getch()?

Dick Moores rdm at rcblue.com
Sun Aug 27 21:51:37 CEST 2006


At 11:48 AM 8/27/2006, Kent Johnson wrote:
>Blocking I/O is an I/O operation that doesn't return to the caller until
>it completes. In the case of blocking input, the input call (getch() in
>this case) won't return until some data is available. This is not what
>you want - you don't want to press a key each time through the loop, you
>want the loop to free-run until you press 'k', then exit. A non-blocking
>getch() would be perfect - a call that returns a character if one is
>available, but returns some kind of non-character marker if there is no
>character.
>
>I think this will work, using None as the marker for no character available:
>def getch_nonblocking():
>   if msvcrt.kbhit():
>     return msvcrt.getch()
>   return None
>
>Then substitute getch_nonblocking() for getch() in your loop below.
>
>Kent
> > Yes, I only want to run on Windows.
> >
> > ================
> > import msvcrt
> > c = 0
> > while True:
> >      c += 1
> >      (What goes here?) #  Not 'if msvcrt.getch() == "k":', it seems.
> >          break
> > print c
> > ================
> >
> > What I want to do is start the loop spinning, then hit "k" at some
> > point, and see what c is.

============================
import msvcrt

def getch_nonblocking():
     if msvcrt.kbhit():
         return msvcrt.getch()
     return None

c = 0
while True:
     c += 1
     if getch_nonblocking() == "k":
print c
============================

When I run this, wait a bit, then press "k", "k" is printed. In fact, 
whatever I type gets printed.  No break, no c.

Dick



More information about the Tutor mailing list