(In Linux context) Entering terminal raw mode (to read mouse, Function keys etc) in python is easy:
import sys, tty, termios
fd=sys.stdin.fileno()
#tty.setraw(fd)
tty.setcbreak(fd)
But then I want to get back and use input()
again. Unfortunately, there is no tty.setcooked()
function. What to do?
Save the tty attributes returned by tty.setraw
, and pass them to termios.tcsetattr
to restore the previous settings:
tty_attrs = tty.setraw(fd)
# later, to restore
termios.tcsetattr(fd, termios.TCSAFLUSH, tty_attrs)
On Python versions before 3.12, tty.setraw
returns None
instead of the old attributes, so you'll have to call termios.tcgetattr
manually:
tty_attrs = termios.tcgetattr(fd)
tty.setraw(fd)
# later, to restore
termios.tcsetattr(fd, termios.TCSAFLUSH, tty_attrs)