rich/README.md

440 lines
16 KiB
Markdown
Raw Normal View History

2023-01-20 08:10:19 +00:00
[![Supported Python Versions](https://img.shields.io/pypi/pyversions/rich/13.2.0)](https://pypi.org/project/rich/) [![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich)
2021-04-05 10:04:34 +00:00
[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich)
2022-04-25 14:38:34 +00:00
[![codecov](https://img.shields.io/codecov/c/github/Textualize/rich?label=codecov&logo=codecov)](https://codecov.io/gh/Textualize/rich)
2020-05-27 10:59:22 +00:00
[![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/)
2020-04-14 14:38:10 +00:00
[![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan)
2019-12-23 16:21:51 +00:00
2022-09-19 10:27:11 +00:00
![Logo](https://github.com/textualize/rich/raw/master/imgs/logo.svg)
[English readme](https://github.com/textualize/rich/blob/master/README.md)
• [简体中文 readme](https://github.com/textualize/rich/blob/master/README.cn.md)
• [正體中文 readme](https://github.com/textualize/rich/blob/master/README.zh-tw.md)
• [Lengua española readme](https://github.com/textualize/rich/blob/master/README.es.md)
• [Deutsche readme](https://github.com/textualize/rich/blob/master/README.de.md)
• [Läs på svenska](https://github.com/textualize/rich/blob/master/README.sv.md)
• [日本語 readme](https://github.com/textualize/rich/blob/master/README.ja.md)
• [한국어 readme](https://github.com/textualize/rich/blob/master/README.kr.md)
• [Français readme](https://github.com/textualize/rich/blob/master/README.fr.md)
• [Schwizerdütsch readme](https://github.com/textualize/rich/blob/master/README.de-ch.md)
• [हिन्दी readme](https://github.com/textualize/rich/blob/master/README.hi.md)
• [Português brasileiro readme](https://github.com/textualize/rich/blob/master/README.pt-br.md)
• [Italian readme](https://github.com/textualize/rich/blob/master/README.it.md)
• [Русский readme](https://github.com/textualize/rich/blob/master/README.ru.md)
• [Indonesian readme](https://github.com/textualize/rich/blob/master/README.id.md)
• [فارسی readme](https://github.com/textualize/rich/blob/master/README.fa.md)
• [Türkçe readme](https://github.com/textualize/rich/blob/master/README.tr.md)
2023-02-23 15:40:07 +00:00
• [Polskie readme](https://github.com/textualize/rich/blob/master/README.pl.md)
2020-07-03 19:55:58 +00:00
2020-06-06 11:08:07 +00:00
Rich is a Python library for _rich_ text and beautiful formatting in the terminal.
2019-12-23 16:21:51 +00:00
2020-06-06 12:11:29 +00:00
The [Rich API](https://rich.readthedocs.io/en/latest/) 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.
2019-12-23 16:21:51 +00:00
2022-09-19 10:27:11 +00:00
![Features](https://github.com/textualize/rich/raw/master/imgs/features.png)
2020-03-27 20:01:42 +00:00
2020-06-07 09:53:34 +00:00
For a video introduction to Rich see [calmcode.io](https://calmcode.io/rich/introduction.html) by [@fishnets88](https://twitter.com/fishnets88).
2020-06-06 11:08:07 +00:00
2020-08-12 09:35:54 +00:00
See what [people are saying about Rich](https://www.willmcgugan.com/blog/pages/post/rich-tweets/).
2020-03-28 15:43:11 +00:00
## Compatibility
Rich works with Linux, OSX, and Windows. True color / emoji works with new Windows Terminal, classic terminal is limited to 16 colors. Rich requires Python 3.7 or later.
2020-03-28 15:43:11 +00:00
2020-07-16 17:35:16 +00:00
Rich works with [Jupyter notebooks](https://jupyter.org/) with no additional configuration required.
2020-05-31 14:19:54 +00:00
2019-12-23 16:21:51 +00:00
## Installing
2021-11-13 11:19:11 +00:00
Install with `pip` or your favorite PyPI package manager.
2019-12-25 16:33:52 +00:00
```sh
python -m pip install rich
2019-12-25 16:33:52 +00:00
```
2019-12-23 16:21:51 +00:00
2020-12-02 16:50:21 +00:00
Run the following to test Rich output on your terminal:
```sh
2020-12-02 16:50:21 +00:00
python -m rich
```
2021-02-20 22:10:25 +00:00
## Rich Print
2020-01-22 16:00:03 +00:00
To effortlessly add rich output to your application, you can import the [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) method, which has the same signature as the builtin Python function. Try this:
```python
from rich import print
print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())
```
2022-09-19 10:27:11 +00:00
![Hello World](https://github.com/textualize/rich/raw/master/imgs/print.png)
2020-02-22 20:04:20 +00:00
2020-08-08 10:47:10 +00:00
## Rich REPL
Rich can be installed in the Python REPL, so that any data structures will be pretty printed and highlighted.
```python
>>> from rich import pretty
>>> pretty.install()
```
2022-09-19 10:27:11 +00:00
![REPL](https://github.com/textualize/rich/raw/master/imgs/repl.png)
2020-08-08 10:47:10 +00:00
2020-04-14 14:38:10 +00:00
## Using the Console
2019-12-23 16:21:51 +00:00
2020-04-14 14:38:10 +00:00
For more control over rich terminal content, import and construct a [Console](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console) object.
2019-12-23 16:21:51 +00:00
```python
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:
2020-01-22 16:00:03 +00:00
```python
2019-12-23 16:21:51 +00:00
console.print("Hello", "World!")
```
2020-02-22 20:04:20 +00:00
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.
2019-12-23 16:21:51 +00:00
2019-12-23 19:29:52 +00:00
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:
2019-12-23 16:21:51 +00:00
2020-01-22 16:00:03 +00:00
```python
2019-12-23 16:21:51 +00:00
console.print("Hello", "World!", style="bold red")
```
The output will be something like the following:
2022-09-19 10:27:11 +00:00
![Hello World](https://github.com/textualize/rich/raw/master/imgs/hello_world.png)
2019-12-23 16:32:46 +00:00
2019-12-23 16:21:51 +00:00
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](https://en.wikipedia.org/wiki/BBCode). Here's an example:
2019-12-23 19:29:52 +00:00
```python
console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].")
```
2019-12-23 16:21:51 +00:00
2022-09-19 10:27:11 +00:00
![Console Markup](https://github.com/textualize/rich/raw/master/imgs/where_there_is_a_will.png)
2019-12-23 16:21:51 +00:00
2021-02-21 16:59:38 +00:00
You can use a Console object to generate sophisticated output with minimal effort. See the [Console API](https://rich.readthedocs.io/en/latest/console.html) docs for details.
2021-02-20 22:08:27 +00:00
## Rich Inspect
Rich has an [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) function which can produce a report on any Python object, such as class, instance, or builtin.
```python
2021-02-20 22:10:25 +00:00
>>> my_list = ["foo", "bar"]
2021-02-20 22:08:27 +00:00
>>> from rich import inspect
2021-02-20 22:10:25 +00:00
>>> inspect(my_list, methods=True)
2021-02-20 22:08:27 +00:00
```
2022-09-19 10:27:11 +00:00
![Log](https://github.com/textualize/rich/raw/master/imgs/inspect.png)
2021-02-20 20:17:56 +00:00
2021-02-20 22:10:25 +00:00
See the [inspect docs](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect) for details.
# Rich Library
Rich contains a number of builtin _renderables_ you can use to create elegant output in your CLI and help you debug your code.
Click the following headings for details:
2021-02-20 20:17:56 +00:00
<details>
2021-02-20 22:15:39 +00:00
<summary>Log</summary>
2019-12-23 17:16:44 +00:00
2020-01-22 16:00:03 +00:00
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.
2019-12-23 23:12:12 +00:00
```python
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:
2022-09-19 10:27:11 +00:00
![Log](https://github.com/textualize/rich/raw/master/imgs/log.png)
2019-12-23 23:12:12 +00:00
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.
2019-12-23 19:29:52 +00:00
2021-02-20 22:08:27 +00:00
</details>
<details>
<summary>Logging Handler</summary>
2020-03-27 09:00:46 +00:00
2020-05-05 02:15:35 +00:00
You can also use the builtin [Handler class](https://rich.readthedocs.io/en/latest/logging.html) to format and colorize output from Python's logging module. Here's an example of the output:
2020-03-27 08:53:58 +00:00
2022-09-19 10:27:11 +00:00
![Logging](https://github.com/textualize/rich/raw/master/imgs/logging.png)
2020-03-27 08:53:58 +00:00
2021-02-20 20:17:56 +00:00
</details>
<details>
<summary>Emoji</summary>
2019-12-23 16:21:51 +00:00
2019-12-23 19:29:52 +00:00
To insert an emoji in to console output place the name between two colons. Here's an example:
2019-12-23 16:21:51 +00:00
```python
2019-12-23 17:16:44 +00:00
>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:")
😃 🧛 💩 👍 🦝
2019-12-23 16:21:51 +00:00
```
Please use this feature wisely.
2019-12-23 18:00:28 +00:00
2021-02-20 20:17:56 +00:00
</details>
<details>
<summary>Tables</summary>
2020-05-31 14:07:37 +00:00
2020-07-03 20:30:33 +00:00
Rich can render flexible [tables](https://rich.readthedocs.io/en/latest/tables.html) with unicode box characters. There is a large variety of formatting options for borders, styles, cell alignment etc.
2022-09-19 10:27:11 +00:00
![table movie](https://github.com/textualize/rich/raw/master/imgs/table_movie.gif)
2020-07-03 20:30:33 +00:00
2022-09-19 10:27:11 +00:00
The animation above was generated with [table_movie.py](https://github.com/textualize/rich/blob/master/examples/table_movie.py) in the examples directory.
2020-07-03 20:59:49 +00:00
2020-07-03 21:01:57 +00:00
Here's a simpler table example:
2020-05-31 14:07:37 +00:00
```python
from rich.console import Console
from rich.table import Table
2020-05-31 14:07:37 +00:00
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(
"Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
2020-05-31 14:07:37 +00:00
)
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:
2022-09-19 10:27:11 +00:00
![table](https://github.com/textualize/rich/raw/master/imgs/table.png)
2020-05-31 14:07:37 +00:00
2020-07-05 19:37:20 +00:00
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).
2020-05-31 14:07:37 +00:00
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:
2022-09-19 10:27:11 +00:00
![table2](https://github.com/textualize/rich/raw/master/imgs/table2.png)
2020-05-31 14:07:37 +00:00
2021-02-20 20:17:56 +00:00
</details>
<details>
<summary>Progress Bars</summary>
2020-03-12 17:36:40 +00:00
2020-05-01 13:27:19 +00:00
Rich can render multiple flicker-free [progress](https://rich.readthedocs.io/en/latest/progress.html) bars to track long-running tasks.
2020-03-12 17:36:40 +00:00
2020-05-01 13:27:19 +00:00
For basic usage, wrap any sequence in the `track` function and iterate over the result. Here's an example:
2020-03-12 17:36:40 +00:00
```python
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:
2022-09-19 10:27:11 +00:00
![progress](https://github.com/textualize/rich/raw/master/imgs/progress.gif)
2020-05-01 13:27:19 +00:00
2020-05-08 14:21:30 +00:00
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:
2020-05-01 13:27:19 +00:00
2022-09-19 10:27:11 +00:00
![progress](https://github.com/textualize/rich/raw/master/imgs/downloader.gif)
2020-05-01 13:27:19 +00:00
2022-09-19 10:27:11 +00:00
To try this out yourself, see [examples/downloader.py](https://github.com/textualize/rich/blob/master/examples/downloader.py) which can download multiple URLs simultaneously while displaying progress.
2020-03-12 17:36:40 +00:00
2021-02-20 20:17:56 +00:00
</details>
<details>
<summary>Status</summary>
2020-12-10 17:07:11 +00:00
2020-12-13 12:36:06 +00:00
For situations where it is hard to calculate progress, you can use the [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) method which will display a 'spinner' animation and message. The animation won't prevent you from using the console as normal. Here's an example:
2020-12-10 17:07:11 +00:00
```python
from time import sleep
from rich.console import Console
console = Console()
tasks = [f"task {n}" for n in range(1, 11)]
with console.status("[bold green]Working on tasks...") as status:
while tasks:
task = tasks.pop(0)
sleep(1)
console.log(f"{task} complete")
```
This generates the following output in the terminal.
2022-09-19 10:27:11 +00:00
![status](https://github.com/textualize/rich/raw/master/imgs/status.gif)
2020-12-10 17:07:11 +00:00
2020-12-13 12:34:27 +00:00
The spinner animations were borrowed from [cli-spinners](https://www.npmjs.com/package/cli-spinners). You can select a spinner by specifying the `spinner` parameter. Run the following command to see the available values:
2020-12-13 12:32:23 +00:00
```
python -m rich.spinner
```
The above command generates the following output in the terminal:
2020-12-13 12:32:23 +00:00
2022-09-19 10:27:11 +00:00
![spinners](https://github.com/textualize/rich/raw/master/imgs/spinners.gif)
2020-12-13 12:32:23 +00:00
2021-02-20 20:17:56 +00:00
</details>
<details>
<summary>Tree</summary>
2021-01-09 14:34:17 +00:00
2021-01-09 20:39:03 +00:00
Rich can render a [tree](https://rich.readthedocs.io/en/latest/tree.html) with guide lines. A tree is ideal for displaying a file structure, or any other hierarchical data.
2021-01-09 14:34:17 +00:00
The labels of the tree can be simple text or anything else Rich can render. Run the following for a demonstration:
```
python -m rich.tree
```
This generates the following output:
2022-09-19 10:27:11 +00:00
![markdown](https://github.com/textualize/rich/raw/master/imgs/tree.png)
2021-01-09 14:34:17 +00:00
2022-09-19 10:27:11 +00:00
See the [tree.py](https://github.com/textualize/rich/blob/master/examples/tree.py) example for a script that displays a tree view of any directory, similar to the linux `tree` command.
2021-01-09 20:39:03 +00:00
2021-02-20 20:17:56 +00:00
</details>
<details>
<summary>Columns</summary>
2020-05-31 14:07:37 +00:00
2020-05-31 14:25:07 +00:00
Rich can render content in neat [columns](https://rich.readthedocs.io/en/latest/columns.html) with equal or optimal width. Here's a very basic clone of the (MacOS / Linux) `ls` command which displays a directory listing in columns:
2020-05-31 14:07:37 +00:00
```python
import os
import sys
2020-05-31 14:07:37 +00:00
from rich import print
from rich.columns import Columns
directory = os.listdir(sys.argv[1])
print(Columns(directory))
```
2022-09-19 10:27:11 +00:00
The following screenshot is the output from the [columns example](https://github.com/textualize/rich/blob/master/examples/columns.py) which displays data pulled from an API in columns:
2020-05-31 14:07:37 +00:00
2022-09-19 10:27:11 +00:00
![columns](https://github.com/textualize/rich/raw/master/imgs/columns.png)
2020-05-31 14:07:37 +00:00
2021-02-20 20:17:56 +00:00
</details>
<details>
<summary>Markdown</summary>
2019-12-23 18:00:28 +00:00
2020-05-08 14:17:54 +00:00
Rich can render [markdown](https://rich.readthedocs.io/en/latest/markdown.html) and does a reasonable job of translating the formatting to the terminal.
2019-12-23 18:00:28 +00:00
2019-12-23 19:29:52 +00:00
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:
2019-12-23 18:00:28 +00:00
```python
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:
2022-09-19 10:27:11 +00:00
![markdown](https://github.com/textualize/rich/raw/master/imgs/markdown.png)
2019-12-23 18:00:28 +00:00
2021-02-20 20:17:56 +00:00
</details>
<details>
<summary>Syntax Highlighting</summary>
2019-12-23 18:00:28 +00:00
2020-05-08 14:17:54 +00:00
Rich uses the [pygments](https://pygments.org/) library to implement [syntax highlighting](https://rich.readthedocs.io/en/latest/syntax.html). Usage is similar to rendering markdown; construct a `Syntax` object and print it to the console. Here's an example:
2019-12-23 18:00:28 +00:00
```python
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:
2022-09-19 10:27:11 +00:00
![syntax](https://github.com/textualize/rich/raw/master/imgs/syntax.png)
2019-12-23 23:13:26 +00:00
2021-02-20 20:17:56 +00:00
</details>
<details>
<summary>Tracebacks</summary>
2020-02-22 20:04:20 +00:00
2020-08-12 09:42:50 +00:00
Rich can render [beautiful tracebacks](https://rich.readthedocs.io/en/latest/traceback.html) 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.
2020-02-22 20:12:22 +00:00
Here's what it looks like on OSX (similar on Linux):
2020-02-22 20:04:20 +00:00
2022-09-19 10:27:11 +00:00
![traceback](https://github.com/textualize/rich/raw/master/imgs/traceback.png)
2020-02-22 20:04:20 +00:00
2021-02-20 20:17:56 +00:00
</details>
2021-02-22 14:18:11 +00:00
All Rich renderables make use of the [Console Protocol](https://rich.readthedocs.io/en/latest/protocol.html), which you can also use to implement your own Rich content.
2022-02-13 11:31:23 +00:00
# Rich CLI
2021-02-22 14:18:11 +00:00
2022-02-13 11:36:07 +00:00
See also [Rich CLI](https://github.com/textualize/rich-cli) for a command line application powered by Rich. Syntax highlight code, render markdown, display CSVs in tables, and more, directly from the command prompt.
2022-02-13 11:31:23 +00:00
![Rich CLI](https://raw.githubusercontent.com/Textualize/rich-cli/main/imgs/rich-cli-splash.jpg)
2022-05-06 09:46:22 +00:00
# Textual
See also Rich's sister project, [Textual](https://github.com/Textualize/textual), which you can use to build sophisticated User Interfaces in the terminal.
![Textual screenshot](https://raw.githubusercontent.com/Textualize/textual/main/imgs/textual.png)