ZetCode

Python rich

last modified November 18, 2026 Python 3.15

In this article we create rich text and advanced formatting in the terminal with the Python rich library.

Rich adds colours and styles to terminal output with a simple markup language. It renders tables, panels, columns, trees, Markdown, syntax-highlighted code, progress bars, and readable tracebacks, and it pretty prints Python data structures. Rich works in Linux, macOS, and Windows terminals and in Jupyter notebooks.

When the output is not a terminal, for example when it is redirected to a file or a pipe, rich leaves out the colours and the animations but keeps the layout. The text outputs in this article were captured this way. For the examples where colour is the point, we show a picture of the terminal output instead; it was exported with rich itself, as shown in the last example. The examples were run with rich 15.0 on Python 3.15.

$ pip install rich

Printing with markup

The quickest way to use rich is its print function, a drop-in replacement for the built-in one. It understands console markup and highlights the printed data.

simple.py
from datetime import date

from rich import print as rprint

rprint('[italic red]an old falcon[/italic red]')
rprint('[bold blue on white] a stormy night [/]')
rprint('[link=https://zetcode.com]ZetCode[/link] :thumbs_up:')

rprint({'name': 'John Doe', 'occupation': 'gardener', 'active': True})
rprint(date.today(), [1, 2.5, None, 'sky'])

We import the rich print function as rprint so that it does not hide the built-in print.

Markup tags are placed between square brackets. A style applies from the opening tag to the matching closing tag; [/] closes the last opened style. The bold blue on white style sets the text attribute, the foreground colour, and the background colour. The link tag creates a hyperlink in terminals that support it, and emoji codes such as :thumbs_up: are replaced with the emoji characters.

Containers and other Python objects are pretty printed and highlighted: strings, numbers, None, booleans, and dates each get their own colour.

Rich print with markup
Figure: Rich print with markup

Styles

A style is a string of attributes and colours. Besides markup tags, it can be passed to the print method of a Console object, which is the central object of the library.

styles.py
from rich.console import Console

console = Console()

console.print('bold red', style='bold red')
console.print('underlined, on a hex colour', style='underline #ffffff on #3465a4')
console.print('color(208) and dim', style='color(208) dim', highlight=False)
console.print('Several styles: [b]bold[/b], [i]italic[/i], [s]strike[/s], '
              '[reverse]reverse[/reverse], [green3]green3[/]')
console.print('Escaped markup: \\[not a tag]')
console.print('No highlighting: 3.15 None True', highlight=False)
console.print('Highlighting: 3.15 None True /usr/bin https://zetcode.com')

The style parameter styles the whole text. Colours can be given by one of 256 names (such as green3), as a hex value, as an rgb(r,g,b) triple, or as a palette number with color(n). Attributes include bold, dim, italic, underline, strike, and reverse, and most of them have a short form such as b or i.

A backslash before an opening bracket escapes the markup. By default, the console highlights numbers, constants, paths, URLs, and other patterns in printed strings; we turn it off with highlight=False. Rich detects the colour capabilities of the terminal and converts the colours if needed.

Rich styles
Figure: Rich styles

Console log

The log method of the console prints the current time on the left and the file name and line number of the call on the right. It is handy for debugging.

console_log.py
from rich.console import Console

console = Console()

users = [{'name': 'John Doe', 'age': 34}, {'name': 'Lucy Smith', 'age': 27}]

console.log('loading users')
console.log(users)
console.log('[green]done[/green]', len(users), 'users')

The time is printed only when it changes; the following lines leave the column empty. Data structures are pretty printed over multiple lines if they do not fit the width.

$ python console_log.py
[22:00:54] loading users                                        console_log.py:7
           [                                                    console_log.py:8
               {'name': 'John Doe', 'age': 34},
               {'name': 'Lucy Smith', 'age': 27}
           ]
           done 2 users                                         console_log.py:9

Text

The Text class is a string with styled regions. Instead of markup, we apply the styles with methods, which is useful when the text comes from the user and may contain square brackets.

