On this page
tty
Prev: tracemalloc | Up: stdlib_module | Next: turtle
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — tty
Tags: #public #python3 #stdlib
Import
import tty
Overview
High-level POSIX convenience helpers (setraw, setcbreak) built on top of termios for switching a terminal file descriptor into character-at-a-time input mode without manually bit-masking termios flags.
Quick Start
import tty
# In Python 3.12+, setraw() and setcbreak() return the previous termios attributes:
assert callable(tty.setraw) and callable(tty.setcbreak)
Implementation Walkthrough
1. Reading a Single Keypress Without Waiting for Enter (setcbreak)
Prefer setcbreak() over setraw() when you still want Ctrl-C (SIGINT) and output newline translation (\n → \r\n) to work normally:
import os
import sys
import termios
import tty
def read_single_char() -> str:
fd = sys.stdin.fileno()
if not os.isatty(fd):
return sys.stdin.read(1)
old = termios.tcgetattr(fd)
try:
tty.setcbreak(fd)
return sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
Gotchas & Boundaries
- POSIX-only: Requires a real TTY (
os.isatty(fd)). setraw()disablesSIGINT(Ctrl-C) and\n→\r\ntranslation: Your app must explicitly handle\x03and emit\r\nin raw mode.- Always restore original
termiosattributes infinally:.
Common Functions
- tty.cfmakecbreak() —
cfmakecbreak(mode)— Make termios mode cbreak. - tty.cfmakeraw() —
cfmakeraw(mode)— Make termios mode raw. - tty.setcbreak() —
setcbreak(fd, when=2)— Put terminal into cbreak mode. - tty.setraw() —
setraw(fd, when=2)— Put terminal into raw mode.
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/curses
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/tracemalloc
- tuts/python3/stdlib_module/tty/cfmakecbreak
- tuts/python3/stdlib_module/tty/cfmakeraw
- tuts/python3/stdlib_module/tty/setcbreak
- tuts/python3/stdlib_module/tty/setraw
- tuts/python3/stdlib_module/turtle
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tracemalloc Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tty/cfmakecbreak Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tty/cfmakeraw Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tty/setcbreak Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tty/setraw Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/turtle Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/curses links to this page; shared tags: #stdlib