On this page
  1. curses
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Safe Initialization & Terminal Restoration (curses.wrapper)
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

curses

Prev: ctypes | Up: stdlib_module | Next: dataclasses
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — curses
Tags: #public #python3 #stdlib


Import

import curses

Overview

Terminal-independent screen-painting and keyboard-handling library wrapping POSIX ncurses (wrapper, initscr, newwin, cbreak, noecho). Reach for curses.wrapper() for quick POSIX terminal UIs when you want terminfo abstraction; for modern TrueColor/async/zero-curses TUIs, consider raw ANSI + termios/tty.

Quick Start

import curses

def draw(stdscr: curses.window) -> None:
    curses.curs_set(0)
    stdscr.clear()
    stdscr.addstr(0, 0, "Press q to quit")
    stdscr.refresh()
    while stdscr.getch() != ord("q"):
        pass

# Invoke only on an interactive POSIX TTY:
# curses.wrapper(draw)
assert callable(curses.wrapper)

Implementation Walkthrough

1. Safe Initialization & Terminal Restoration (curses.wrapper)

Always launch via curses.wrapper(main_fn)—it enables noecho, cbreak, keypad keys, and color pairs, and guarantees your terminal is restored cleanly even if an unhandled exception occurs:

import curses

def app(stdscr: curses.window) -> str:
    curses.start_color()
    curses.use_default_colors()
    curses.init_pair(1, curses.COLOR_CYAN, -1)
    height, width = stdscr.getmaxyx()
    msg = f"Terminal: {width}x{height}"[: max(0, width - 1)]
    stdscr.addstr(0, 0, msg, curses.color_pair(1))
    stdscr.refresh()
    return msg

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes