Your listing command looks great in a maximised terminal on a large monitor. Then someone runs it in an 80-column SSH session, a split tmux pane or the narrow terminal panel of an IDE, and every row wraps across three lines, columns misalign, and the one field they needed — the status — is pushed off the right edge. The opposite also happens: output designed for 80 columns wastes a wide terminal by truncating messages that would have fitted. A CLI's human-readable output should adapt to the width it actually has. This guide shows how to find that width reliably, decide which columns matter most, truncate gracefully with an ellipsis, give users --wide and --width controls, and make sure machine-readable output is never affected. It belongs to the cross-platform terminal compatibility topic.
Prerequisites
- Python 3.10+, Typer and Rich.
- A command with tabular or wrapped output — the example lists CI builds, with a mix of short essential columns and long optional ones.
Finding the width
shutil.get_terminal_size() does the standard lookup: it returns the COLUMNS environment variable if set, otherwise asks the terminal attached to stdout, otherwise returns the fallback you pass. That order matters. COLUMNS lets users — and tests — override the width without a real terminal, and the fallback of 80 is what pipes, files and CI logs get. Rich's Console performs the same lookup for its own width. Add an explicit --width option at the top of the chain for reproducible output in documentation and screenshots.
Deciding what to show
Not every column is equally important. Before writing layout code, rank them:
- Essential columns identify the row and its state — ID, name, status. They are never truncated or dropped.
- Useful columns add context — branch, start time. They may be truncated and are dropped on narrow terminals.
- Nice-to-have columns — long descriptions, commit messages — absorb whatever width remains and are the first to go.
With priorities decided, four strategies cover every width: drop low-priority columns below a threshold, truncate long values with an ellipsis (showing that something is missing, not silently cutting it), let one flexible column absorb the leftover space, and offer --wide to show everything in full when the user wants it.
The recipe
# src/mytool/cli.py
from __future__ import annotations
import json
import shutil
from dataclasses import asdict, dataclass
from typing import Annotated
import typer
from rich.console import Console
from rich.table import Table
app = typer.Typer()
@dataclass
class Build:
id: str
project: str
status: str
branch: str
started: str
commit_message: str
BUILDS = [
Build("4411", "web", "passed", "feature/new-navigation-menu", "2m ago",
"Rework the navigation menu so keyboard users can reach every section"),
Build("4410", "billing", "failed", "main", "9m ago", "Bump httpx"),
]
# (header, attribute, minimum terminal width at which the column is shown)
COLUMNS = [
("ID", "id", 0),
("PROJECT", "project", 0),
("STATUS", "status", 0),
("BRANCH", "branch", 50),
("STARTED", "started", 70),
("MESSAGE", "commit_message", 100),
]
def terminal_width(explicit: int | None) -> int:
if explicit:
return explicit
return shutil.get_terminal_size(fallback=(80, 24)).columns
def build_table(rows: list[Build], width: int, wide: bool) -> Table:
table = Table(box=None, pad_edge=False, header_style="bold")
shown = [c for c in COLUMNS if wide or width >= c[2]]
def natural(attr: str, header: str) -> int:
longest = max([len(header)] + [len(str(getattr(r, attr))) for r in rows])
return longest if wide or attr in ("id", "project", "status") else min(longest, 24)
fixed = sum(natural(a, h) for h, a, _ in shown if a != "commit_message")
gutters = 2 * (len(shown) - 1)
for header, attr, _ in shown:
if attr == "commit_message": # the flexible column gets what is left
room = None if wide else max(20, width - fixed - gutters)
table.add_column(header, overflow="ellipsis", no_wrap=not wide, max_width=room)
else:
table.add_column(header, overflow="ellipsis", no_wrap=True,
min_width=natural(attr, header), max_width=natural(attr, header))
for r in rows:
table.add_row(*(str(getattr(r, attr)) for _, attr, _ in shown))
return table
@app.callback()
def main() -> None:
"""Build history."""
@app.command()
def builds(
width: Annotated[int | None, typer.Option("--width", min=40, help="Layout width (default: terminal).")] = None,
wide: Annotated[bool, typer.Option("--wide", "-w", help="Show every column in full.")] = False,
as_json: Annotated[bool, typer.Option("--json", help="Machine-readable output, never truncated.")] = False,
) -> None:
"""List recent builds, fitted to the terminal."""
if as_json:
typer.echo(json.dumps([asdict(b) for b in BUILDS]))
return
cols = terminal_width(width)
console = Console(width=10_000 if wide else cols, highlight=False)
console.print(build_table(BUILDS, cols, wide))
if __name__ == "__main__":
app()
How the layout works:
- Each column carries a minimum terminal width at which it appears: branch at 50 columns, start time at 70, the message at 100. Below those, the columns are dropped entirely — a narrow terminal still shows a clean table of what matters.
- Essential columns are sized to their content (
min_widthandmax_widthboth set to the natural width), so Rich never squeezes the ID or status into an ellipsis. - Useful columns are capped at 24 characters with
overflow="ellipsis", so one long branch name cannot push everything else off screen. - The message column gets the remaining space. Its
max_widthis computed from the terminal width minus the fixed columns and gutters, so it fills the line exactly and truncates with an ellipsis only when it must. --wideremoves all limits: every column shown in full, on a virtually unlimited console width, so lines may exceed the terminal — the user asked for completeness over fit, as withps -wworkubectl get -o wide.--jsonbypasses layout entirely. Machine output is complete regardless of width; truncating data meant for another program would be a bug.
UX considerations
- Show that something was cut. An ellipsis tells users there is more; silent truncation makes them think the value is shorter than it is — dangerous for paths and IDs.
- Never truncate identifiers users copy. An ID someone will paste into another command must appear in full, which is why it is an essential column here. If IDs are long (UUIDs), consider showing a unique prefix and accepting prefixes as input, as git does with commit hashes.
- Keep row count predictable. No-wrap columns keep one row per item, which is what people scan and what
wc -lcounts. Wrap only the flexible column, and only in--widemode. - Point to the escape hatch. When columns were dropped, a short footer on stderr — "(narrow terminal: use --wide for all columns)" — teaches the option at the moment it helps.
- Wrap prose to the width too. Help text and messages longer than a line read better wrapped at word boundaries; Rich wraps
console.printoutput automatically, andtextwrap.fill(text, width)does it for plain strings.
Testing the behaviour
Because shutil.get_terminal_size() and Rich both honour COLUMNS, tests can exercise every width through CliRunner's env= without a real terminal:
# tests/test_width.py
import json
import pytest
from typer.testing import CliRunner
from mytool.cli import BUILDS, app
runner = CliRunner()
def lines(result):
return [l for l in result.output.splitlines() if l.strip()]
@pytest.mark.parametrize("cols", [40, 60, 80, 120])
def test_output_fits_the_width(cols):
result = runner.invoke(app, ["builds"], env={"COLUMNS": str(cols)})
assert result.exit_code == 0
assert all(len(l) <= cols for l in lines(result)), result.output
def test_narrow_drops_low_priority_columns():
out = runner.invoke(app, ["builds", "--width", "45"]).output
assert "BRANCH" not in out and "STATUS" in out
def test_long_values_are_truncated_with_an_ellipsis():
out = runner.invoke(app, ["builds", "--width", "60"]).output
assert "…" in out and "feature/new-navigation-menu" not in out
def test_wide_shows_everything_in_full():
out = runner.invoke(app, ["builds", "--wide"]).output
assert "feature/new-navigation-menu" in out
assert "keyboard users can reach every section" in out
def test_json_is_never_truncated():
result = runner.invoke(app, ["builds", "--json"], env={"COLUMNS": "40"})
assert json.loads(result.output)[0]["branch"] == BUILDS[0].branch
The parametrised fit test is the core guarantee — at 40, 60, 80 and 120 columns, no line is wider than the terminal. The other tests pin the degradation strategy: which columns drop, that truncation shows an ellipsis, that --wide is complete, and that JSON is untouched at any width.
Conclusion
Terminal width is an input to your output. Read it with shutil.get_terminal_size() (honouring COLUMNS and falling back to 80), rank columns by importance, drop the least important on narrow screens, size essential columns to their content, cap and ellipsise the useful ones, let one flexible column absorb the rest, and give users --wide and --width for full or reproducible output. Keep machine output complete regardless, and test at several widths through COLUMNS. Your tables then read cleanly in a split pane and make full use of a wide screen.
Frequently asked questions
What width should output use when piped?
The fallback — 80 columns — or whatever COLUMNS says. Piped output is often read later in a pager or editor, and 80 is a safe default. For data meant for programs, provide --json or a delimited format instead of relying on table layout at all.
Should the tool react when the terminal is resized?
For ordinary commands, no: output is printed once. For live displays — progress bars, Rich Live, Textual apps — the libraries re-read the size and re-render automatically.
How do I handle wide characters like CJK text and emoji?
Rich measures display width in terminal cells rather than characters, so double-width characters are aligned correctly. len() does not; when computing widths yourself, use rich.cells.cell_len() instead.
Is a vertical layout better on very narrow screens?
Sometimes. Below about 40 columns, a "key: value" block per item (like kubectl describe) reads better than any table. Switch layouts at a threshold rather than squeezing a table further.