rich_text.py
from rich.console import Console
from rich.text import Text

text = Text('Python is a general-purpose, dynamic, object-oriented '
            'programming language.', style='italic')

text.stylize('bold cyan', 0, 6)
text.highlight_words(['dynamic', 'object-oriented'], style='yellow')
text.append(' Created by Guido van Rossum.', style='green')

console = Console(width=60)
console.print(text)

The text is created with the italic base style. The stylize method styles the characters from index 0 to 6, and highlight_words styles all occurrences of the given words. The append method adds another piece of text with its own style.

We create the console with a fixed width of 60 characters; rich wraps the text at word boundaries. The plain attribute of a Text object holds the string without the styles and spans holds the list of styled regions.

Rich Text object
Figure: Rich Text object

Rules

A rule is a horizontal line with an optional title. It divides output into sections.

rules.py
from rich.console import Console

console = Console(width=60)

console.rule('Python')
console.print('Python is a general-purpose, dynamic, object-oriented '
              'programming language.')

console.rule('[bold]F#[/bold]', style='red', align='left')
console.print('F# is a universal programming language for writing '
              'succinct, robust and performant code.')

console.rule(characters='=')

The title is centred by default; the align parameter moves it to the left or right. The style parameter sets the style of the line, and characters sets the characters the line is drawn with. A rule spans the whole width of the console.

$ python rules.py
────────────────────────── Python ──────────────────────────
Python is a general-purpose, dynamic, object-oriented
programming language.
F# ─────────────────────────────────────────────────────────
F# is a universal programming language for writing succinct,
robust and performant code.
============================================================

Panels

A panel draws a border around its content.

panels.py
from rich import box
from rich.console import Console
from rich.panel import Panel

console = Console(width=60)

console.print(Panel('an old falcon'))
console.print(Panel.fit('an old falcon', title='Falcon', subtitle='bird',
                        border_style='blue'))
console.print(Panel.fit('an old falcon', box=box.ASCII, padding=(1, 4)))

By default, a panel expands to the full width of the console. The Panel.fit constructor makes it only as wide as its content. A panel can have a title and a subtitle in the border. The box parameter selects one of the box styles from the rich.box module, and padding adds space around the content (vertical and horizontal).

$ python panels.py
╭──────────────────────────────────────────────────────────╮
│ an old falcon                                            │
╰──────────────────────────────────────────────────────────╯
╭─── Falcon ────╮
│ an old falcon │
╰──── bird ─────╯
+---------------------+
|                     |
|    an old falcon    |
|                     |
+---------------------+

Columns

The Columns class arranges renderables into as many columns as fit the console width.

cols.py
from pathlib import Path

from rich.columns import Columns
from rich.console import Console
from rich.panel import Panel

words = Path('words.txt').read_text().split()

console = Console(width=60)
console.print(Columns(words, equal=True, expand=True))
console.print()
console.print(Columns([Panel(word) for word in words[:6]]))

We read words from a file. With equal=True, all columns have the same width, and expand=True spreads them over the whole width. In the second call, we place the first six words into panels; any renderable can be placed in columns.

$ python cols.py
cup      snow   falcon   eagle  forest   water  atom    lamp
pencil   book   phone    chart  cloud    horse  stream  nail
boot     wind   storm

╭─────╮ ╭──────╮ ╭────────╮ ╭───────╮ ╭────────╮ ╭───────╮
│ cup │ │ snow │ │ falcon │ │ eagle │ │ forest │ │ water │
╰─────╯ ╰──────╯ ╰────────╯ ╰───────╯ ╰────────╯ ╰───────╯

Groups

Most renderables accept a single child. A group combines several renderables into one, so we can, for instance, put them into one panel.

groups.py
from rich.console import Console, Group, group
from rich.panel import Panel
from rich.rule import Rule


@group()
def get_panels():

    for word in ('an old falcon', 'a long stormy night'):
        yield Panel(word, style='on blue')


console = Console(width=60)

console.print(Panel(get_panels(), title='group decorator'))

g = Group(Rule('Users'), 'John Doe', 'Lucy Smith', Rule())
console.print(Panel.fit(g, title='Group'))

The @group decorator turns a generator function into a function that returns a group of the yielded renderables. The Group class does the same for renderables passed as arguments; plain strings are allowed too.

$ python groups.py
╭──────────────────── group decorator ─────────────────────╮
│ ╭──────────────────────────────────────────────────────╮ │
│ │ an old falcon                                        │ │
│ ╰──────────────────────────────────────────────────────╯ │
│ ╭──────────────────────────────────────────────────────╮ │
│ │ a long stormy night                                  │ │
│ ╰──────────────────────────────────────────────────────╯ │
╰──────────────────────────────────────────────────────────╯
╭── Group ───╮
│ ─ Users ── │
│ John Doe   │
│ Lucy Smith │
│ ────────── │
╰────────────╯

Tables

The Table class displays tabular data. Columns adjust their width to the content and the console size; long values are wrapped.

table.py
from rich import box
from rich.console import Console
from rich.table import Table

table = Table(title='Users', box=box.SIMPLE_HEAVY, caption='4 users',
              caption_justify='left')

table.add_column('Name', style='cyan')
table.add_column('Occupation')
table.add_column('Date of birth', justify='right', style='green')
table.add_column('Salary', justify='right')

table.add_row('John Doe', 'gardener', '1997-05-12', '1 200')
table.add_row('Jane Doe', 'teacher', '1983-05-16', '1 850')
table.add_row('Robert Smith', 'driver', '2001-04-02', '980')
table.add_row('Maria Smith', 'cook', '1976-09-21', '1 340', end_section=True)
table.add_row('Total', '', '', '[bold]5 370[/]')

console = Console()
console.print(table)

The table has a title above it and a caption below it. The add_column method sets the header, the style, and the justification of a column. The add_row method adds a row; cells may contain markup or other renderables. With end_section=True, a line separates the row from the next one, which we use for the total.

$ python table.py
                        Users

  Name           Occupation   Date of birth   Salary
 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  John Doe       gardener        1997-05-12    1 200
  Jane Doe       teacher         1983-05-16    1 850
  Robert Smith   driver          2001-04-02      980
  Maria Smith    cook            1976-09-21    1 340

  Total                                        5 370

4 users

Live data in a table

In the next example, we display Bitcoin daily prices in a table. The data is fetched from the Binance exchange with the ccxt library (pip install ccxt).

btc_ohlcv.py
import asyncio
from datetime import datetime, UTC

import ccxt.async_support as ccxt
from rich import box
from rich.console import Console
from rich.table import Table


async def main():

    binance = ccxt.binance()

    try:
        data = await binance.fetch_ohlcv('BTC/USDT', '1d', limit=7)
    finally:
        await binance.close()

    table = Table(title='Binance - BTC/USDT', box=box.ASCII)

    table.add_column('Date', style='steel_blue')
    for name in ('Open', 'High', 'Low', 'Close', 'Volume'):
        table.add_column(name, justify='right')

    for ts, o, h, l, c, v in data:
        d = datetime.fromtimestamp(ts / 1000, UTC)
        table.add_row(f'{d:%Y-%m-%d}', f'{o:.2f}', f'{h:.2f}', f'{l:.2f}',
                      f'{c:.2f}', f'{v:.3f}')

    Console().print(table)

asyncio.run(main())

The fetch_ohlcv method returns the open, high, low, close prices and the volume for the last seven days. The timestamps are in milliseconds since the epoch; we convert them to dates in UTC. The box.ASCII style draws the table with ASCII characters only. The output reflects the market at the time of running, so it is different every time.

$ python btc_ohlcv.py
                          Binance - BTC/USDT
