# This file exports a function called `getch` which will read a single
# character of user input from the terminal without waiting for a
# newline. In theory this ought to be Windows compatable but I am
# unable to verify this as I (Zeke) do not own a Windows machine.
#
# To use this file place it in the same directory as the file that you
# would like to use it in is in and add:
# ```
# from <NAME OF THIS FILE> import getch
# ```
#
# Note that when using this `getch` function sending ^C to the console
# will not cause the program to end like you might expect as the ^C
# interrupt will be read in. To avoid a program that is impossible to
# exit you may want to configure a specific character that when read
# in will terminate the program.
class _Getch:
"""Gets a single character from standard input. Does not echo to
the screen.
Source:
https://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/
"""
def __init__(self):
try:
self.impl = _GetchWindows()
except 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()
getch = _Getch()