Rich is a Python library for rich textual jabber and supreme formatting within the terminal.
The Rich API makes it easy to add shade and magnificence to terminal output. Rich can even render somewhat tables, growth bars, markdown, syntax highlighted provide code, tracebacks, and additional — out of the sector.
For a video introduction to Rich take a look at calmcode.io by @fishnets88.
Compatibility
Rich works with Linux, OSX, and Dwelling windows. Perfect shade / emoji works with unique Dwelling windows Terminal, traditional terminal is specific to 8 colors.
Rich also works with Jupyter notebooks with out a extra configuration required.
Inserting in
Set up with pip
or your popular PyPi package manager.
pip set up rich
Rich print characteristic
To without distress add rich output to your utility, you can import the rich print technique, which has the the same signature because the builtin Python characteristic. Achieve that:
from rich import print print("Hi there, [bold magenta]World[/bold magenta]!", ":vampire:", locals())
The usage of the Console
For added protect watch over over rich terminal jabber, import and invent a Console object.
from rich.console import Console console = Console()
The Console object has a print
technique which has an intentionally equivalent interface to the builtin print
characteristic. Right here’s an example of exercise:
console.print("Hi there", "World!")
As you’ll depend on, this would print "Hi there World!"
to the terminal. Demonstrate that unlike the builtin print
characteristic, Rich will note-wrap your textual jabber to compare within the terminal width.
There are about a systems of including shade and magnificence to your output. You presumably can situation a style for the total output by including a style
keyword argument. Right here’s an example:
console.print("Hi there", "World!", style="courageous purple")
The output would possibly be one thing bask in the following:
That is good-hunting for styling a line of textual jabber at a time. For added finely grained styling, Rich renders a diversified markup which is equivalent in syntax to bbcode. Right here’s an example:
console.print("The set there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]come[/i].")
Console logging
The Console object has a log()
technique which has a equivalent interface to print()
, nonetheless also renders a column for the unique time and the file and line which made the resolution. By default Rich will raise out syntax highlighting for Python structures and for repr strings. If you log a series (i.e. a dict or a listing) Rich will somewhat print it in declare that it suits within the on hand dwelling. Right here’s an example of nearly all these aspects.
from rich.console import Console console = Console() test_data = [ {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "identification": "1",}, {"jsonrpc": "2.0", "technique": "notify_hello", "params": [7]}, {"jsonrpc": "2.0", "technique": "subtract", "params": [42, 23], "identification": "2"}, ] def test_log(): enabled = Fraudulent context = { "foo": "bar", } movies = ["Deadpool", "Rise of the Skywalker"] console.log("Hi there from", console, "!") console.log(test_data, log_locals=Perfect) test_log()
The above produces the following output:
Demonstrate the log_locals
argument, which outputs a table containing the local variables the set the log technique became as soon as called.
The log technique would possibly maybe also very successfully be old for logging to the terminal for lengthy operating functions corresponding to servers, nonetheless is also a extremely good debugging help.
Logging Handler
You presumably can even exercise the builtin Handler class to format and colorize output from Python’s logging module. Right here’s an example of the output:
Emoji
To insert an emoji in to console output space the title between two colons. Right here’s an example:
>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:") 😃 🧛 💩 👍 🦝
Please exercise this selection wisely.
Tables
Rich can render flexible tables with unicode field characters. There is a unheard of diversity of formatting recommendations for borders, kinds, cell alignment and tons others.
The animation above became as soon as generated with table_movie.py within the examples directory.
Right here’s a less advanced table example:
from rich.console import Console from rich.table import Column, Desk console = Console() table = Desk(show_header=Perfect, header_style="courageous magenta") table.add_column("Date", style="unlit", width=12) table.add_column("Title") table.add_column("Manufacturing Value range", account for="appropriate") table.add_column("Field Administrative heart", account for="appropriate") table.add_row( "Dev 20, 2019", "Superstar Wars: The Upward push of Skywalker", "$275,000,000", "$375,126,118" ) table.add_row( "Would per chance maybe well 25, 2018", "[red]Solo[/red]: A Superstar Wars Chronicle", "$275,000,000", "$393,151,347", ) table.add_row( "Dec 15, 2017", "Superstar Wars Ep. VIII: The Final Jedi", "$262,000,000", "[bold]$1,332,539,889[/bold]", ) console.print(table)
This produces the following output:
Demonstrate that console markup is rendered within the the same became as soon as as print()
and log()
. In actuality, the rest that is renderable by Rich would possibly maybe be integrated within the headers / rows (even other tables).
The Desk
class is orderly ample to resize columns to compare the on hand width of the terminal, wrapping textual jabber as required. Right here’s the the same example, with the terminal made smaller than the table above:
Progress Bars
Rich can render a pair of flicker-free growth bars to music lengthy-operating tasks.
For overall usage, wrap any sequence within the music
characteristic and iterate over the outcome. Right here’s an example:
from rich.growth import music for step in music(vary(100)): do_step(step)
It be no longer necessary harder to add a pair of growth bars. Right here’s an example taken from the docs:
The columns would possibly maybe be configured to reveal any crucial points you will want. Constructed-in columns encompass share total, file size, file trail, and time last. Right here’s one other example showing a download in growth:
To strive this out yourself, take a look at examples/downloader.py which will download a pair of URLs concurrently whereas showing growth.
Columns
Rich can render jabber in neat columns with equal or optimum width. Right here’s a extremely overall clone of the (MacOS / Linux) ls
reveal which displays a directory itemizing 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:
Markdown
Rich can render markdown and does an reasonable job of translating the formatting to the terminal.
To render markdown import the Markdown
class and invent it with a string containing markdown code. Then print it to the console. Right here’s an example:
from rich.console import Console from rich.markdown import Markdown console = Console() with commence("README.md") as readme: markdown = Markdown(readme.be taught()) console.print(markdown)
This would possibly occasionally invent output one thing bask in the following:
Syntax Highlighting
Rich uses the pygments library to enforce syntax highlighting. Utilization is akin to rendering markdown; invent a Syntax
object and print it to the console. Right 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 final tag.""" iter_values = iter(values) strive: previous_value = subsequent(iter_values) in addition to StopIteration: return first = Perfect for tag in iter_values: yield first, Fraudulent, previous_value first = Fraudulent previous_value = tag yield first, Perfect, previous_value ''' syntax = Syntax(my_code, "python", theme="monokai", line_numbers=Perfect) console = Console() console.print(syntax)
This would possibly occasionally invent the following output:
Tracebacks
Rich can render supreme tracebacks which would possibly maybe be easier to be taught and reveal extra code than customary Python tracebacks. You presumably can situation Rich because the default traceback handler so all uncaught exceptions would possibly be rendered by Rich.
Right here’s what it looks bask in on OSX (equivalent on Linux):
Right here’s what it looks bask in on Dwelling windows:
Peek the rich traceback documentation for the runt print.