Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (47.6k points)

Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like getch()). I know there's a function in Windows for it, but I'd like something that is cross-platform.

1 Answer

0 votes
by (106k points)

The ActiveState recipe quoted verbatim in two answers is over-engineered. It can be boiled down to this:

def _find_getch(): 

try: 

import termios 

except ImportError: 

import msvcrt 

return msvcrt.getch 

import sys, tty 

def _getch(): 

fd = sys.stdin.fileno() 

old_settings = termios.tcgetattr(fd) 

try:

tty.setraw(fd) 

ch = sys.stdin.read(1) 

finally:

termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 

return ch 

return _getch 

getch = _find_getch()

Related questions

0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...