Skip to content

Instantly share code, notes, and snippets.

@payne92
Created April 19, 2014 16:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save payne92/11090057 to your computer and use it in GitHub Desktop.
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)
# 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
@payne92
Copy link
Author

payne92 commented Apr 19, 2014

@nathan-a-macleod
Copy link

nathan-a-macleod commented Jun 26, 2020

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...

@payne92
Copy link
Author

payne92 commented Jun 26, 2020

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