[Tutor] How to use getch()?

Kent Johnson kent37 at tds.net
Sun Aug 27 20:48:11 CEST 2006


Dick Moores wrote:
> At 10:55 AM 8/27/2006, Kent Johnson wrote:
>   
>> getch is a callable object (it implements __call__()) and is used like a
>> function.
>>
>> If you only want to run on Windows, as your code suggests, just call
>> msvcrt.getch() directly. This is a blocking call - it won't return until
>> a key is pressed. If you don't want to block, use msvcrt.kbhit() to
>> check whether a key is available before calling getch().
>>     
>
> Thanks, Kent, but I'm afraid I don't know what a blocking call is.
>   
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.
>
> Dick
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   




More information about the Tutor mailing list