Created
February 24, 2012 15:54
-
-
Save jasonrdsouza/1901709 to your computer and use it in GitHub Desktop.
Python function to get keypresses from the terminal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def getchar(): | |
#Returns a single character from standard input | |
import tty, termios, sys | |
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 | |
while 1: | |
ch = getchar() | |
print 'You pressed', ch |
The best solution on the internet so far, good job.
@jasonrdsouza Could i use this in a public script?
Thanks!
ty
Wouldn't it be better to move the imports outside the function body? That way the modules don't get imported every time the function is run but instead just once and then reused for every call to the function.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@oname-15h, I find that KeyboardInterrupt at tty.setcbreak() crashes the BASH shell for some reason.
If tty.setraw() is used as before, then its capturing of all control characters makes the "try" block redundant, but if we want a way to return to the shell from within the getchar() routine, then we can test for ordinal values of the control codes and call sys.exit() if found.