Skip to content

Instantly share code, notes, and snippets.

@ajschumacher
Created May 11, 2015 03:33
Show Gist options
  • Save ajschumacher/46db8770201b00337308 to your computer and use it in GitHub Desktop.
Save ajschumacher/46db8770201b00337308 to your computer and use it in GitHub Desktop.
get one character at a time at the console with python
def _find_getch():
# courtesy of Louis
# http://stackoverflow.com/questions/510357/
try:
import termios
except ImportError:
# Non-POSIX. Return msvcrt's (Windows') getch.
import msvcrt
return msvcrt.getch
# POSIX system. Create and return a getch that manipulates the tty.
import sys, tty
def _getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
return _getch
getch = _find_getch()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment