数据STUDIO

强推这个 Python 库,把终端玩出花儿了

Image

Image
Image

不知道你是不是,反正我是厌倦了单调的 print() 和难读的命令行输出,今天云朵君跟大家一起学习 Rich 库,它能用 3 行代码 让你的日志、表格和进度条变得专业又美观——语法高亮、实时刷新、自动对齐,这些本该麻烦的功能,现在开箱即用。

如果你希望:

  • 调试输出 不再是一团乱麻,而是色彩分明的结构化信息
  • CLI 工具 的交互体验从“古董级”升级到“现代感”
  • 进度条 不再自己手搓,而是自带时间预估和动态效果

那么,是时候让 Rich 来接管你的终端了。告别枯燥的打印语句,用更少的代码,做出让用户(和你自己)更愉悦的命令行界面。接下来云朵君就和大家一起看看这个强大的python都有哪些功能,都能怎么使用。

首先,确保你已经安装了它:

!pip install rich

现在,我们揭开 Rich 的神秘面纱!

实现方法如下:

语法高亮

想象一下:你花了几个小时精心编写了一段完美的代码,现在是向全世界展示它的时候了。如果语法高亮能让人眼前一亮,为什么还要满足于平淡无奇的单色呢?rich的库让这一切变得轻而易举。

绘制画布

想象一下,你有一段代码正等着你去展示。平淡无奇的print输出可能会给观众留下不深刻的印象,不过不用担心,rich库可以帮你解决这个问题:

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

# Create code
code = '''def calculate_sum(a, b):
    """Calculate the sum of two numbers and returns the result."""
    try:
        sum = a + b
        message = f"The sum of {a} and {b} is {sum}."

        if sum > 10:
            message += " This is a big number!"
        else:
            message += " This is a small number."

        return message
    except TypeError:
        return "Error: Invalid input. Please provide two numbers."'''


# Create syntax
syntax = Syntax(code, "python", line_numbers=True)

# Create console
console = Console()

# Print highlighted code
console.print(syntax)

输出结果如下

Image

只需几行代码,你的普通代码片段就能变成视觉杰作。

自定义颜色

rich的库提供了大量颜色供你选择。你可以尝试不同的风格,找到最适合自己的颜色:

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

