Tsinghua boss tells you the perfect terminal tool for Python developers

Posted by jamesflynn on Thu, 14 Oct 2021 23:22:59 +0200

Rich is a Python library that can provide you with rich text and beautiful and exquisite formats 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 work with   Jupyter NoteBook   Use together without additional configuration.

#   2.Rich installation instructions

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

  1. The 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 customize 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. Please note that unlike the built-in "print" function, Rich will automatically wrap the text to fit the width of the terminal.

There are several ways to add custom colors and styles to the 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 styles 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 fit 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 containing 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. Emoticons

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:")
😃 🧛 💩 👍 🦝

Use this feature with caution.

#   7. Forms

Rich contains a variety of formatting options such as border, style, cell alignment, etc. 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: call the program with the track function 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 yourself, see in the sample file   examples/downloader.py  , Backstage reply in Python utility treasure official account   rich example   Download all samples.

#   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 directory list 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 column example that shows the data extracted from the API:

# 10.Markdown

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

To render the 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):

We need python data to focus on official account programming, simple learning and clicking related information.  

Topics: Python Visual Studio Code