您好,欢迎访问一九零五行业门户网

Python输出还可以这么花里胡哨,这个第三方库值得你了解一下

最近后知后觉看到一个花里胡哨的rich库,可以让你的控制台输出结果美妙绝伦!!
如果你也还不知道这库的存在,倒是可以一看究竟,没准也会喜欢上她!
rich 是一个 python 库,可以为您在终端中提供富文本和精美格式。
rich api可以很容易的在终端输出添加各种颜色和不同风格。rich 还可以绘制漂亮的表格,进度条,markdown,突出显示语法的源代码及回溯等等,不胜枚举。
rich 适用于 linux,osx 和 windows。真彩色/表情符号可与新的 windows 终端一起使用,windows 的经典终端仅限 8 种颜色。
rich 还可以与jupyter 笔记本一起使用,而无需其他配置。
目录:
1. 准备工作
2. rich的功能特色
3. 功能演示
3.1. 颜色与样式
3.2. 文本格式
3.3. 文本高亮
3.4. 输入提示
3.5. 表情符号
3.6. 表格
3.7. 语法高亮
3.8. markdown格式输出
3.9. 进度条
3.10. 树结构
+ more
本文演示环境:
jupyterlab = 3.0.11,主题为暗色
1. 准备工作安装rich库
pip install rich
简单的例子
from rich import printprint("[italic red]hello[/italic red] world!")
我们可以看到,上面例子中输出的hello world中hello被设置为红色斜体,world为默认值。
再看一个例子
from rich.panel import panelpanel.fit("[bold yellow]hi, i'm a panel", border_style="red")
这个例子,我们采用了panel(面板),面板的轮廓为红色,内容文案为加粗的黄色。
以上只是简单介绍两个小例子,接下来我们来看看rich是如何rich各种精美的输出吧!
2. rich的功能特色在jupyterlab里运行(截图是在jupyterlab暗黑主题下截取)
%run -m rich
在cmd终端里运行
python -m rich
可以得到下面这个展示rich库功能特色的简要说明,我们能清晰的看出它所具备的及支持的精美格式诸如:
颜色样式文本对齐方式多语言支持标记符号&表情表格语法高亮markdown进度条...+more3. 功能演示我们这里只做简单的功能案例演示,详细的使用大家可以直接查看官方文档。
https://rich.readthedocs.io/en/stable/
3.1. 颜色与样式我们先构造一个控制台对象,然这个对象有一个print方法,和python内置的功能基本一致。和内置的不同在于rich会将文字自动换行以适合终端宽度,并且有几种方法可以为输出添加颜色和样式。
from rich.console import consoleconsole = console()console.print("hello", style="magenta")
可以看到,输出的hello是酒红色的,颜色通过style参数设置,这里颜色是英文单词,同时也可以是16进制颜色码、rgb或者颜色color(n)表示等等。
console.print("rich库有点意思啊", style="red on white")
上面这个例子,我们发现还可以通过style设置文本颜色及底色。
另外,我们还可以这样设置文本样式:通过[red] 与 [/red]来设置其框定的区域文本颜色与样式。
from rich import printprint("[bold red]alert![/bold red] something happened")
3.2. 文本格式rich有个text类,用于我们对长文本进行颜色与样式调整。
from rich.console import consolefrom rich.text import textconsole = console()text = text("0123456789")text.stylize("bold magenta", 0, 6)console.print(text)
对于上面这个案例,将字符串0123456789中[0,6)下标的字符颜色设置为酒红色粗体。
from rich import printfrom rich.panel import panelfrom rich.text import textpanel = panel(text("大家好,我是才哥。欢迎关注微信公众号:可以叫我才哥!", justify="center"))print(panel)
这个例子中,我们可以看到它是将文本居中对齐在一个面板中。
3.3. 文本高亮rich可以通过正则或者其他形式让文本中指定的字符高亮。
比如,我们通过正则让文本中邮箱字符高亮:
from rich.console import consolefrom rich.highlighter import regexhighlighterfrom rich.theme import themeclass 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")
比如,我们可以将文本每个字符设置成随机的颜色:
from random import randintfrom rich import printfrom rich.highlighter import highlighterclass 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("大家好,我是才哥,是不是每个字的颜色都不一样?"))
3.4. 输入提示rich有个prompt类,用于提示我们进行输入(类似input功能),不过它还支持指定值输入及选择判断等。
提示输入:
from rich.prompt import promptname = prompt.ask("enter your name")
指定值输入:
from rich.prompt import promptname = prompt.ask("enter your name", choices=["才哥", "可以叫我才哥", "天才"], default="可以叫我才哥")
选择判断:
from rich.prompt import confirmis_rich_great = confirm.ask("do you like rich?")assert is_rich_great
3.5. 表情符号将名称放在两个冒号之间即可在控制台输出中插入表情符号。
from rich.console import consoleconsole = console()console.print(":smiley: :pile_of_poo: :thumbs_up: ")
3.6. 表格rich 可以使用 unicode 框字符来呈现多变的表格,它包含多种边框,样式,单元格对齐等格式设置的选项。
from rich.console import consolefrom rich.table import tabletable = 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)
3.7. 语法高亮rich 使用pygments库来实现语法高亮显示
from rich.console import consolefrom rich.syntax import syntaxmy_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)
3.8. markdown格式输出rich 可以呈现markdown,并可相当不错的将其格式转移到终端。为了渲染 markdown,导入markdown类,并使用包含 markdown 代码的字符串来构造它,然后将其打印到控制台。
markdown = """# 这是一级标题rich 库能比较**完美**的输出markdown.1. this is a list item2. this is another list item```pythonfrom rich.console import consolefrom rich.markdown import markdownconsole = 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 consolefrom rich.markdown import markdownconsole = console()md = markdown(markdown)console.print(md)
3.9. 进度条rich 可以渲染多个不闪烁的进度条形图,以跟踪长时间运行的任务。基本用法:用track函数调用任何程序并迭代结果。
from rich.progress import trackimport timefor step in track(range(100)): time.sleep(0.1)
进度条3.10. 树结构rich有个tree类,用于展示树结构。
from rich.tree import treefrom rich import printtree = tree("地球")baz_tree = tree.add("亚洲")baz_tree.add("[red]中国").add("[green]北京").add("[yellow]海淀区")print(tree)
+ morepadding填充:
from rich import printfrom rich.padding import paddingtest = padding("hello", (2, 4), style="on blue", expand=false)print(test)
panel面板:
from rich import printfrom rich.panel import panelprint(panel("hello, [red]world!", title="welcome"))
layout布局:
from rich import printfrom rich.layout import layoutlayout = 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)
live动态:
import timefrom rich.live import livefrom rich.table import tabletable = 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")
live
以上就是python输出还可以这么花里胡哨,这个第三方库值得你了解一下的详细内容。
其它类似信息

推荐信息