+--------------------------------------------------------------------+
| Date       |     Open |     High |      Low |    Close |    Volume |
|------------+----------+----------+----------+----------+-----------|
| 2026-11-12 | 74015.20 | 74217.49 | 71113.06 | 71460.00 | 15228.240 |
| 2026-11-13 | 71460.00 | 71514.01 | 67568.00 | 68314.00 | 29648.752 |
| 2026-11-14 | 68314.01 | 68446.21 | 63320.00 | 64150.00 | 32674.752 |
| 2026-11-15 | 64150.01 | 66132.01 | 62006.00 | 65351.05 | 29231.160 |
| 2026-11-16 | 65351.05 | 65696.16 | 63905.01 | 64882.87 | 21929.236 |
| 2026-11-17 | 64882.88 | 65447.00 | 63336.00 | 64947.35 | 28316.763 |
| 2026-11-18 | 64947.36 | 65002.00 | 62279.36 | 62648.00 | 16469.031 |
+--------------------------------------------------------------------+

Trees

The Tree class displays hierarchical data with guide lines.

tree_ex.py
from pathlib import Path

from rich.console import Console
from rich.tree import Tree


def walk(path, tree):

    for p in sorted(path.iterdir(), key=lambda p: (p.is_file(), p.name)):
        if p.is_dir():
            walk(p, tree.add(f'[bold blue]{p.name}/'))
        else:
            tree.add(f'{p.name} [dim]({p.stat().st_size} B)')


root = Path('project')
tree = Tree(f'[bold]{root}/', guide_style='bright_black')
walk(root, tree)

Console().print(tree)

The add method adds a child node and returns it, so we can add grandchildren to it. The walk function recursively adds the directories and files of a small project; directories go first. The guide_style parameter styles the guide lines.

$ python tree_ex.py
project/
├── src/
│   └── shop/
│       ├── __init__.py (23 B)
│       └── cart.py (61 B)
├── tests/
│   └── test_cart.py (72 B)
├── README.md (39 B)
└── pyproject.toml (69 B)

Pretty printing and inspect

The rich.pretty module formats Python data structures. The inspect function produces a report on any Python object.

pretty_ex.py
from dataclasses import dataclass, field

from rich import inspect
from rich.pretty import pprint


@dataclass
class User:
    name: str
    occupation: str
    tags: list[str] = field(default_factory=list)


data = {
    'users': [User('John Doe', 'gardener', ['admin', 'staff']),
              User('Lucy Smith', 'teacher')],
    'counts': list(range(30)),
    'meta': {'version': (3, 15), 'debug': False},
}

pprint(data, max_length=8)
inspect(User('Roger Roe', 'driver'), title='Roger')

The pprint function prints the data with indentation guides. The max_length parameter abbreviates long containers. Dataclasses are printed with their fields.

The inspect function shows the signature, the representation, and the attributes of an object. Its methods=True parameter adds the methods and help=True adds the docstrings.

$ python pretty_ex.py
{
│   'users': [
│   │   User(name='John Doe', occupation='gardener', tags=['admin', 'staff']),
│   │   User(name='Lucy Smith', occupation='teacher', tags=[])
│   ],
│   'counts': [0, 1, 2, 3, 4, 5, 6, 7, ... +22],
│   'meta': {'version': (3, 15), 'debug': False}
}
╭──────────────────────────── Roger ────────────────────────────╮
│ User(name: str, occupation: str, tags: list[str] = <factory>) │
│                                                               │
│ ╭───────────────────────────────────────────────────────────╮ │
│ │ User(name='Roger Roe', occupation='driver', tags=[])      │ │
│ ╰───────────────────────────────────────────────────────────╯ │
│                                                               │
│       name = 'Roger Roe'                                      │
│ occupation = 'driver'                                         │
│       tags = []                                               │
╰───────────────────────────────────────────────────────────────╯

Markdown

Rich renders Markdown documents in the terminal, including tables, lists, quotes, and highlighted code blocks.

langs.md
# Programming languages

A programming language is a *formal language* used to write **programs**.

## Popular languages

| Language | Typing  | First release |
|----------|---------|---------------|
| Python   | dynamic | 1991          |
| Go       | static  | 2012          |
| F#       | static  | 2005          |

