Code of the Day
IntermediateBetter Interfaces

Rich text output

Use the Rich library to add colour, panels, and syntax highlighting to your CLI output with minimal code.

UtilitiesIntermediate8 min read
Recommended first
By the end of this lesson you will be able to:
  • Use rich.print() for inline markup (bold, colour, italic)
  • Create a Panel with a title to frame output clearly
  • Use Syntax for highlighted code output

The Rich library is a Python package for rendering styled text, tables, progress bars, panels, and more in the terminal. Its API is straightforward: in the simplest case you just replace print with rich.print and add markup tags.

Inline markup with rich.print()

Rich supports a simple markup syntax using square brackets. [bold]text[/bold] makes text bold. [green]text[/] makes it green. You can combine them: [bold red]Error[/]. The [/] closes the most recently opened tag.

from rich import print

print("[bold green]Success:[/] 42 files processed")
print("[bold red]Error:[/] could not open config.toml")
print("[yellow]Warning:[/] output directory already exists")

This is all it takes to move from monochrome walls of text to scannable, coloured status lines.

Framing output with Panel

When you want to draw attention to a block of output — a summary, an error message, a config preview — wrap it in a Panel. A Panel draws a box around the content with an optional title.

from rich.panel import Panel
from rich import print

print(Panel("Build completed in 1.4 s", title="[bold green]Result[/]"))
print(Panel("config.toml not found\nRun 'mytool init' to create one",
            title="[bold red]Error[/]", border_style="red"))

Panels make the most important output impossible to miss.

Highlighting code with Syntax

If your tool outputs code, configuration, or structured text, Syntax applies language-aware highlighting:

from rich.syntax import Syntax
from rich.console import Console

console = Console()
code = "def greet(name):\n    print(f'Hello, {name}')"
console.print(Syntax(code, "python", theme="monokai", line_numbers=True))

Try it

Rich is available in the Pyodide environment used by the browser runner. Run the demo below to see markup, a Panel, and Syntax rendering in action:

Python — editable, runs in your browser

Rich detects whether its output is going to a real terminal. When you pipe a Rich tool to another program (e.g. mytool | grep error), Rich automatically strips ANSI codes so the downstream tool gets clean text. You get colour for humans and plain text for machines at no extra cost.

Where to go next

Next: progress bars — when to show a bar versus a spinner, and what information a good progress indicator communicates.

Finished reading? Mark it complete to track your progress.

On this page