faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 7 people (57%) answered Yes
Recently 3 of 6 people (50%) answered Yes

Entry

Read one key press

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 301, Fredrik Lundh


"""
Packages: operating_systems.windows;operating_systems.unix
"""
"""
> 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