1. Python is used in data science and web development.
2. Go is used for networking and cloud services.

> Code is read much more often than it is written.

```python
words = ['sky', 'cup', 'forest']
print(sorted(words, key=len))
```

This is our Markdown document.

markdown_ex.py
from pathlib import Path

from rich.console import Console
from rich.markdown import Markdown

md = Markdown(Path('langs.md').read_text(), code_theme='monokai')

console = Console(width=70)
console.print(md)

We read the file and pass its contents to the Markdown class. The code_theme parameter sets the Pygments theme for the code blocks.

Rich Markdown rendering
Figure: Rich Markdown rendering

Syntax highlighting

The Syntax class highlights source code. It uses Pygments, which is installed together with rich, and supports hundreds of languages.

users.py
from dataclasses import dataclass


@dataclass
class User:
    name: str
    salary: int


users = [User('Robert Novak', 1770), User('John Doe', 1230),
         User('Lucy Novak', 670), User('Ben Walter', 2050)]

avg = sum(u.salary for u in users) / len(users)

for user in users:
    if user.salary > avg:
        print(f'{user.name:12} {user.salary}')  # above average

This is the Python file we are going to highlight.

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

stx = Syntax.from_path('users.py', theme='monokai', line_numbers=True,
                       highlight_lines={16})

console = Console(width=72)
console.print(stx)
console.print(Syntax('SELECT name FROM users WHERE salary > 1000;', 'sql'))

The Syntax.from_path constructor reads a file and guesses the language from the file name. We choose the monokai theme, turn on line numbers, and mark line 16. When the code is in a string, we create a Syntax object directly and give the language name.

Rich syntax highlighting
Figure: Rich syntax highlighting

Progress bars

Rich shows progress bars for long-running tasks. The track function wraps an iterable and updates a bar on each iteration.

progress_ex.py
import time

from rich.progress import Progress, track

for _ in track(range(20), description='Processing...'):
    time.sleep(0.05)

with Progress() as progress:

    download = progress.add_task('[cyan]Downloading', total=50)
    unpack = progress.add_task('[green]Unpacking', total=30)

    while not progress.finished:
        progress.advance(download, 2)
        progress.advance(unpack)
        time.sleep(0.02)

For several bars, we use the Progress class as a context manager. The add_task method creates a task with a total number of steps and advance moves it forward. The finished attribute is true when all tasks are complete.

In a terminal, the bars are animated with the elapsed and estimated remaining time. When the output is redirected, rich prints only the final state.

$ python progress_ex.py
Processing... ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:01
Downloading ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00
Unpacking   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00

Logging

The RichHandler class is a handler for the standard logging module. It formats log records into columns and colours the levels.

logging_ex.py
import logging

from rich.logging import RichHandler

logging.basicConfig(level='DEBUG', format='%(message)s', datefmt='[%X]',
                    handlers=[RichHandler(rich_tracebacks=True)])

log = logging.getLogger('app')

log.debug('reading configuration from %s', '/etc/app.toml')
log.info('server started on port %d', 8080)
log.warning('disk usage at %d%%', 91)

try:
    1 / 0
except ZeroDivisionError:
    log.exception('computation failed')

The handler adds the time, the level, and the source location itself, so the format string contains only the message. With rich_tracebacks=True, exceptions logged with log.exception are rendered by rich.

