Last active
January 3, 2025 13:59
-
-
Save jfktrey/8928865 to your computer and use it in GitHub Desktop.
Cross-platform getch() for Python without any fuss
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This does have a minor type disparity.
msvcrt.getch()
returnsbytes
whilesys.stdin.read(1)
returnsstr
. There ismsvcrt.getwch()
available which returnsstr
.