[Tutor] How to use getch()?

Dick Moores rdm at rcblue.com
Mon Aug 28 06:30:29 CEST 2006


So now I have keyPress-b.py. It works well, except that I have to ^C 
to quit it.

======================================
#keyPress-b.py
import msvcrt, time
print \
"""
After pressing Enter to start,
press Space to get first and subsequent measurements of spin.
Use Ctrl+C to quit.
"""
answer = raw_input("Press Enter to start ")
while answer == "":
     c = 0
     timeStart = time.time()
     while True:
         c += 1
         if msvcrt.kbhit():
            if msvcrt.getch() == ' ':
                break
            else:
                continue

     timeEnd = time.time()
     print
     print c, "spins"
     print "Time was %.4g seconds" % (timeEnd - timeStart)
     print "Spin rate was %.f per second" % (c/(timeEnd - timeStart))
print "Bye."
time.sleep(1)
========end of keyPress-b.py=================

I've tried revising in all sorts of ways, but none are satisfactory.
Here's keyPress-b3.py, into which I've added ways to get "Hello" by a 
key press, and also a way to quit by pressing "q".

It's flaky. I usually have to hit Space, "h" or "q" several times (or 
hold them down) before they will work.

========================================
#keyPress-b3.py
import msvcrt, time
print \
"""
After pressing Enter to start,
press Space to get first and subsequent measurements.
Press h to print "Hello".
Press and hold down q to quit.
"""
answer = raw_input("Press Enter to start ")
while answer == "":
     c = 0
     timeStart = time.time()
     while True:
         c += 1
         if msvcrt.kbhit():
            if msvcrt.getch() == ' ':
                break
         if msvcrt.kbhit():
            if msvcrt.getch() == 'h':
                print "Hello"
         if msvcrt.kbhit():
            if msvcrt.getch() == 'q':
                answer = "quit"

     timeEnd = time.time()
     print
     print c, "spins"
     print "Time was %.4g seconds" % (timeEnd - timeStart)
     print "Spin rate was %.f per second" % (c/(timeEnd - timeStart))
print "Bye."
time.sleep(5)
========end of keyPress-b3.py====================

Advice, please, on how to correct the flakiness.

Also, I can't figure out why the FIRST spin measurement of 
spins/second is usually almost double the subsequent measurements. E.g.,

26536 spins
Time was 0.765 seconds
Spin rate was 34688 per second

27632 spins
Time was 1.547 seconds
Spin rate was 17862 per second

Dick Moores
Windows XP, Python 2.43



More information about the Tutor mailing list