banner
andrewji8

Being towards death

Heed not to the tree-rustling and leaf-lashing rain, Why not stroll along, whistle and sing under its rein. Lighter and better suited than horses are straw sandals and a bamboo staff, Who's afraid? A palm-leaf plaited cape provides enough to misty weather in life sustain. A thorny spring breeze sobers up the spirit, I feel a slight chill, The setting sun over the mountain offers greetings still. Looking back over the bleak passage survived, The return in time Shall not be affected by windswept rain or shine.
telegram
twitter
github

Forget about print, start using this perfect terminal tool for Python developers today, tested and proven effective!

Today I recommend a very exquisite terminal tool - Rich.

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

Using the Rich API, you can easily add various colors and different styles to your terminal output. It can draw beautiful tables, progress bars, Markdown, syntax-highlighted source code, and tracebacks, among many other excellent features.

image

  1. Compatibility of Rich

Rich is compatible with Linux, OSX, and Windows. It can be used with the new Windows Terminal, while the classic Windows terminal is limited to 8 colors.

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

  1. Installation instructions for Rich

Please choose one of the following methods to install the dependencies:

  1. For Windows environment, open Cmd (Start-Run-CMD).

  2. For MacOS environment, open Terminal (command+space, then type Terminal).

  3. If you are using the VSCode editor or Pycharm, you can directly use the Terminal at the bottom of the interface.

1 pip install rich

  1. Print function of Rich

To effortlessly add the output functionality of Rich to your Python script, you just need to import the Rich Print method, which has similar parameters to other built-in Python functions. You can try it out:

from rich import print

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

image
As you can see, the output generated by the Rich Print method is colorful and emphasized compared to the built-in Print function of Python.

  1. Customizing Console output
    If you want to customize the output of Rich terminal content, you need to import and construct a Console object:
from rich.console import Console

console = Console()

The Console object has a Print method, which has a similar interface to the built-in Print function of Python. You can try it out:

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

As you may have guessed, this will display "Hello World!" on the terminal. Please note that unlike the built-in "print" function, Rich automatically wraps the text to fit the terminal width.

There are several ways to add custom colors and styles to the output. You can set the style for the entire output by adding the Style keyword parameter. Here is an example:

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

The output will be as shown in the image below:

image
In this example, the style of only one line of text is set at a time. If you want more delicate and complex styles, Rich can render a special markup that has a syntax similar to Bbcode. Here is an example:

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

image

  1. Console logging
    The Console object has a Log() method, which has a similar interface to the Print() method, but it also displays the current time and the file and line that called it.

By default, Rich will syntax highlight Python structures and Repr strings. If you log a collection (such as a dictionary or list), Rich will print it beautifully to fit the available space. Here are some examples of its functionality:


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:

image

Note that the Log_locals parameter outputs a table that includes the local variables of the log method call.
The Log method can be used to log long-running applications (such as servers) to the terminal or for debugging purposes.

Logging Handler

You can also use the built-in handler to format and colorize the output of the Python logging module. Here is an example of the output:

image
6. Emoji
To insert emojis in console output, simply put the name between two colons. Here is an example:


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

Please use this feature with caution.
7. Tables
Rich provides various options for formatting tables, including borders, styles, 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:

image

Please note that the rendering of console markup is the same as print() and log(). In fact, anything rendered by Rich can be added to headers/rows (even other tables). The Table class is smart enough to adjust the column sizes to fit the available width of the terminal and handle text wrapping as needed. Here is the same example output in a smaller terminal than the previous table:

image

  1. Progress Bars
    Rich can render multiple non-flickering progress bars to track long-running tasks.
    Basic usage: Call the Track function and iterate over 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 also easy. Here is an example of the effect:

image
These columns can be configured to display any details you need.
Built-in columns include completion percentage, file size, file speed, and remaining time. Here is an example showing the progress of ongoing downloads:

image
It can download multiple URLs while displaying the progress.

  1. Columnar Data Output
    Rich can present content in neatly arranged columns with equal or optimal widths. Here is a very basic clone of the (macOS/Linux) ls command that uses columns to display a directory listing:

import os
import sys

from rich import print
from rich.columns import Columns

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

The screenshot below shows the output of the column example, which displays data extracted from an API:

image

  1. Markdown
    Rich can render Markdown and display its formatted version in the terminal.
    To render Markdown, import the Markdown class, read the Markdown file, and print it to the console. Here is 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)

The output of this example is as follows:

image

  1. Syntax Highlighting
    Rich uses the Pygments library to achieve 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:

image
12. Error Tracebacks
Rich can render beautiful error tracebacks that are easier to read and display more code than the standard Python traceback.
You can set Rich as the default traceback handler, so that all exceptions will be rendered by Rich.
Here is an example of the appearance on OSX (similar to Linux):

image

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.