$ python logging_ex.py
[22:01:00] DEBUG    reading configuration from /etc/app.toml    logging_ex.py:10
           INFO     server started on port 8080                 logging_ex.py:11
           WARNING  disk usage at 91%                           logging_ex.py:12
           ERROR    computation failed                          logging_ex.py:17
                    ╭─── Traceback (most recent call last) ───╮
                    │ /home/user/python/logging_ex.py:15 in   │
                    │ <module>                                │
                    │                                         │
                    │   12 log.warning('disk usage at %d%%',  │
                    │   13                                    │
                    │   14 try:                               │
                    │ ❱ 15 │   1 / 0                          │
                    │   16 except ZeroDivisionError:          │
                    │   17 │   log.exception('computation fai │
                    │   18                                    │
                    ╰─────────────────────────────────────────╯
                    ZeroDivisionError: division by zero

Tracebacks

The install function from rich.traceback replaces the default exception hook. Uncaught exceptions are then shown with highlighted source code around each frame.

traceback_ex.py
from rich.traceback import install

install(show_locals=True, width=72)


def average(values):

    total = sum(values)
    return total / len(values)


def report(data):

    for name, values in data.items():
        print(name, average(values))


report({'math': [1, 2, 3], 'physics': []})

With show_locals=True, each frame also lists the values of its local variables, which often reveals the cause of the error right away: here, the list of values for physics is empty. The traceback is printed to standard error.

$ python traceback_ex.py
math 2.0
╭───────────────── Traceback (most recent call last) ──────────────────╮
│ /home/user/python/traceback_ex.py:18 in <module>                     │
│                                                                      │
│   15 │   │   print(name, average(values))                            │
│   16                                                                 │
│   17                                                                 │
│ ❱ 18 report({'math': [1, 2, 3], 'physics': []})                      │
│   19                                                                 │
│                                                                      │
│ /home/user/python/traceback_ex.py:15 in report                       │
│                                                                      │
│   12 def report(data):                                               │
│   13 │                                                               │
│   14 │   for name, values in data.items():                           │
│ ❱ 15 │   │   print(name, average(values))                            │
│   16                                                                 │
│   17                                                                 │
│   18 report({'math': [1, 2, 3], 'physics': []})                      │
│                                                                      │
│ ╭────────────────── locals ───────────────────╮                      │
│ │   data = {'math': [1, 2, 3], 'physics': []} │                      │
│ │   name = 'physics'                          │                      │
│ │ values = []                                 │                      │
│ ╰─────────────────────────────────────────────╯                      │
│                                                                      │
│ /home/user/python/traceback_ex.py:9 in average                       │
│                                                                      │
│    6 def average(values):                                            │
│    7 │                                                               │
│    8 │   total = sum(values)                                         │
│ ❱  9 │   return total / len(values)                                  │
│   10                                                                 │
│   11                                                                 │
│   12 def report(data):                                               │
│                                                                      │
│ ╭── locals ───╮                                                      │
│ │  total = 0  │                                                      │
│ │ values = [] │                                                      │
│ ╰─────────────╯                                                      │
╰──────────────────────────────────────────────────────────────────────╯
ZeroDivisionError: division by zero

Exporting output

A console created with record=True keeps everything it prints. The recording can be saved as SVG, HTML, or plain text.

export.py
from pathlib import Path

from rich.console import Console
from rich.table import Table

console = Console(record=True, width=50)

table = Table(title='Languages')
table.add_column('Name', style='cyan')
table.add_column('Since', justify='right', style='green')

table.add_row('Python', '1991')
table.add_row('Go', '2012')

console.print(table)

console.save_svg('languages.svg', title='export.py', clear=False)
console.save_html('languages.html', clear=False)
console.save_text('languages.txt')

for name in ('languages.svg', 'languages.html', 'languages.txt'):
    print(f'{name:15} {Path(name).stat().st_size:6} bytes')

The save_svg, save_html, and save_text methods write the recorded output to a file. By default they clear the recording, so we pass clear=False to all but the last one. The SVG file is an image of a terminal window with the coloured output; the pictures in this article were made this way.

$ python export.py
    Languages
┏━━━━━━━━┳━━━━━━━┓
┃ Name   ┃ Since ┃
┡━━━━━━━━╇━━━━━━━┩
│ Python │  1991 │
│ Go     │  2012 │
└────────┴───────┘
languages.svg     6611 bytes
languages.html     878 bytes
languages.txt      259 bytes

Source

Rich documentation

Rich on GitHub

In this article we have created rich text and advanced formatting in the terminal with the Python rich library. See also the PrettyTable, click, and logging tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.