Read one key press.

Sean Hummel seanh at unforgettable.com
Wed Oct 20 04:01:45 EDT 1999


It really seems like this problem should be solved by a builtin.  I've found
a need for this in many of my applications as well, and I was lucky I only
needed to write the application for windows.




----------
In article <00a101bf1a00$95d66080$f29b12c2 at secret.pythonware.com>, "Fredrik
Lundh" <fredrik at pythonware.com> wrote:


> Gerrit Holl <gerrit.holl at pobox.com> wrote:
>> if I have the following program:
>>
>> key = raw_input("press a key: ")
>> if key == 'a':
>>     print "you pressed 'a'"
>> elif key == '^['
>>     print "you pressed escape"
>>
>> it doesn't work. Well, it works but it itsn't what I'm looking for. I want
>> ONE key input. Can this me done easyly?
>
> well, at least it can be done in Python.  here's something
> that appears to work on Windows and Linux (should have
> been in the guide, but didn't quite make it).
>
> # tty-example-2.py
>
> import sys
>
> try:
>     # windows or dos
>     import msvcrt
>     getkey = msvcrt.getch
> except ImportError:
>     # assume unix
>     import tty, termios, TERMIOS
>     def getkey():
>         file = sys.stdin.fileno()
>         mode = termios.tcgetattr(file)
>         try:
>             tty.setraw(file, TERMIOS.TCSANOW)
>             ch = sys.stdin.read(1)
>         finally:
>             termios.tcsetattr(file, TERMIOS.TCSANOW, mode)
>         return ch
>
> print "press 'q' to quit..."
>
> while 1:
>     ch = getkey()
>     if ch == "q":
>         break
>     print ch,
>
> print
>
> </F>
>
> <!-- (the eff-bot guide to) the standard python library:
> http://www.pythonware.com/people/fredrik/librarybook.htm
> -->
>
>
> 




More information about the Python-list mailing list