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()
).
Also worth trying is the readchar library, which is in part based on the ActiveState recipe mentioned in other answers.
Installation:
pip install readchar
Usage:
import readchar
print("Reading a char:")
print(repr(readchar.readchar()))
print("Reading a key:")
print(repr(readchar.readkey()))
Tested on Windows and Linux with Python 2.7.
On Windows, only keys which map to letters or ASCII control codes are supported (Backspace, Enter, Esc, Tab, Ctrl+letter). On GNU/Linux (depending on exact terminal, perhaps?) you also get Insert, Delete, Pg Up, Pg Dn, Home, End and F n keys... but then, there's issues separating these special keys from an Esc.
Caveat: Like with most (all?) answers in here, signal keys like Ctrl+C, Ctrl+D and Ctrl+Z are caught and returned (as '\x03'
, '\x04'
and '\x1a'
respectively); your program can be come difficult to abort.