Using msvcrt (in Windows), how to catch Enter key?
Dick Moores
rdm at rcblue.com
Mon Oct 29 13:39:49 EDT 2007
At 09:53 AM 10/29/2007, Dick Moores wrote:
>At 09:26 AM 10/29/2007, Gabriel Genellina wrote:
> >On 29 oct, 09:23, Dick Moores <r... at rcblue.com> wrote:
> >
> > > >while True:
> > > > if msvcrt.getch() == '\r':
> > >
> > > I tried it and find that without the msvcrt.kbhit the first key I hit
> > > doesn't do anything. I have to hit that key again, or another key.
> >
> >I'd say there is a logic error in your program then; keys don't "do
> >anything" by themselves.
> >Try posting a small sample, telling what you get and what you expect.
>
>Huh. Works now.
>
>import msvcrt
>while True:
> key = msvcrt.getch()
> if key == 'h':
> print 'Hello'
> if key == 'b':
> print 'Bye'
> if key == '\r': # 'Enter' key
> break
>
>Dick
But here's a case where it seems I do need the
if msvcrt.kbhit() line
=========================
#!/usr/bin/env python
#coding=utf-8
import time
import msvcrt
timeNow = time.time()
oldTimeNow = timeNow
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
if key == 'h':
print 'Hello'
if key == 'b':
print 'Bye'
if key == '\r': # Enter key
break
timeNow = time.time()
if timeNow - oldTimeNow > 5:
print "5 seconds passed"
oldTimeNow = timeNow
==========================
Without that line:
==========================
#!/usr/bin/env python
#coding=utf-8
import time
import msvcrt
timeNow = time.time()
oldTimeNow = timeNow
while True:
#if msvcrt.kbhit():
key = msvcrt.getch()
if key == 'h':
print 'Hello'
if key == 'b':
print 'Bye'
if key == '\r': # Enter key
break
timeNow = time.time()
if timeNow - oldTimeNow > 5:
print "5 seconds passed"
oldTimeNow = timeNow
============================
Without that line the "5 seconds passed" report is printed ONLY after
a "b" or an "h", not what I want.
Dick
More information about the Python-list
mailing list