Python Function: Read Character-by-Character Until ESC is Pressed
To read from standard input character by character until the user presses the ESC key, you need to bypass the usual line-buffered input (which waits for Enter) and instead read raw keypresses. This requires different approaches on Windows and Unix-like systems.
Below is a cross-platform solution that works on both Windows and Unix (Linux, macOS) using only the Python standard library. The ESC key corresponds to the ASCII code 27 ('\x1b').
Implementation:
import sys
def read_until_esc():
"""
Reads characters from standard input one at a time until the ESC key is pressed.
Returns the string of characters entered (excluding ESC).
"""
chars = []
try:
# Windows
import msvcrt
print("Press keys (ESC to quit):")
while True:
ch = msvcrt.getch()
if isinstance(ch, bytes):
ch = ch.decode('utf-8', errors='ignore')
if ch == '\x1b': # ESC key
break
print(ch, end='', flush=True)
chars.append(ch)
except ImportError:
# Unix (Linux, macOS)
import tty
import termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
print("Press keys (ESC to quit):")
try:
tty.setraw(fd)
while True:
ch = sys.stdin.read(1)
if ch == '\x1b': # ESC key
break
print(ch, end='', flush=True)
chars.append(ch)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
print() # for newline after loop
return ''.join(chars)
Usage Example:
if __name__ == "__main__":
result = read_until_esc()
print("You entered:", result)
Key Points:
- On Windows,
msvcrt.getch() reads a single character without waiting for Enter[1][8].
- On Unix-like systems,
tty.setraw() and sys.stdin.read(1) allow reading one character at a time without Enter[1][6].
- The function prints each character as it's typed and stops when ESC (
'\x1b') is detected.
- The collected characters (excluding ESC) are returned as a string.
This approach avoids third-party dependencies and works in most terminal environments. If you need more advanced key handling (like arrow keys or function keys), consider using libraries such as readchar or keyboard, but for simple ESC detection, the above is sufficient[1][8].