对于Python的初学者来说,最常见的就是控制台输出了。但大部分时候,控制台输出的就是黑白色的内容。今天我们要看的这个库Rich就是给文字上色,加样式。让我们可以看到更丰富的界面样式。rich文本格式化的基本用法主要有两种方式,一是从rich导入print,覆盖Python原生print;二是从rich.console导入Console对象。from rich.console import Consoleconsole = Console()
Rich支持多种文本美化方式:样式、颜色、链接、代码高亮等1.文本样式使用[标签]文本[/标签]格式,多个样式用空格分隔console.print("[bold]加粗文字[/bold]")console.print("[italic]斜体文字[/italic]")console.print("[underline]下划线文字[/underline]")console.print("[bold italic underline]三合一样式[/bold italic underline]")
2.文字颜色的用法和样式标签类似,支持四种颜色模式,标准颜色名、256色编号、Hex色值和RGB值console.print("[steel_blue]颜色名 steel_blue[/steel_blue]")console.print("[color(69)]256色编号[/color(69)]")console.print("[#46ccB4]Hex 色值[/#46ccB4]")console.print("[rgb(170,130,180)]RGB 值[/rgb(170,130,180)]")
3.代码高亮,使用Syntax模块可以自动识别语言并高亮代码:from rich.syntax import Syntaxcode = """def hello(): print("Hello Rich")"""syntax = Syntax(code, "python", theme="monokai", line_numbers=True)console.print(syntax)
Rich会自动识别代码语言,渲染出行号、配色舒适的高亮效果。自定义样式与主题,如果每次都写内联标签,重复代码会非常多。Rich提供Style+Theme,相当于给了我们一套调色盘,统一管理样式。from rich.console import Consolefrom rich.theme import Theme# 自定义主题custom_theme = Theme({ "success": "green bold", "warning": "yellow italic", "error": "red underline", "info": "blue"})# 控制台应用主题console = Console(theme=custom_theme)
console.print("操作成功", style="success")console.print("请注意风险", style="warning")console.print("执行出错", style="error")console.print("系统提示", style="info")
Rich功能非常强大,我们只介绍了基本功能,更多的进阶内容可以参考官方文档,例如Table表格、Layout布局总之,通过Rich可以让终端从黑白色中解脱出来,可以变得更美观。