作者制作不易,关注、点赞、收藏一下吧!
目录
1.rich库简介
Rich 是一个 Python 库,用于在终端中添加丰富的文本(如颜色、粗体、下划线等)、表格、进度条。它让终端输出不再单调,通过美观的格式化增强了信息的可读性和吸引力。
2.下载并导入rich库
2.1.下载
pip install rich
2.2.导入
在.py文件中输入
import rich # 或者 from rich import*
3.使用
3.1.输出表情包
将名称放在两个冒号之间即可在控制台输出中插入emoji表情符。更多表情请见Emoji库。
print(":smiley: :vampire: :pile_of_poo:")
![](https://i-blog.csdnimg.cn/direct/2c91ae6d83c24ce5a58e1265e26f4a8b.png)
3.2.文本的样式
from rich import print
# 函数名和Python内置的一样
print("[underline blue]蓝色下划线[/underline blue] 文本")
print("[bold blue]蓝色加粗[/bold blue] 文本")
3.3.表格
from rich.console import Console
from rich.table import 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(
"Dec 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)
![](https://i-blog.csdnimg.cn/direct/ed4efd958de94762b1fa52b49d13d2ef.png)
3.4.日志
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()
![](https://i-blog.csdnimg.cn/direct/02aa6a5821a7474783f3333b7856fefa.png)