Python output can be so fancy. This third-party library is worth knowing about.

Release: 2023-08-10 16:09:54
forward
1702 people have browsed it

Recently I saw a 花##. #里Huwhistle rich library can make your console output results wonderful! !

If you don’t know the existence of this library, you can take a look and maybe you will fall in love with her!

Rich is a Python library that gives you rich text and beautiful formatting in your terminal.

Rich API makes it easy to add various colors and styles to the terminal output. Rich can also draw beautiful tables, progress bars, markdown, source code with syntax highlighting and tracebacks, and the list goes on.

Rich available for Linux, OSX and Windows. True Colors/Emojis work with the new Windows Terminal, Windows' classic Terminal is limited to 8 colors.

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

Contents:

  • 1. Preparation

  • 2. Features of Rich

  • 3. Function demonstration

    • ##3.1. Color and style

    • 3.2. Text format

    • 3.3. Text highlighting

    • 3.4. Input prompt

    • 3.5. Emoticon

    • 3.6 . Table

    • 3.7. Syntax highlighting

    • 3.8. Markdown format output

    • 3.9. Progress bar

    • ##3.10. Tree structure

    • More

    Demo environment for this article:

JupyterLab = 3.0.11

, the theme is dark

1. PreparationInstallation

rich

Library<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;">pip install rich</pre><div class="contentsignin">Copy after login</div></div>Simple example

from rich import print

print("[italic red]Hello[/italic red] World!")
Copy after login

Python output can be so fancy. This third-party library is worth knowing about.We can see that the

Hello# output in the above example #Hello in World is set to red italic, and World is the default value. Look at another example

from rich.panel import Panel

Panel.fit("[bold yellow]Hi, I&#39;m a Panel", border_style="red")
Copy after login

In this example, we use Python output can be so fancy. This third-party library is worth knowing about.Panel
(panel), the outline of the panel is red, and the content The copy is in bold yellow.

以上只是简单介绍两个小例子,接下来我们来看看Rich是如何rich各种精美的输出吧!

2. Rich的功能特色

在jupyterlab里运行(截图是在jupyterlab暗黑主题下截取)

%run -m rich
Copy after login

在cmd终端里运行

python -m rich
Copy after login

可以得到下面这个展示rich库功能特色的简要说明,我们能清晰的看出它所具备的及支持的精美格式诸如:

  • 颜色
  • 样式
  • 文本对齐方式
  • 多语言支持
  • 标记符号&表情
  • 表格
  • 语法高亮
  • markdown
  • 进度条
  • ...+more
Python output can be so fancy. This third-party library is worth knowing about.

3. 功能演示

我们这里只做简单的功能案例演示,详细的使用大家可以直接查看官方文档。

https://rich.readthedocs.io/en/stable/

3.1. 颜色与样式

我们先构造一个控制台对象,然这个对象有一个print方法,和python内置的功能基本一致。和内置的不同在于Rich会将文字自动换行以适合终端宽度,并且有几种方法可以为输出添加颜色和样式。

from rich.console import Console

console = Console()
console.print("Hello", style="magenta")
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

可以看到,输出的Hello是酒红色的,颜色通过style参数设置,这里颜色是英文单词,同时也可以是16进制颜色码RGB或者颜色color(n)表示等等。

console.print("Rich库有点意思啊", style="red on white")
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

上面这个例子,我们发现还可以通过style设置文本颜色及底色。

另外,我们还可以这样设置文本样式:通过[red][/red]来设置其框定的区域文本颜色与样式。

from rich import print

print("[bold red]alert![/bold red] Something happened")
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

3.2. 文本格式

Rich有个Text类,用于我们对长文本进行颜色与样式调整。

from rich.console import Console
from rich.text import Text

console = Console()
text = Text("0123456789")
text.stylize("bold magenta", 0, 6)
console.print(text)
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

对于上面这个案例,将字符串0123456789[0,6)下标的字符颜色设置为酒红色粗体。

from rich import print
from rich.panel import Panel
from rich.text import Text

panel = Panel(Text("大家好,我是才哥。欢迎关注微信公众号:可以叫我才哥!", justify="center"))
print(panel)
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

这个例子中,我们可以看到它是将文本居中对齐在一个面板中。

3.3. 文本高亮

Rich可以通过正则或者其他形式让文本中指定的字符高亮。

比如,我们通过正则让文本中邮箱字符高亮:

from rich.console import Console
from rich.highlighter import RegexHighlighter
from rich.theme import Theme

class EmailHighlighter(RegexHighlighter):
    """Apply style to anything that looks like an email."""

    base_style = "example."
    highlights = [r"(?P<email>[\w-]+@([\w-]+\.)+[\w-]+)"]


