python rich学习
rich是一个python的第三方库,在终端中提供富文本和精美格式
安装
pip install rich
效果查看
python -m rich
demo1
from rich.console import Console console = Console() from rich import print as rprint rprint("[italic red]Hello[/italic red] World!", locals()) rprint({"aaa": 123, "bbb": 324, "ccc": ["123", 23, 42]})
demo2
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) #注意其中的log_locals参数会输出一个表格,该表格包含调用 log 方法的局部变量。 # log 方法既可用于将长时间运行应用程序(例如服务器)的日志记录到终端,也可用于辅助调试。 test_log()
emoji格式
console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:") #展示emoji图片
表格
from rich.console import Console from rich.table import Column, Table console = Console() table = Table(show_header=True, header_style="bold yellow") #show_header是否显示表头,header_style表头样式 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( #添加行 "Dev 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)
markdown
MARKDOWN = """ # 表格 | 表头 | 表头 | | ---- | ---- | | 单元格 | 单元格 | | 单元格 | 单元格 | | 左对齐 | 右对齐 | 居中对齐 | | :-----| ----: | :----: | | 单元格 | 单元格 | 单元格 | | 单元格 | 单元格 | 单元格 | """ from rich.markdown import Markdown md = Markdown(MARKDOWN) console.print(md) # python -m rich.markdown README.md 命令行 # python -m rich.markdown -h 帮助
代码高亮
from rich.console import Console from rich.syntax import Syntax my_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)