【python】rich工具使用方法详细说明

发布时间:2026/7/30 19:23:05
【python】rich工具使用方法详细说明 rich 相关内容学习1. 基本用法rich库可以打印文本颜色我们可以使用16进制颜色同时很多颜色都有对应的语义化名称例如black,red,green,light_sea_green,dark_orange,deep_pink2使用方法与html类似使用颜色区块包围对应打印的文本[颜色]文本[/颜色]或者[颜色]文本也可以打印边框的颜色[定义颜色]文本[/定义颜色], border_style[边框颜色]fromrichimportprintasrprintfromrich.panelimportPanel# 十六进制及语义化颜色打印rprint([deep_pink2]这是粉红色[/deep_pink2][#22ff00]这是绿色[/#22ff00][#2244ff]这是蓝色)# 边框颜色定义Panel.fit([bold yellow]Hi, Im a Panel,border_stylered)运行结果2. consoleconsole提供了各种类型的打印方法例如富文本打印(console.print)、日志打印(console.log)、json打印(console.print_json)、转文本打印(console.out)、块区分打印(console.rule)、执行状态打印(console.status)、可输入的打印(console.input)、打印内容导出(console.export_html, console.export_text, console.export_svg)接下来我将一一介绍2.1 富文本打印(console.print)富文本打印可以让文本展示不同格式其中包括颜色设置、文本位置设置等2.1.1 字体样式设置fromrich.consoleimportConsole# 实例化consoleconsoleConsole()# 颜色打印console.print([yellow]黄色)# 文本添加下划线console.print([yellow underline]黄色下划线)# 设置文本样式console.print(这是什么颜色,styleblack on white)# 白底黑字console.print(这里只有颜色,stylered)# 红色字console.print(文本加粗,stylebold)# 字体加粗console.print(字体倾斜,styleitalic)# 字体倾斜console.print(字体下划线,styleunderline)# 字体下划线console.print(背景与字体颜色颠倒,stylereverse)# 背景与字体颜色颠倒没用console.print(删除线,stylestrike)# 删除线console.print(超豪华钛合金亮瞎狗眼特效,styleblink)# 超豪华钛合金亮瞎狗眼特效需要终端支持console.print(超链接,stylelink www.baidu.com)# 链接console.print(组合使用,stylebold red on white)# 组合使用console.print(取消[not bold]样式[/not bold],stylebold)# 取消样式[not 样式]关闭对应样式运行结果2.1.2 文本位置设置# 文本位置设置console.print(左侧展示)console.print(居中展示,justifycenter)console.print(右侧展示,justifyright)long_textThe quick brown fox jumps over the lazy dog. *2console.print(long_text,justifyfull,width40)# 左右两侧紧贴中间空隙填充通常用于英文段落展示会按单词截断换行运行结果2.1.3 文本超长展示console.print(默认展示风格*5,width40)console.print(超长展示文本*5,overflowignore,width40)console.print(超长文本省略*5,overflowellipsis,width40)console.print(超长文本截断*5,overflowcrop,width40)console.print(超长文本换行*5,overflowfold,width40)# 是否换行console.print(文本不换行*8,no_wrapTrue,width40)console.print(文本换行*8,no_wrapFalse,width40)运行结果2.1.4 其他设置# 设置多段文本的连接符console.print(hello,world,sep,)# 设置文本终止符console.print(你好,end!)# 是否允许别名转emojiconsole.print(我有emoji但是打印不出来:smile:,emojiFalse)console.print(我有emoji而且能打印出来:smile:,emojiTrue)# 是否允许文本标记console.print([yellow underline]黄色下划线,markupFalse)# 特殊文本高亮设置让数字、英文、布尔值、空、路径展示更加智能默认Trueconsole.print(这个文本高亮 1111 hello False None /user/list,highlightTrue)# 文本高度# console.print(文本有多高*15, height20, width40) # 不生效参数没使用# 根据终端宽度调整输出宽度默认Trueconsole.print(这是一串很长很长的文本*15,cropTrue)# 看不出来# 文本超出裁剪console.print(这是一串很长很长的文本*15,soft_wrapTrue)# 看不出来运行结果2.2 日志打印console.log日志打印可以打印出带时间内容其中参数有sep、end、style、justify、emoji、markup、highlight与print相同log_locals、_stack_offset为特殊参数# 打印一行日志console.log(这是一行日志)# 打印执行当前代码的执行栈console.log(这是一行日志,_stack_offset2)# 会打印出来执行文件的所有内容console.log(这是一行日志,log_localsTrue)运行结果2.3 json打印(console.print_json)json打印可以格式化打印JSON字符串其中参数有sep、end、style、justify、emoji、markup、highlight与print相同log_locals、_stack_offset为特殊参数与日志打印相同fromrich.jsonimportJSON console.print_json([false, true, null , data])# 转换后打印console.log(JSON([false, true, null , data]))运行结果2.4 转文本打印(console.out)将内容转为字符串打印其中参数有sep、end、style、highlight与print相同# 打印数组console.out([a,b,c,d])# 打印对象console.out({a:1,b:2,c:3,d:4})运行结果2.5 块区分打印(console.rule)块区分打印将会在打印内容左右添加一行分割线用于区分一个模块其中参数有characters、style、alignconsole.rule(这是一个模块)# 设置分割线样式console.rule(特殊分割线,characters)# 文本在分割线左侧console.rule([bold]我是左侧标题[/bold],alignleft)# 设置红色分割线console.rule(我是红色分割线,stylered)运行结果2.6 执行状态打印(console.status)执行状态打印会持续打印直到内部任务结束执行会返回status用于更新状态文本spinner设置loading动画,spinner_style设置loading样式speed设置loading速度默认1refresh_per_second设置每秒刷新频率默认12.5importtimewithconsole.status(执行中...,spinnerdots3,spinner_stylegreen,speed0.5,refresh_per_second5)asstatus:console.print(我执行了第一个任务)status.update(进度20%)time.sleep(1)console.print(我执行了第二个任务)status.update(进度80%)time.sleep(5)status.stop()console.print(任务执行完成)运行结果2.7. 可输入的打印console.input相当于有样式的input方法strsconsole.input([green]想说点什么[/green])console.print(f[yellow]你说的是[/yellow]:{strs})运行结果2.8 打印内容导出console.export_html, console.export_text, console.export_svg导出方法可将记录的打印内容转为html,text,svg文件export_html:theme为导出主题code_format为导出模板clear为导出后是否清空记录日志inline_styles导出html是否使用内联样式默认Falseexport_textclear为导出后是否清空记录日志styles为是否带样式文本默认为Falseexport_svgtitle导出图片标题theme为导出主题clear为导出后是否清空记录日志code_format为导出模板font_aspect_ratio为字体宽高比fromrich.consoleimportConsole console_exportConsole(recordTrue)console_export.print([green]打印第一个内容)console_export.log(记录一行日志)# 导出htmlhtml_contentconsole_export.export_html(clearFalse)withopen(./files/export.html,w,encodingutf-8)asfile:file.write(html_content)text_fileconsole_export.export_text(clearFalse,stylesTrue)withopen(./files/export.txt,w,encodingutf-8)asfile:file.write(text_file)avg_fileconsole_export.export_svg(title测试导出)withopen(./files/export.svg,w,encodingutf-8)asfile:file.write(avg_file)运行结果3. 报错打印打印标准报错信息console_errorConsole(stderrTrue,stylebold #F5222D)try:.append(111)exceptExceptionase:console_error.print(e)运行结果4. 文件内容写入可以使用console写入文件传入写入文件流实例打印的方法都将写入文件中而不是打印出来withopen(./files/log.txt,w,encodingutf-8)aslog_file:console_write_fileConsole(filelog_file)console_write_file.rule(我们写入一份日志)console_write_file.print(日志里面什么都没写)console_write_file.print(那我写几句吧)log_file.flush()print(写完了)运行结果5. 捕捉输出(console.caputure)capture方法可以将后面的输出全部收集起来而不是打印出来console_captureConsole()withconsole_capture.capture()ascapture:console_capture.print(我采集一个数据不会打印到控制台)str_outputcapture.get()print(f打印捕捉内容{str_output})运行结果6. 内容格式化打印pretty方法能够对打印内容进行格式化fromrich.prettyimportpprint# 展开打印内容pprint({a:1,b:2,c:3},expand_allTrue)# pprint((1, 2, 3), expand_allTrue)# 限制对象打印最大项其他压缩pprint((1,2,3,4,5,6),max_length3)# 限制最长的字符长度pprint(这是一个长字符串,max_string4)运行结果7. 分组打印fromrichimportprintfromrich.consoleimportGroupfromrich.panelimportPanel panel_groupGroup(Panel(Hello,styleon blue),Panel(World,styleon red),)print(Panel(panel_group))运行结果8. Markdown打印console可以打印Markdown格式的字符串MARKDOWN # This is an h1 Rich can do a pretty *decent* job of rendering markdown. 1. This is a list item 2. This is another list item | 表头1 | 表头2 | | ----- | ----- | | 1111 | 2222 | fromrich.consoleimportConsolefromrich.markdownimportMarkdown consoleConsole()mdMarkdown(MARKDOWN)console.print(md)运行结果9. 打印表格console可以创建一个表格格式并且打印表格包括头部(add_column)、行(add_row)其中add_column参数如下参数说明header列标题文本footer列底部文本页脚style列中所有单元格的样式如red、bold cyanjustify列文本对齐方式left、center、right、fulloverflow文本过长时的处理方式fold换行、crop裁剪、ellipsis省略号、ignore忽略width固定列宽度字符数不设置则自动计算min_width列的最小宽度max_width列的最大宽度ratio列宽分配权重比例值no_wrap是否禁止换行True时文本单行显示header_style列标题的样式覆盖全局样式header_justify列标题对齐方式覆盖列的justifyfooter_style列页脚的样式footer_justify列页脚对齐方式add_row参数如下参数说明*cells变长参数每个参数对应一列的值按列顺序style整行所有单元格的样式end_section该行后是否添加分隔线fromrich.tableimportTable tableTable(title我的测试表格)table.add_column(姓名,justifycenter,stylegreen,no_wrapTrue,max_width100)table.add_column(年龄,justifycenter,styleyellow,no_wrapTrue)table.add_column(描述,justifyleft)table.add_row(张三,15,他是李四)table.add_row(李四,15,他是王五)table.add_row(王五,15,他是赵六)console.print(table)我的测试表格 ┏━━━━━━┳━━━━━━┳━━━━━━━━━━┓ ┃ 姓名 ┃ 年龄 ┃ 描述 ┃ ┡━━━━━━╇━━━━━━╇━━━━━━━━━━┩ │ 张三 │ 15 │ 他是李四 │ │ 李四 │ 15 │ 他是王五 │ │ 王五 │ 15 │ 他是赵六 │ └──────┴──────┴──────────┘10. 打印树rich可以创建树形结构多层级可以链式调用fromrich.treeimportTree treeTree(这是一棵树)# 链式调用tree.add(第一层1).add(第二层1)# 返回对象调用level1tree.add(第一层2)level1.add(第二层2)rprint(tree)这是一棵树 ├── 第一层1 │ └── 第二层1 └── 第一层2 └── 第二层2官方资源Rich 官方文档: https://rich.readthedocs.io/GitHub 仓库: https://github.com/Textualize/rich

相关新闻

最新新闻

日新闻

周新闻

月新闻