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?

8 of 11 people (73%) answered Yes
Recently 6 of 9 people (67%) answered Yes

Entry

Read one key press

Jul 5th, 2000 10:01
Nathan Wallace, Hans Nowak, Snippet 203, Carel Fellinger


"""
Packages: 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?
as you are running linux it sure can be done:) though not as easily as
in Windows. For a better understanding try reading the libc info pages,
menu "Low-Level Terminal Interface". You can find the example I recoded
in python in its submenu "Noncanon Example". Also have a look at the
termios module.
"""
import termios, TERMIOS, sys
fd = sys.stdin.fileno()
def getch():
    saved_attributes = termios.tcgetattr(fd)
    try:
        attributes = termios.tcgetattr(fd)            #get a fresh copy!
        attributes[3] = attributes[3] & ~(TERMIOS.ICANON | TERMIOS.ECHO)
        attributes[6][TERMIOS.VMIN] = 1
        attributes[6][TERMIOS.VTIME] = 0
        termios.tcsetattr(fd, TERMIOS.TCSANOW, attributes)
        a = sys.stdin.read(1)
    finally:            #be sure to reset the attributes no matter what!
        termios.tcsetattr(fd, TERMIOS.TCSANOW, saved_attributes)
    return a