Initial release.
[robmyers:dogecode.git] / dogecode / getch.py
1 # From http://code.activestate.com/recipes/134892/
2 # "getch()-like unbuffered character reading from stdin
3 #  on both Windows and Unix (Python recipe)"
4
5 class _Getch:
6     """Gets a single character from standard input.  Does not echo to the
7 screen."""
8     def __init__(self):
9         try:
10             self.impl = _GetchWindows()
11         except ImportError:
12             self.impl = _GetchUnix()
13
14     def __call__(self): return self.impl()
15
16
17 class _GetchUnix:
18     def __init__(self):
19         import tty, sys
20
21     def __call__(self):
22         import sys, tty, termios
23         fd = sys.stdin.fileno()
24         old_settings = termios.tcgetattr(fd)
25         try:
26             tty.setraw(sys.stdin.fileno())
27             ch = sys.stdin.read(1)
28         finally:
29             termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
30         return ch
31
32
33 class _GetchWindows:
34     def __init__(self):
35         import msvcrt
36
37     def __call__(self):
38         import msvcrt
39         return msvcrt.getch()
40
41
42 getch = _Getch()
43