Created
April 19, 2014 16:49
-
-
Save payne92/11090057 to your computer and use it in GitHub Desktop.
getch() function to read single char from stdin, w/o waiting for newline (Windows and Unix)
This file contains hidden or 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
# If Windows getch() available, use that. If not, use a | |
# Unix version. | |
try: | |
import msvcrt | |
getch = msvcrt.getch | |
except: | |
import sys, tty, termios | |
def _unix_getch(): | |
"""Get a single character from stdin, Unix version""" | |
fd = sys.stdin.fileno() | |
old_settings = termios.tcgetattr(fd) | |
try: | |
tty.setraw(sys.stdin.fileno()) # Raw read | |
ch = sys.stdin.read(1) | |
finally: | |
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) | |
return ch | |
getch = _unix_getch |
Do you know if there is a way of doing this, but printing a message prompt before accepting input?
Edit: I have just realised that this is 6 years old...
Yes, you can simply call print() before calling this getch() function. You may need to specify flush=True to make sure all the print output is shown.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simplified version of this SO thread: http://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user