To implement a Python function that reads characters from standard input one by one until the user presses the ESC key, you need to handle unbuffered, single-character input. This requires different approaches depending on the operating system (Windows vs Unix-like systems).
Here is a cross-platform solution that reads single characters without waiting for Enter, and stops when ESC (ASCII 27, \x1b) is pressed:
def read_until_esc():
"""
Reads characters from standard input one by one until the ESC key is pressed.
Works on both Windows and Unix-like systems.
"""
try:
# Windows
import msvcrt
print("Press keys (ESC to quit):")
while True:
ch = msvcrt.getch()
if ch == b'\x1b': # ESC key
print("\nESC pressed, exiting.")
break
# Decode byte to string for printing if possible
try:
char = ch.decode('utf-8')
except UnicodeDecodeError:
char = repr(ch)
print(f"Read character: {char}")
except ImportError:
# Unix-like system
import sys
import tty
import termios
print("Press keys (ESC to quit):")
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd) # Set terminal to raw mode
while True:
ch = sys.stdin.read(1)
if ch == '\x1b': # ESC key
print("\nESC pressed, exiting.")
break
print(f"Read character: {ch}")
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
Explanation
- On Windows, the
msvcrt.getch() function reads a single byte from the console without echoing it and without waiting for Enter.
- On Unix-like systems (Linux, macOS), the
tty.setraw() function puts the terminal into raw mode so that input is given character-by-character without buffering or echo.
- The function reads characters one at a time and prints them.
- When the ESC key (ASCII 27, represented as
\x1b) is detected, the loop breaks and the function exits.
- Terminal settings are restored after reading on Unix-like systems to avoid messing up the terminal state.
This approach is based on well-established methods for single-character input in Python and is adapted from common recipes such as those found on Stack Overflow[1][6].
You can call read_until_esc() in your script to start reading characters until ESC is pressed.
Note: This function reads raw characters and does not handle special keys like arrow keys or function keys that may send multiple bytes. It also does not echo input on Windows (you can add echo if needed). For more complex key handling, third-party libraries like readchar or keyboard can be used.