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 exclusive Python developer's perfect terminal tool 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 styles to your terminal output. It can draw beautiful tables, progress bars, Markdown, syntax-highlighted source code, and tracebacks, among many other excellent features.

Rich Compatibility:

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.

Rich Installation Instructions:

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 and type Terminal).

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

pip install rich

Rich Print Function:

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:

from rich import print

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

You can see that the output of the Rich Print method is colored and emphasized compared to the built-in Print function in Python.

Custom Console Output:

To customize the output of Rich in the terminal, 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 in Python. You can try:

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")

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 highlights the syntax for 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 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()

Please 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 classes to format and colorize the output of the Python logging module. Here is an example of the output:

Emojis:

To insert emojis into the console output, simply put the name between two colons. Here is an example:

console.print("😃 :vampire: :pile_of_poo: :thumbs_up: 🦝")

Please use this feature with caution.

Tables:

Rich includes options for various borders, styles, and cell alignments for formatting tables. 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)

Progress Bars:

Rich can render multiple non-flickering progress bars to track long-running tasks. The basic usage is to 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)

It is not difficult to add multiple progress bars. Here is an example:

Column Output:

Rich can render content in neatly arranged columns with equal or optimal widths. Here is a very basic clone of the "ls" command (macOS/Linux) that displays a directory listing in columns:

import os
import sys

from rich import print
from rich.columns import Columns

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

Markdown:

Rich can render Markdown and display it nicely in the terminal. To render Markdown, import the Markdown class 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)

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)

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 are rendered by Rich. Here is an example of the appearance on OSX (similar to Linux):

Outputting Data by Column:

Rich can present content in columns with neatly arranged, equally or optimally sized columns. Here is a very basic clone of the "ls" command (on macOS/Linux) that displays a directory listing in columns:

Markdown:

Rich can render Markdown and display it nicely in the terminal. To render Markdown, import the Markdown class and print it to the console. Here is an example:

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:

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 are rendered by Rich. Here is an example of the appearance on OSX (similar to Linux):

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