On this page
  1. tty
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Reading a Single Keypress Without Waiting for Enter (setcbreak)
  7. Gotchas & Boundaries
  8. Common Functions

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

Common Functions

Linked from

Related notes