Rich is a Python library for rich text and beautiful formatting in the terminal.
Go to file
Will McGugan 03d6025bcb thread test 2020-09-26 16:01:04 +01:00
.github Update make command in black check 2020-08-21 17:22:34 +08:00
docs traceback improvements 2020-09-26 15:56:27 +01:00
examples fix more spelling 2020-09-16 07:20:22 +00:00
imgs projects using rich 2020-08-12 10:00:13 +01:00
rich missing quote 2020-09-26 15:58:16 +01:00
tests thread test 2020-09-26 16:01:04 +01:00
tools tests 2020-08-24 17:26:30 +01:00
.coveragerc prompt update 2020-07-20 18:52:01 +01:00
.gitignore improved jupyter support 2020-05-30 11:38:47 +01:00
.readthedocs.yml source path 2020-01-12 16:47:55 +00:00
CHANGELOG.md traceback improvements 2020-09-26 15:56:27 +01:00
CODE_OF_CONDUCT.md Create CODE_OF_CONDUCT.md 2020-02-24 11:23:14 +00:00
CONTRIBUTING.md rename make, update workflow and contributing 2020-08-21 09:20:36 +00:00
CONTRIBUTORS.md Add README.es.md in Spanish/Español 2020-09-17 15:55:22 -04:00
LICENSE forgotten files 2020-01-26 17:24:55 +00:00
Makefile rename make, update workflow and contributing 2020-08-21 09:20:36 +00:00
README.cn.md Add projects using Rich to Chinese documentation 2020-08-24 21:05:56 +08:00
README.es.md Add README.es.md in Spanish/Español 2020-09-17 15:55:22 -04:00
README.md capture 2020-09-23 15:53:41 +01:00
make.bat added docs 2019-12-26 17:20:46 +00:00
poetry.lock Bump pygments from 2.6.1 to 2.7.1 2020-09-18 05:33:34 +00:00
pull_request_template.md update black link in pr template 2020-08-21 09:23:54 +00:00
pyproject.toml traceback improvements 2020-09-26 15:56:27 +01:00
requirements-dev.txt Merge branch 'master' of github.com:willmcgugan/rich 2020-08-28 12:56:26 +01:00
setup.py added --page argument to markdown 2020-05-12 21:25:39 +01:00

README.md

Rich

PyPI version codecov Rich blog Twitter Follow

中文 readmelengua española readme

Rich is a Python library for rich text and beautiful formatting in the terminal.

The Rich API makes it easy to add color and style to terminal output. Rich can also render pretty tables, progress bars, markdown, syntax highlighted source code, tracebacks, and more — out of the box.

Features

For a video introduction to Rich see calmcode.io by @fishnets88.

See what people are saying about Rich.

Compatibility

Rich works with Linux, OSX, and Windows. True color / emoji works with new Windows Terminal, classic terminal is limited to 8 colors. Rich requires Python 3.6.1 or later.

Rich works with Jupyter notebooks with no additional configuration required.

Installing

Install with pip or your favorite PyPi package manager.

pip install rich

Rich print function

To effortlessly add rich output to your application, you can import the rich print method, which has the same signature as the builtin Python function. Try this:

from rich import print

print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())

Hello World

Rich REPL

Rich can be installed in the Python REPL, so that any data structures will be pretty printed and highlighted.

>>> from rich import pretty
>>> pretty.install()

REPL

Rich Inspect

Rich has an inspect function which can produce a report on any Python object, such as class, instance, or builtin.

>>> from rich import inspect
>>> inspect(str, methods=True)

Using the Console

For more control over rich terminal content, import and construct a Console object.

from rich.console import Console

console = Console()

The Console object has a print method which has an intentionally similar interface to the builtin print function. Here's an example of use:

console.print("Hello", "World!")

As you might expect, this will print "Hello World!" to the terminal. Note that unlike the builtin print function, Rich will word-wrap your text to fit within the terminal width.

There are a few ways of adding color and style to your output. You can set a style for the entire output by adding a style keyword argument. Here's an example:

console.print("Hello", "World!", style="bold red")

The output will be something like the following:

Hello World

That's fine for styling a line of text at a time. For more finely grained styling, Rich renders a special markup which is similar in syntax to bbcode. Here's an example:

console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].")

Console Markup

Console logging

