Skip to content

Instantly share code, notes, and snippets.

@houtianze
Last active January 7, 2018 12:06
Show Gist options
  • Save houtianze/9e623a90bb836aedadc3abea54cf6747 to your computer and use it in GitHub Desktop.
Save houtianze/9e623a90bb836aedadc3abea54cf6747 to your computer and use it in GitHub Desktop.
getch() / getche() for Python
# https://stackoverflow.com/a/48136131/404271
if sys.platform == 'win32':
import msvcrt
getch = msvcrt.getch
getche = msvcrt.getche
else:
import sys
import termios
def __gen_ch_getter(echo):
def __fun():
fd = sys.stdin.fileno()
oldattr = termios.tcgetattr(fd)
newattr = oldattr[:]
try:
if echo:
# disable ctrl character printing, otherwise, backspace will be printed as "^?"
lflag = ~(termios.ICANON | termios.ECHOCTL)
else:
lflag = ~(termios.ICANON | termios.ECHO)
newattr[3] &= lflag
termios.tcsetattr(fd, termios.TCSADRAIN, newattr)
ch = sys.stdin.read(1)
if echo and ord(ch) == 127: # backspace
# emulate backspace erasing
# https://stackoverflow.com/a/47962872/404271
sys.stdout.write('\b \b')
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, oldattr)
return ch
return __fun
getch = __gen_ch_getter(False)
getche = __gen_ch_getter(True)
# to test:
#while True:
# print(getch())
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment