Single keystrokes, non-blocking

The following script shows how single keystrokes are read in a non-blocking mode.

#!/usr/bin/env python

import sys, termios
import __builtin__

def inkey():
    if not 'inkeyInit' in __builtin__.__dict__:
        __builtin__.__dict__['inkeyInit'] = 1
        fd = sys.stdin.fileno()
        old = termios.tcgetattr( fd)
        new = termios.tcgetattr( fd)
        new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
        #
        # VMIN specifies the minimum number of characters to be read
        #
        new[6] [termios.VMIN] = 0
        #
        # VTIME specifies how long the driver waits for VMIN characters.
        # the unit of VTIME is 0.1 s. 
        #
        new[6] [termios.VTIME] = 1
        termios.tcsetattr( fd, termios.TCSADRAIN, new)
        sys.exitfunc = lambda: termios.tcsetattr( fd, termios.TCSADRAIN, old)
	    
    key = sys.stdin.read(1)
    if( len( key) == 0):
	key = -1
    else:
	key = ord( key)
    return key

def main():
    print( "Press some keys, 'x' terminates")
    while True:
        key = inkey()
        if( key == ord( 'x')): break
        if( key != -1): print( key)
    print( "Bye")

if __name__ == "__main__":
    main()