Alternative to raw_input ?

Peter Hansen peter at engcorp.com
Sat Feb 12 22:24:40 EST 2005


BOOGIEMAN wrote:
> On Fri, 11 Feb 2005 21:38:47 -0500, Peter Hansen wrote:
> 
>>print prompt
>>while msvcrt.kbhit():
>>     msvcrt.getch()
>>msvcrt.getch()
> 
> 
> Thanks, it works but without line "print prompt" and also

That was intended to be a hint that you might need
to print a prompt to the user (maybe a string contained
in a variable named "prompt", for example ;-), or the
program might halt without apparent reason.

> I'm not sure if I should put this function :
> 
> def cekaj():
>     while msvcrt.kbhit():
>         msvcrt.getch()
>     msvcrt.getch()
> 
> #Or this one, which sounds more logical according to help
> #kbhit() - Return true if a keypress is waiting to be read. 
> 
> def cekaj():
>     msvcrt.getch()
>     while msvcrt.kbhit():
>         msvcrt.getch()
>      
> It works both ways, not sure which one is right

The point of doing the first approach is that you are
reading *all* available keystrokes (in the loop), and
then sitting and waiting for one more keystroke before
continuing.  If you don't read all keystrokes first,
then if the user has hit a key, say, five minutes
earlier, it will still be sitting in the queue and
your program will not actually stop at all.

Your second approach sits and waits (if necessary)
to read a single keystroke, and then if the user had
managed to hit two or more keys** before that, it will
consume all remaining keystrokes before continuing.
Not exactly the same thing, nor generally quite
what you want.  Based on what you originally asked for,
the former is the correct approach.

** Note that some keys will result in a pair of
values being retrieved by getch(), with the first one
being (generally... maybe always... I can't remember
but it's easy for you to experiment) a 0, and the second
being another code that identifies the key.  The F5
key, for example, returns a 0 and then a 64 on the
second call to getch().  If you *really* want *any*
key to continue, you'll want to check for this sort
of thing as well... though personally I'd just use
raw_input() and keep my program portable. <wink>

-Peter



More information about the Python-list mailing list