msvcrt.getch() and raw_input() get same key

Tim Peters tim_one at email.msn.com
Sun Oct 8 14:05:14 EDT 2000


[Georg Simon]
> Python 2.0b2 and Windows 98
> ----------------------------
> import msvcrt
> key = msvcrt.getch()
> if key == '\000' :
>     key = key+msvcrt.getch()
> line = raw_input(': ')
> print key, line
> ----------------------------
> In this test script raw_input() is called after msvcrt.getch() .
> In this case raw_input() receives as first character the same character
> already received by by msvcrt.getch() :
>
> Running the script in the DOS-box and pressing 'a' and 'Enter'
> gives the output 'a a'
>
> The DOS-box then looks like this :
>
> : a
> a a
> >>>
>
> Is there a way to make msvcrt.getch() eat completely it's character ?

Not really, and regardless of Python version.  The msvcrt.*ch*() functions
are thin wrappers around MS's functions of the same names, and, as the MS
docs say, are incompatible with std C I/O (which raw_input and print use).
To make this work reliably, and across all flavors of Windows, once you use
one msvcrt console I/O function, you should do all I/O with the console
using those functions.  So instead of raw_input, use msvcrt.putch() to print
the ":" and the space, and use msvcrt.getche() in a loop to read the rest of
the line.  See win_getpass in the std getpass.py for the basic idea.

MS's implementation of the console-mode I/O functions uses different buffers
than MS's implementation of std C I/O, and treat the raw keyboard buffer in
undocumented and surprising (when mixing them) ways:  MS didn't bother to
synch them up, and Python doesn't know how to.

can't-get-there-from-here-ly y'rs  - tim






More information about the Python-list mailing list