[Tutor] How to use getch()?

Dick Moores rdm at rcblue.com
Sun Aug 27 19:11:44 CEST 2006


At 09:51 AM 8/27/2006, Kent Johnson wrote:
>Dick Moores wrote:
> > I'm trying to figure out how to change what a script does while it is
> > running, by pressing a key, such as "k". Can getch() be used for
> > this?
>Google 'python getch' or see this recipe by our very own Danny Yoo:

So now I have, thanks to Danny Yoo:

=====================================
class _Getch:
     """Gets a single character from standard input.  Does not echo to the
screen."""
     def __init__(self):
         try:
             self.impl = _GetchWindows()
         except ImportError:
             self.impl = _GetchUnix()

     def __call__(self): return self.impl()

class _GetchWindows:
     def __init__(self):
         import msvcrt

     def __call__(self):
         import msvcrt
         return msvcrt.getch()

c = 0
getch = _Getch()
while True:
     c += 1
     if getch == "k":
         break
print c
================================================

No more errors, but it doesn't do what I wanted. More help, please.

Dick Moores



More information about the Tutor mailing list