Python lib for rich text, markdown, tables, etc. in the terminal

栏目: IT技术 · 发布时间: 4年前

内容简介:Rich is a Python library for renderingThe

Rich

Rich is a Python library for rendering rich text and beautiful formatting to the terminal.

The Rich API makes it easy to add colorful text (up to 16.7 million colors) with styles (bold, italic, underline etc.) to your script or application. Rich can also render pretty tables, progress bars, markdown, syntax highlighted source code, and tracebacks -- out of the box.

Python lib for rich text, markdown, tables, etc. in the terminal

Compatibility

Rich works with Linux, OSX, and Windows. True color / emoji works with new Windows Terminal, classic terminal is limited to 8 colors.

Installing

Install with pip or your favorite PyPi package manager.

pip install rich

Rich print function

To effortlessly add rich output to your application, you can import the rich print method, which has the same signature as the builtin Python function. Try this:

from rich import print

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

Python lib for rich text, markdown, tables, etc. in the terminal

Using the Console

For more control over rich terminal content, import and construct a Console object.

from rich.console import Console

console = Console()

The Console object has a print method which has an intentionally similar interface to the builtin print function. Here's an example of use:

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

As you might expect, this will print "Hello World!" to the terminal. Note that unlike the builtin print function, Rich will word-wrap your text to fit within the terminal width.

There are a few ways of adding color and style to your output. You can set a style for the entire output by adding a style keyword argument. Here's an example:

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

The output will be something like the following:

Python lib for rich text, markdown, tables, etc. in the terminal

That's fine for styling a line of text at a time. For more finely grained styling, Rich renders a special markup which is similar in syntax to bbcode . Here's an example:

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

Python lib for rich text, markdown, tables, etc. in the terminal

Console logging

The Console object has a log() method which has a similar interface to print() , but also renders a column for the current time and the file and line which made the call. By default Rich will do syntax highlighting for Python structures and for repr strings. If you log a collection (i.e. a dict or a list) Rich will pretty print it so that it fits in the available space. Here's an example of some 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 above produces the following output:

Python lib for rich text, markdown, tables, etc. in the terminal

Note the log_locals argument, which outputs a table containing the local variables where the log method was called.

The log method could be used for logging to the terminal for long running applications such as servers, but is also a very nice debugging aid.

Logging Handler

You can also use the builtin Handler class to format and colorize output form Python's logging module. Here's an example of the output:

Python lib for rich text, markdown, tables, etc. in the terminal

Emoji

To insert an emoji in to console output place the name between two colons. Here's an example:

>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:")
:smiley:    :hankey: :+1:   

Please use this feature wisely.

Progress Bars

Rich can render multiple flicker-free progress bars to track long-running tasks.

For basic usage, wrap any sequence in the track function and iterate over the result. Here's an example:

from rich.progress import track

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

It's not much harder to add multiple progress bars. Here's an example taken from the docs:

Python lib for rich text, markdown, tables, etc. in the terminal

The columns may be configured to show any details you want. Built-in columns include percentage complete, file size, file speed, and time remaining. Here's another example showing a download in progress::

Python lib for rich text, markdown, tables, etc. in the terminal

To try this out yourself, see examples/downloader.py which can download multiple URLs simultaneously while displaying progress.

Markdown

Rich can render markdown and does a reasonable job of translating the formatting to the terminal.

To render markdown import the Markdown class and construct it with a string containing markdown code. Then print it to the console. Here's 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)

This will produce output something like the following:

Python lib for rich text, markdown, tables, etc. in the terminal

Syntax Highlighting

Rich uses the pygments library to implement syntax highlighting. Usage is similar to rendering markdown; construct a Syntax object and print it to the console. 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 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)

This will produce the following output:

Python lib for rich text, markdown, tables, etc. in the terminal

Tables

Rich can render flexible tables with unicode box characters. There is a large variety of formatting options for borders, styles, cell alignment etc. Here's 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",, 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,0000", "$375,126,118"
)
table.add_row(
    "May 25, 2018",
    "[red]Solo[/red]: A Star Wars Story",
    "$275,000,0000",
    "$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)

This produces the following output:

Python lib for rich text, markdown, tables, etc. in the terminal

Note that console markup is rendered in the same was as print() and log() . In fact, anything that is renderable by Rich may be included in the headers / rows (even other tables).

The Table class is smart enough to resize columns to fit the available width of the terminal, wrapping text as required. Here's the same example, with the terminal made smaller than the table above:

Python lib for rich text, markdown, tables, etc. in the terminal

Tracebacks

Rich can render beautiful tracebacks which are easier to read and show more code than standard Python tracebacks. You can set Rich as the default traceback handler so all uncaught exceptions will be rendered by Rich.

Here's what it looks like on OSX (similar on Linux):

Python lib for rich text, markdown, tables, etc. in the terminal

Here's what it looks like on Windows:

Python lib for rich text, markdown, tables, etc. in the terminal

See the rich traceback documentation for the details.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

这就是OKR

这就是OKR

【美】约翰·杜尔(John Doerr) / 曹仰锋、王永贵 / 中信出版社 / 2018-12 / 68.00元

这本书是传奇风险投资人约翰·杜尔的作品,揭示了OKR这一目标设定系统如何促使英特尔、谷歌等科技巨头实现爆炸性增长,以及怎样促进所有组织的蓬勃发展。 20世纪70年代,在英特尔担任工程师时,杜尔首次接触到OKR。之后,作为一个风险投资人,杜尔不遗余力地将这一管理智慧,分享给50多家公司和机构,包括谷歌、亚马逊、领英、脸书、比尔及梅琳达·盖茨基金会,甚至摇滚歌手波诺的公益项目。在杜尔的帮助下,任......一起来看看 《这就是OKR》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换