Files
exercises-in-programming-style/32-reactive/util.py
2013-11-28 20:54:31 -08:00

76 lines
1.7 KiB
Python
Executable File

import sys, os
#
# getch in a platform-independent way
# Credit: http://code.activestate.com/recipes/134892/
#
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
try:
self.impl = _GetchMacCarbon()
except(AttributeError, ImportError):
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
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
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
class _GetchMacCarbon:
def __init__(self):
import Carbon
def __call__(self):
import Carbon
if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
return ''
else:
(what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
return chr(msg & 0x000000FF)
getch = _Getch()
def cls():
os.system(['clear','cls'][os.name == 'nt'])
interactive = True
def get_input():
global interactive
if not interactive:
return True
while True:
key = ord(getch())
if key == 32: # space bar
return True
elif key == 27: # ESC
interactive = False
return True