# Create code
code = '''def binary_search(list, target):
    """Returns the index position of the target if found,
    else returns None"""

    first = 0
    last = len(list) - 1

    while first <= last:
        midpoint = (first + last) // 2
        if list[midpoint] == target:
            return midpoint
        elif list[midpoint] < target:
            first = midpoint + 1
        else:
            last = midpoint - 1

    return None'
''

# Create syntax
syntax = Syntax(code, "python", line_numbers=True, theme="dracula")

# Create console
console = Console()

# Print highlighted code
console.print(syntax)
Image

在本例中,我们使用了 dracula主题,使我们的代码具有独特的外观。

以下是所有可用样式的列表:

abap, algol_nu, algol, arduino, autumn, borland, bw, colorful,default,
dracula, emacs, friendly_grayscale, friendly, fruity, github-dark,
gruvbox-dark, gruvbox-light, igor, inkpot, lightbulb, lilypond, lovelace,
manni, material, monokai, murphy, native, nord-darker, nord, one-dark,
paraiso-dark, paraiso-light, pastie, perldoc, rainbow_dash, rrt, sas,
solarized-dark, solarized-light, staroffice, stata-dark, stata-light,
stata, tango, trac, vim, vs, xcode, zenburn

多种语言

rich库不仅限于 Python,它还支持多种语言的语法高亮:

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

# Create code
code = '''#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    // Initialise the vector
    std::vector<int> vec{3, 4, 2, 5, 1};

    // Print the original vector
    std::cout << "Original vector:";
    for (auto i = vec.begin(); i < vec.end(); ++i) {
        std::cout << " " << *i;
    }
    std::cout << std::endl << std::endl;

    // Sort
    std::sort(vec.begin(), vec.end());

    // Print the sorted vector
    std::cout << "Sorted vector:";
    for (auto i = vec.begin(); i < vec.end(); ++i) {
        std::cout << " " << *i;
    }

    return 0;
}'''


# Create syntax
syntax = Syntax(code, "c++", line_numbers=True, theme="github-dark")

# Create console
console = Console()

# Print highlighted code
console.print(syntax)
Image

无论你展示的是 Python、Java、C++ 还是 SQL,rich的语法库都能确保你的代码保持视觉效果。

语法高亮不仅是为了美观,更是为了增强代码的可读性和理解性。有了rich的语法高亮库,你可以毫不费力地为代码输出增添艺术气息。

表格

表格不仅仅是行和列;它们是有组织信息的可视化表示,让人一目了然,易于理解。在编程世界中,整齐地显示数据是一项重要技能,而rich库能你创建惊艳到表格,为你的输出注入活力。

构建数据结构

想象一下,你有数据想要用表格来展示。手动设置格式的日子一去不复返了。rich库可以做到:

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

# Create table
table = Table(show_header=True, header_style="bold cyan")

# Add columns
table.add_column("ID")
table.add_column("Name")
table.add_column("Age")

# Add rows
table.add_row("1", "Alice", "28")
table.add_row("2", "Bob", "32")
table.add_row("3", "Charlie", "24")

# Create console
console = Console()

# Print table
console.print(table)
Image

有了这个优雅的代码段,你就制作出了一个结构精美的表格,包括表头和行。show_header=True 参数确保了表格页眉的显示,而 header_style="bold cyan" 则为页眉增添了几分丽。

这个rich库并不局限于基本功能,它还提供了一系列样式选项,你的表格熠熠生辉。

列对齐

通过指定列对齐方式,确保数据完美对齐:

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

# Create table
table = Table(show_header=True, header_style="bold green")

# Add columns
table.add_column("ID", style="dim", width=5, justify="center")
table.add_column("Name", style="italic yellow")
table.add_column("Age", style="bold cyan", justify="right")

# Add rows
table.add_row("1", "Alice", "9")
table.add_row("2", "Bob", "32")
table.add_row("3", "Charlie", "24")

# Create console
console = Console()

# Print table
console.print(table)
Image

在本例中,我们将 ID 列居中,Name 列使用斜体,Age 列右移。

突出显示行

通过突出显示特定行来吸引受众的注意力:

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

# Create table
table = Table(show_header=True, header_style="bold green")

# Add columns
table.add_column("ID", style="dim", width=5, justify="center")
table.add_column("Name", style="italic")
table.add_column("Age", style="bold", justify="right")

# Add rows
table.add_row("1", "Alice", "9", style="#af00ff")
table.add_row("2", "Bob", "32", style="rgb(0,255,255)")
table.add_row("3", "Charlie", "24", style="yellow")

# Create console
console = Console()

# Print table
console.print(table)
Image

为行添加颜色可使数据脱颖而出,为表格增添视觉效果。

进度条

想象一下,你正在执行一项耗时的任务或一个冗长的循环--如果能让用户感受到进度,岂不美哉?有了rich库,进度条就能超越其功利功能,成为期待和兴奋的源泉。f

描绘进度

想象一下这样的场景:你有一个需要时间才能完成的功能,你想你的受众了解进度。rich库可将其转化为迷人的体验:

!pip install -q ipywidgets
import time
from rich.progress import track


defdo_something():
    time.sleep(1)


for i in track(range(4)):
    do_something()

输出结果如下

Image

展示其他信息

为什么仅限于进度百分比?显示附加信息,rich用户体验:

import time
from rich.progress import (
    Progress,
    SpinnerColumn,
    TextColumn,
    BarColumn,
    TaskProgressColumn,
    TimeRemainingColumn,
    TimeElapsedColumn,
)

with Progress(
    SpinnerColumn(finished_text="🐍"),
    TextColumn("[progress.description]{task.description}"),
    BarColumn(bar_width=40),
    TaskProgressColumn(),
    TimeRemainingColumn(),
    TimeElapsedColumn(),
) as progress:
    task1 = progress.add_task("[red]Downloading", total=6)
    task2 = progress.add_task("[green]Processing", total=6)
    task3 = progress.add_task("[cyan]Cooking", total=6)

whilenot progress.finished:
        progress.update(task1, advance=1.5)
        progress.update(task2, advance=1)
        progress.update(task3, advance=1.5)
        time.sleep(1)
Image

只需几行代码,你就可以将一项常规任务转变为一种交互式的、引人入胜的体验。rich库的进度条不仅能显示完成情况,还能让受众沉浸在期待的旅程中,将平淡无奇的活动变成引人入胜的时刻。

表情符号Emoji

交流不仅仅是语言,还包括表达情感和传递微妙的信息。表情符号,这些能言善辩的小字符,是为你的代码输出增添人情味的最佳伴侣。有了rich的表情符号库,你的代码将获得全新的情感表达和沟通能力。

import rich

rich.print(":smiley: Hello, world! :thumbs_up::sparkles:")

输出结果如下:

😃 Hello, world! 👍✨

再比如,你可以使用警告表情符号来引起对关键信息的注意。

import rich

warning_message = ":warning: Warning: Unauthorized access detected!"
rich.print(warning_message)
⚠ Warning: Unauthorized access detected!

可用表情符号列表可通过以下片段找到:

from rich.emoji import EMOJI

# Uncomment to print all available emojis
# for name, emoji in EMOJI.items():
#     print(f"{name}: {emoji}")

# Print the first N emojis
N = 10
for name, emoji in list(EMOJI.items())[:N]:
    print(f"{name}: {emoji}")
1st_place_medal 🥇
2nd_place_medal 🥈
3rd_place_medal 🥉
ab_button_(blood_type) 🆎
atm_sign 🏧
a_button_(blood_type) 🅰
afghanistan 🇦🇫
albania 🇦🇱
algeria 🇩🇿
american_samoa 🇦🇸

Tree

有没有发现自己迷失在文件或嵌套结构中?树形可视化是你的指路明灯,能让你清晰地洞察复杂的层次结构。借助rich库,你的代码输出可以转化为优雅的树形,展现数据结构之美。

from rich.console import Console
from rich.tree import Tree

# Create a tree structure
tree = Tree("Root")
tree.add("child1 :child:")
tree.add("child2 :child_dark_skin_tone:")

child3 = tree.add("child3 :child_medium-light_skin_tone:")
child3.add("grand_child1 :baby_light_skin_tone:")
child3.add("grand_child2 :baby:")

tree.add("child4 :child_medium-dark_skin_tone:")

# Create console
console = Console()

# Print tree
console.print(tree)

输出结果如下:

Image

将树分解成子树可以提高可读性,并保持结构清晰。

下面是另一个例子:

from rich.console import Console
from rich.tree import Tree

# Create a tree structure
tree = Tree(":file_folder: Project Root", guide_style="bold yellow")

# `src` subdirectory
src = tree.add(":file_folder: src", guide_style="bold green", style="yellow")
src.add(":page_facing_up: main.py", style="green")
src.add(":page_facing_up: utils.py", style="green")

# `data` subdirectory
data = tree.add(":file_folder: data", guide_style="bold green", style="yellow")
data.add(":page_facing_up: input.csv", style="green")
data.add(":page_facing_up: output.csv", style="green")

# Create console
console = Console()

# Print tree
console.print(tree)
Image

通过添加自定义图标和应用样式,你的树会呈现出与众不同的视觉效果。

Markdown

在代码文档和叙述领域,纯文本只能帮你到这里。Markdown 是一种轻量级、多功能的标记语言,可为文本添加rich的格式、链接、标题等。有了这个rich库,你的代码输出可以毫不费力地变成富有表现力的叙述,吸引人并提供信息。

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

# Markdown text
markdown_text = """
# My Markdown Document

This is a **Markdown** document that will be displayed in the console output.

## Section 1

This is the *first* section of the document. It contains a list:

* Item 1
* Item 2

## Section 2

This is the second section of the document. It contains a code block:

```python
print("Hello World!")
```
"""


# Convert the Markdown to a Rich object
markdown = Markdown(markdown_text)

# Create console
console = Console()

# Print the Markdown
console.print(markdown)
Image

在这个片段中,你为自己的叙述注入了活力。标题、粗体文字、斜体、列表、超链接和代码块将你的文字转化为引人入胜的体验。

结论

在编码领域,通过这个强大的Python 库 --  rich ,功能与艺术完美结合。从富有表现力的格式化和语法高亮到动态表情符号、表格和进度条,rich 将终端输出转化为迷人的视觉体验。有了 rich,你就不仅仅是在编码,而是在以一种吸引人、提供信息和令人陶醉的方式编写叙述和显示进度。拥抱 rich 的丰富性,你的代码闪耀着优雅的光芒。

🏴‍☠️宝藏级🏴‍☠️ 原创公众号『数据STUDIO』内容超级硬核。公众号以Python为核心语言,垂直于数据科学领域,包括可戳👉Python|MySQL|数据分析|数据可视化|机器学习与数据挖掘|爬虫等,从入门到进阶!

长按👇关注- 数据STUDIO -设为星标,干货速递ImageImage