Skip to content

Instantly share code, notes, and snippets.

@jfktrey
Last active May 13, 2024 21:31
Show Gist options
  • 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