Skip to content

Instantly share code, notes, and snippets.

@jfktrey
Last active May 11, 2023 09:42
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfktrey/8928865 to your computer and use it in GitHub Desktop.
Save jfktrey/8928865 to your computer and use it in GitHub Desktop.
Cross-platform getch() for Python without any fuss
import platform
if platform.system() == "Windows":
import msvcrt
def getch():
return msvcrt.getch()
else:
import tty, termios, sys
def getch():
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
@petereon
Copy link

This does have a minor type disparity. msvcrt.getch() returns bytes while sys.stdin.read(1) returns str. There is msvcrt.getwch() available which returns str.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment