Python Tty Module
The tty module defines functions for putting the tty into cbreak and raw modes. Because it requires the termios module, it will work only on Unix.
Importing the Module
import tty
Functions
The module defines the following functions:
tty.setraw()
Change the mode of the file descriptor fd to raw. If when is omitted, it defaults to termios.TCSAFLUSH, and is passed to termios.tcsetattr().
# tty.setraw(fd, when=termios.TCSAFLUSH)
tty.setcbreak()
Change the mode of file descriptor fd to cbreak. If when is omitted, it defaults to termios.TCSAFLUSH, and is passed to termios.tcsetattr().
# tty.setcbreak(fd, when=termios.TCSAFLUSH)
Example: Reading a Single Character
This example demonstrates how to read a single character from standard input without waiting for a newline (which is standard line-buffered behavior).
import tty
import sys
import termios
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
print("Press any key to continue...")
char = getch()
print(f"\nYou pressed: {char}")