theme = Theme({"example.email": "bold magenta"})
console = Console(highlighter=EmailHighlighter(), theme=theme)
console.print("Send funds to money@example.org")
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

比如,我们可以将文本每个字符设置成随机的颜色:

from random import randint

from rich import print
from rich.highlighter import Highlighter


class RainbowHighlighter(Highlighter):
    def highlight(self, text):
        for index in range(len(text)):
            text.stylize(f"color({randint(16, 255)})", index, index + 1)


rainbow = RainbowHighlighter()
print(rainbow("大家好,我是才哥,是不是每个字的颜色都不一样?"))
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

3.4. 输入提示

Rich有个Prompt类,用于提示我们进行输入(类似input功能),不过它还支持指定值输入及选择判断等。

提示输入:

from rich.prompt import Prompt

name = Prompt.ask("Enter your name")
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

指定值输入:

from rich.prompt import Prompt

name = Prompt.ask("Enter your name", choices=["才哥", "可以叫我才哥", "天才"], default="可以叫我才哥")
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

选择判断:

from rich.prompt import Confirm

is_rich_great = Confirm.ask("Do you like rich?")

assert is_rich_great
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

3.5. 表情符号

将名称放在两个冒号之间即可在控制台输出中插入表情符号。

from rich.console import Console

console = Console()
console.print(":smiley: :pile_of_poo: :thumbs_up: ")
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

3.6. 表格

Rich 可以使用 Unicode 框字符来呈现多变的表格,它包含多种边框,样式,单元格对齐等格式设置的选项。

from rich.console import Console
from rich.table import Table

table = Table(title="Star Wars Movies")

table.add_column("Released", justify="right", style="cyan", no_wrap=True)
table.add_column("Title", style="magenta")
table.add_column("Box Office", justify="right", style="green")

table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690")
table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347")
table.add_row("Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889")
table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889")

console = Console()
console.print(table)
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

3.7. 语法高亮

Rich 使用pygments库来实现语法高亮显示

from rich.console import Console
from rich.syntax import Syntax

my_code = &#39;&#39;&#39;
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
&#39;&#39;&#39;
syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True)
console = Console()
console.print(syntax)
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

3.8. markdown格式输出

Rich 可以呈现markdown,并可相当不错的将其格式转移到终端。为了渲染 markdown,导入Markdown类,并使用包含 markdown 代码的字符串来构造它,然后将其打印到控制台。

MARKDOWN = """
# 这是一级标题

Rich 库能比较**完美**的输出markdown.

1. This is a list item
2. This is another list item

```python
from rich.console import Console
from rich.markdown import Markdown

console = Console()
md = Markdown(MARKDOWN)
console.print(md)
```
![二维码](https://gitee.com/dxawdc/pic/raw/master/image/qrcode_for_gh_ce68560ed124_258.jpg)
"""
from rich.console import Console
from rich.markdown import Markdown

console = Console()
md = Markdown(MARKDOWN)
console.print(md)
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

3.9. 进度条

Rich 可以渲染多个不闪烁的进度条形图,以跟踪长时间运行的任务。基本用法:用track函数调用任何程序并迭代结果。

from rich.progress import track
import time

for step in track(range(100)):
    time.sleep(0.1)
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.
进度条

3.10. 树结构

Rich有个Tree类,用于展示树结构。

from rich.tree import Tree
from rich import print

tree = Tree("地球")
baz_tree = tree.add("亚洲")
baz_tree.add("[red]中国").add("[green]北京").add("[yellow]海淀区")
print(tree)
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

+ More

Padding填充:

from rich import print
from rich.padding import Padding

test = Padding("Hello", (2, 4), style="on blue", expand=False)
print(test)
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

Panel面板:

from rich import print
from rich.panel import Panel

print(Panel("Hello, [red]World!", title="Welcome"))
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

layout布局:

from rich import print
from rich.layout import Layout

layout = Layout()
layout.split_column(
    Layout(name="upper",size = 10),
    Layout(name="lower",size = 10)
)

layout["lower"].split_row(
    Layout(name="left"), Layout(name="right"),

    ) 
layout["right"].split(
    Layout(Panel("Hello")),
    Layout(Panel("World!"))
)
print(layout)
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

Live动态:

import time

from rich.live import Live
from rich.table import Table

table = Table()
table.add_column("Row ID")
table.add_column("Description")
table.add_column("Level")

with Live(table, refresh_per_second=4):  # update 4 times a second to feel fluid
    for row in range(12):
        time.sleep(0.4)  # arbitrary delay
        # update the renderable internally
        table.add_row(f"{row}", f"description {row}", "[red]ERROR")
Copy after login
Python output can be so fancy. This third-party library is worth knowing about.

Live


The above is the detailed content of Python output can be so fancy. This third-party library is worth knowing about.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Python当打之年
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!