Check for keystroke

Lee Phillips lee at leeHYPHENphillips.org.invalid
Wed Sep 22 18:19:31 EDT 2004


On Wed, 22 Sep 2004 14:37:56 GMT, Brian <ThisIsNotMyReal at ddress.com> did write:
> Inside a loop, I need to passively check to see if a key is pressed or not 
> without pausing like raw_input does.

I've had partial success on Mac OS X using termios (partial because
it seems to miss some keystrokes - also I haven't looked at this in
a while):

import termios
# in your method:
        old = termios.tcgetattr(fd) # Old term info for restoration later
        new = termios.tcgetattr(fd)
        new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
        new[6][termios.VMIN] = 1
        new[6][termios.VTIME] = 0
        termios.tcsetattr(fd, termios.TCSANOW, new)

        while 1:
            try:
                command = os.read(fd, 1)
                print command+">", #Echo manually
                if command == '0':
                    termios.tcsetattr(fd, termios.TCSADRAIN, old) #Terminal back to line mode
                    break
                elif command == 'b':
                # do something....
                # and so on.....
            finally:
                termios.tcsetattr(fd, termios.TCSAFLUSH, old)




More information about the Python-list mailing list