The Console object has a log() method which has a similar interface to print(), but also renders a column for the current time and the file and line which made the call. By default Rich will do syntax highlighting for Python structures and for repr strings. If you log a collection (i.e. a dict or a list) Rich will pretty print it so that it fits in the available space. Here's an example of some of these features.

from rich.console import Console
console = Console()

test_data = [
    {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",},
    {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
    {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"},
]

def test_log():
    enabled = False
    context = {
        "foo": "bar",
    }
    movies = ["Deadpool", "Rise of the Skywalker"]
    console.log("Hello from", console, "!")
    console.log(test_data, log_locals=True)


test_log()

The above produces the following output:

Log

Note the log_locals argument, which outputs a table containing the local variables where the log method was called.

The log method could be used for logging to the terminal for long running applications such as servers, but is also a very nice debugging aid.

Logging Handler

You can also use the builtin Handler class to format and colorize output from Python's logging module. Here's an example of the output:

Logging

Emoji

To insert an emoji in to console output place the name between two colons. Here's an example:

>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:")
😃 🧛 💩 👍 🦝

Please use this feature wisely.

Tables

Rich can render flexible tables with unicode box characters. There is a large variety of formatting options for borders, styles, cell alignment etc.

table movie

The animation above was generated with table_movie.py in the examples directory.

Here's a simpler table example:

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

console = Console()

table = Table(show_header=True, header_style="bold magenta")
table.add_column("Date", style="dim", width=12)
table.add_column("Title")
table.add_column("Production Budget", justify="right")
table.add_column("Box Office", justify="right")
table.add_row(
    "Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
)
table.add_row(
    "May 25, 2018",
    "[red]Solo[/red]: A Star Wars Story",
    "$275,000,000",
    "$393,151,347",
)
table.add_row(
    "Dec 15, 2017",
    "Star Wars Ep. VIII: The Last Jedi",
    "$262,000,000",
    "[bold]$1,332,539,889[/bold]",
)

console.print(table)

This produces the following output:

table

Note that console markup is rendered in the same way as print() and log(). In fact, anything that is renderable by Rich may be included in the headers / rows (even other tables).

The Table class is smart enough to resize columns to fit the available width of the terminal, wrapping text as required. Here's the same example, with the terminal made smaller than the table above:

table2

Progress Bars

Rich can render multiple flicker-free progress bars to track long-running tasks.

For basic usage, wrap any sequence in the track function and iterate over the result. Here's an example:

from rich.progress import track

for step in track(range(100)):
    do_step(step)

It's not much harder to add multiple progress bars. Here's an example taken from the docs:

progress

The columns may be configured to show any details you want. Built-in columns include percentage complete, file size, file speed, and time remaining. Here's another example showing a download in progress:

progress

To try this out yourself, see examples/downloader.py which can download multiple URLs simultaneously while displaying progress.

Columns

Rich can render content in neat columns with equal or optimal width. Here's a very basic clone of the (MacOS / Linux) ls command which displays a directory listing in columns:

import os

from rich import print
from rich.columns import Columns

directory = os.listdir(sys.argv[1])
print(Columns(directory))

The following screenshot is the output from the columns example which displays data pulled from an API in columns:

columns

Markdown

Rich can render markdown and does a reasonable job of translating the formatting to the terminal.

To render markdown import the Markdown class and construct it with a string containing markdown code. Then print it to the console. Here's an example:

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

console = Console()
with open("README.md") as readme:
    markdown = Markdown(readme.read())
console.print(markdown)

This will produce output something like the following:

markdown

Syntax Highlighting

Rich uses the pygments library to implement syntax highlighting. Usage is similar to rendering markdown; construct a Syntax object and print it to the console. Here's an example:

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

my_code = '''
def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
    """Iterate and generate a tuple with a flag for first and last value."""
    iter_values = iter(values)
    try:
        previous_value = next(iter_values)
    except StopIteration:
        return
    first = True
    for value in iter_values:
        yield first, False, previous_value
        first = False
        previous_value = value
    yield first, True, previous_value
'''
syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True)
console = Console()
console.print(syntax)

This will produce the following output:

syntax

Tracebacks

Rich can render beautiful tracebacks which are easier to read and show more code than standard Python tracebacks. You can set Rich as the default traceback handler so all uncaught exceptions will be rendered by Rich.

Here's what it looks like on OSX (similar on Linux):

traceback

Project using Rich

Here are a few projects using Rich: