Perfect terminal tool for exclusive Python developers

Hello, everyone. I'm in the same line

Today I recommend a very beautiful terminal tool - Rich

Rich is a Python library, which can provide you with rich text and beautiful and exquisite format in the terminal.

Using Rich API, you can easily add various colors and styles to the terminal output. It can draw beautiful tables, progress bars, markdown, highlight the source code of syntax and backtracking, and so on. There are countless excellent functions.

# 1.Rich compatibility

Rich is applicable to Linux, OSX and windows. It can be used with the new Windows terminal. The classic windows terminal is limited to 8 colors.

Rich can also be used with Jupyter NoteBook without additional configuration.

# 2.Rich installation instructions

Please choose one of the following ways to enter the command to install dependencies:

  1. Windows environment opens Cmd (start run CMD).
  2. Open terminal in MacOS environment (Command + space, enter Terminal).
  3. If you use the VSCode editor or pychart, you can directly use the Terminal at the bottom of the interface
pip install rich

# 3.Rich's Print function

To easily add Rich's output function to your Python script, you just need to import the rich print method, which is similar to the parameters of other Python's built-in functions. You can try:

from rich import print

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

It can be seen that the output content of rich based print method is colored and focused, which has obvious advantages over Python's own print.

# 4. Customize Console output

To make more custom settings for Rich terminal content, you need to import and construct a console object:

from rich.console import Console

console = Console()

The Console object contains a print method, and its interface is similar to the print function built in python. You can try:

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

You may have expected that "Hello World!" will be displayed on the terminal, Note that unlike the built-in "print" function, Rich automatically wraps text to fit the terminal width.

There are several ways to add custom colors and styles to your output. You can style the entire output by adding the style keyword parameter. Examples are as follows:

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

The output is as follows:

This example sets the style of only one line of text at a time. If you want more delicate and complex styles, Rich can render a special tag with a syntax similar to bbcode. Examples are as follows:

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

# 5.Console record

The Console object has a log() method, which has an interface similar to print(). In addition, it can display the current time and the called files and lines.

By default, Rich syntax highlights Python structures and repr strings. If you record a collection (such as a dictionary or list), Rich will print it beautifully to match the available space. Here are some examples 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 output of the above example is as follows:

Note the log_ The locals parameter outputs a table that contains the local variables that call the log method.

The log method can be used not only to record the logs of long-running applications (such as servers) to the terminal, but also to assist debugging.

Logging handler

You can also use the built-in processing classes to format and color the output of the Python logging module. The following is an example of the output:

# 6. emoticon

Place the name between two colons to insert emoticons in the console output. Examples are as follows:

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

Please use this function with caution.

# 7. form

Rich contains a variety of formatting options such as border, style and cell alignment. Here is a simple example:

from rich.console import Console
from rich.table import Column, 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)

The output of this example is as follows:

Note that console tags are rendered in the same way as print() and log(). In fact, anything rendered by Rich can be added to the title / row (or even other tables).

The Table class is very smart. It can adjust the size of the column to fit the available width of the terminal, and can wrap the text as needed. The following is the same example. The output is the same as that on the terminal smaller than the above Table:

# 8. progress bar

Rich can render multiple non blinking progress bars to track long-running tasks.

Basic usage: use the track function to call the program and iterate the results. Here is an example:

from rich.progress import track

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

Adding multiple progress bars is not difficult. The following is an example of the effect:

These columns can be configured to display any details you need.

Built in columns include percent complete, file size, file speed, and time remaining. The following is an example showing a download in progress:

It can download multiple URL s while displaying progress. To try it on your own, see examples / downloader. Exe in the sample file Py, download the full example of the rich sample in the Python utility official account.

# 9. Output data by column

Rich can present content through neatly arranged columns with equal or optimal width. The following is a very basic clone of the (macOS / Linux) ls command. The list of directories is displayed in columns:

import os
import sys

from rich import print
from rich.columns import Columns

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

The following screenshot is the output of a sample column that shows the data extracted from the API:

# 10.Markdown

Rich can present markdown and display its format to the terminal quite well.

To render Markdown, import the Markdown class and print it to the console. Examples are as follows:

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)

The output of this example is as follows:

# 11. Syntax highlighting

Rich uses the pysegments library for Syntax highlighting. The usage is similar to rendering markdown. Construct a Syntax object and print it to the console. Here is 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)

The output is as follows:

# 12. Error traceback

Rich can render beautiful error backtracking logs, which are easier to read than standard Python backtracking, and can display more code.

You can set Rich as the default backtracking handler so that all exceptions will be rendered by Rich for you.

The following is the appearance on OSX (similar to Linux):

This is the end of our article. If you like today's Python practical tutorial, please continue to pay attention to us. Remember to leave three messages in the welcome area.

Added by disconne on Mon, 28 Feb 2022 05:47:14 +0200