# Cross platform getch() and putch() implementation # by Mario Vilas (mvilas at gmail.com) # based on http://snippets.dzone.com/posts/show/915 __all__ = [ 'getch', 'putch' ] import select import socket import os import sys import time try: import msvcrt except ImportError: msvcrt = None try: import tty except ImportError: tty = None try: import termios except ImportError: termios = None class Getch: def __init__( self ): if msvcrt != None: self.getch = self.getch_windows elif tty != None and termios != None: self.getch = self.getch_unix else: raise Exception, "Unknown target OS" def getch_unix( self ): fd = sys.stdin.fileno() old_settings = termios.tcgetattr( fd ) try: tty.setraw( sys.stdin.fileno() ) ch = sys.stdin.read( 1 ) finally: termios.tcsetattr( fd, termios.TCSADRAIN, old_settings ) return ch def getch_windows( self ): ch = msvcrt.getch() if ch == '\r': ch = '\r\n' return ch getch = Getch().getch def putch( ch ): sys.stdout.write( ch ) sys.stdout.flush() if __name__ == '__main__': while 1: putch( getch() )