{"id":13412047,"url":"https://github.com/Textualize/rich","last_synced_at":"2025-03-14T17:31:30.708Z","repository":{"id":37094437,"uuid":"220809393","full_name":"Textualize/rich","owner":"Textualize","description":"Rich is a Python library for rich text and beautiful formatting in the terminal.","archived":false,"fork":false,"pushed_at":"2024-12-02T16:01:57.000Z","size":50082,"stargazers_count":51146,"open_issues_count":270,"forks_count":1797,"subscribers_count":539,"default_branch":"master","last_synced_at":"2025-03-10T03:54:15.360Z","etag":null,"topics":["ansi-colors","emoji","markdown","progress-bar","progress-bar-python","python","python-library","python3","rich","syntax-highlighting","tables","terminal","terminal-color","traceback","tracebacks-rich","tui"],"latest_commit_sha":null,"homepage":"https://rich.readthedocs.io/en/latest/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Textualize.png","metadata":{"files":{"readme":"README.cn.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":null},"created_at":"2019-11-10T15:28:09.000Z","updated_at":"2025-03-10T02:57:17.000Z","dependencies_parsed_at":"2022-07-08T19:02:52.330Z","dependency_job_id":"f9b327eb-ad14-4b44-afb4-070a1049bf9e","html_url":"https://github.com/Textualize/rich","commit_stats":{"total_commits":3152,"total_committers":268,"mean_commits":"11.761194029850746","dds":"0.41275380710659904","last_synced_commit":"43d3b04725ab9731727fb1126e35980c62f32377"},"previous_names":["willmcgugan/rich"],"tags_count":169,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Textualize%2Frich","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Textualize%2Frich/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Textualize%2Frich/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Textualize%2Frich/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Textualize","download_url":"https://codeload.github.com/Textualize/rich/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243618745,"owners_count":20320285,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ansi-colors","emoji","markdown","progress-bar","progress-bar-python","python","python-library","python3","rich","syntax-highlighting","tables","terminal","terminal-color","traceback","tracebacks-rich","tui"],"created_at":"2024-07-30T20:01:20.466Z","updated_at":"2025-03-14T17:31:30.678Z","avatar_url":"https://github.com/Textualize.png","language":"Python","readme":"[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich)\n[![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich)\n[![codecov](https://codecov.io/gh/Textualize/rich/branch/master/graph/badge.svg)](https://codecov.io/gh/Textualize/rich)\n[![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/)\n[![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan)\n\n![Logo](https://github.com/textualize/rich/raw/master/imgs/logo.svg)\n\n[English readme](https://github.com/textualize/rich/blob/master/README.md)\n • [简体中文 readme](https://github.com/textualize/rich/blob/master/README.cn.md)\n • [正體中文 readme](https://github.com/textualize/rich/blob/master/README.zh-tw.md)\n • [Lengua española readme](https://github.com/textualize/rich/blob/master/README.es.md)\n • [Deutsche readme](https://github.com/textualize/rich/blob/master/README.de.md)\n • [Läs på svenska](https://github.com/textualize/rich/blob/master/README.sv.md)\n • [日本語 readme](https://github.com/textualize/rich/blob/master/README.ja.md)\n • [한국어 readme](https://github.com/textualize/rich/blob/master/README.kr.md)\n • [Français readme](https://github.com/textualize/rich/blob/master/README.fr.md)\n • [Schwizerdütsch readme](https://github.com/textualize/rich/blob/master/README.de-ch.md)\n • [हिन्दी readme](https://github.com/textualize/rich/blob/master/README.hi.md)\n • [Português brasileiro readme](https://github.com/textualize/rich/blob/master/README.pt-br.md)\n • [Italian readme](https://github.com/textualize/rich/blob/master/README.it.md)\n • [Русский readme](https://github.com/textualize/rich/blob/master/README.ru.md)\n  • [فارسی readme](https://github.com/textualize/rich/blob/master/README.fa.md)\n • [Türkçe readme](https://github.com/textualize/rich/blob/master/README.tr.md)\n • [Polskie readme](https://github.com/textualize/rich/blob/master/README.pl.md)\n\nRich 是一个 Python 库，可以为您在终端中提供富文本和精美格式。\n\n[Rich 的 API](https://rich.readthedocs.io/en/latest/) 让在终端输出颜色和样式变得很简单。此外，Rich 还可以绘制漂亮的表格、进度条、markdown、语法高亮的源代码以及栈回溯信息（tracebacks）等——开箱即用。\n\n![功能纵览](https://github.com/textualize/rich/raw/master/imgs/features.png)\n\n有关 Rich 的视频介绍，请参见\n[@fishnets88](https://twitter.com/fishnets88) 录制的\n[calmcode.io](https://calmcode.io/rich/introduction.html)。\n\n## 兼容性\n\nRich 适用于 Linux，OSX 和 Windows。真彩色/表情符号可与新的 Windows 终端一起使用，Windows 的经典终端仅限 8 种颜色。\n\nRich 还可以与 [Jupyter 笔记本](https://jupyter.org/)一起使用，而无需其他配置。\n\n## 安装说明\n\n使用`pip`或其他 PyPI 软件包管理器进行安装。\n\n```sh\npython -m pip install rich\n```\n\n## Rich 的打印功能\n\n想毫不费力地将 Rich 的输出功能添加到您的应用程序中，您只需导入 [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) 方法，它和 Python 内置的同名函数有着完全一致的函数签名。试试看：\n\n```python\nfrom rich import print\n\nprint(\"Hello, [bold magenta]World[/bold magenta]!\", \":vampire:\", locals())\n```\n\n![Hello World](https://github.com/textualize/rich/raw/master/imgs/print.png)\n\n## 在交互式命令行（REPL）中使用 Rich\n\nRich 可以被安装到 Python 交互式命令行中，那样做以后，任何数据结构都可以被漂亮的打印出来，自带语法高亮。\n\n```python\n\u003e\u003e\u003e from rich import pretty\n\u003e\u003e\u003e pretty.install()\n```\n\n![REPL](https://github.com/textualize/rich/raw/master/imgs/repl.png)\n\n## 使用控制台\n\n想要对 Rich 终端内容进行更多控制，请您导入并构造一个[控制台](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console)对象。\n\n```python\nfrom rich.console import Console\n\nconsole = Console()\n```\n\nConsole 对象包含一个`print`方法，它和语言内置的`print`函数有着相似的接口。下面是一段使用样例：\n\n```python\nconsole.print(\"Hello\", \"World!\")\n```\n\n您可能已经料到，这时终端上会显示“ Hello World！”。请注意，与内置的“print”函数不同，Rich 会将文字自动换行以适合终端宽度。\n\n有好几种方法可以为输出添加颜色和样式。您可以通过添加`style`关键字参数来为整个输出设置样式。例子如下：\n\n```python\nconsole.print(\"Hello\", \"World!\", style=\"bold red\")\n```\n\n输出如下图：\n\n![Hello World](https://github.com/textualize/rich/raw/master/imgs/hello_world.png)\n\n这个范例一次只设置了一行文字的样式。如果想获得更细腻更复杂的样式，Rich 可以渲染一个特殊的标记，其语法类似于[bbcode](https://en.wikipedia.org/wiki/BBCode)。示例如下：\n\n```python\nconsole.print(\"Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].\")\n```\n\n![控制台标记](https://github.com/textualize/rich/raw/master/imgs/where_there_is_a_will.png)\n\n使用`Console`对象，你可以花最少的工夫生成复杂的输出。更详细的内容可查阅 [Console API](https://rich.readthedocs.io/en/latest/console.html) 文档。\n\n## Rich Inspect\n\nRich 提供一个 [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) 函数来给任意的 Python 对象打印报告，比如类（class）、实例（instance）和内置对象（builtin）等。\n\n```python\n\u003e\u003e\u003e my_list = [\"foo\", \"bar\"]\n\u003e\u003e\u003e from rich import inspect\n\u003e\u003e\u003e inspect(my_list, methods=True)\n```\n\n![Log](https://github.com/textualize/rich/raw/master/imgs/inspect.png)\n\n查看  [inspect 文档](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect)详细了解。\n\n# Rich 库内容\n\nRich 包含了一系列内置的 _可渲染类型(renderables)_ ，你可以用它们为命令行程序构建出优雅的输出，也可以拿它们来辅助调试你的代码。\n\n点击以下标题查看详细：\n\n\u003cdetails\u003e\n\u003csummary\u003e日志（Log）\u003c/summary\u003e\n\nConsole 对象有一个与`print()`类似的`log()`方法，但它会多输出一列内容，里面包含当前时间以及调用方法的文件行号。默认情况下，Rich 将针对 Python 结构和 repr 字符串添加语法高亮。如果您记录一个集合（如字典或列表），Rich 会把它漂亮地打印出来，使其切合可用空间。下面是其中一些功能的示例：\n\n```python\nfrom rich.console import Console\nconsole = Console()\n\ntest_data = [\n    {\"jsonrpc\": \"2.0\", \"method\": \"sum\", \"params\": [None, 1, 2, 4, False, True], \"id\": \"1\",},\n    {\"jsonrpc\": \"2.0\", \"method\": \"notify_hello\", \"params\": [7]},\n    {\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": [42, 23], \"id\": \"2\"},\n]\n\ndef test_log():\n    enabled = False\n    context = {\n        \"foo\": \"bar\",\n    }\n    movies = [\"Deadpool\", \"Rise of the Skywalker\"]\n    console.log(\"Hello from\", console, \"!\")\n    console.log(test_data, log_locals=True)\n\n\ntest_log()\n```\n\n以上范例的输出如下：\n\n![日志](https://github.com/textualize/rich/raw/master/imgs/log.png)\n\n注意其中的`log_locals`参数会输出一个表格，该表格包含调用 log 方法的局部变量。\n\nlog 方法既可用于将常驻进程（例如服务器进程）的日志打印到终端，在调试时也是个好帮手。\n\n\u003c/details\u003e\n\u003cdetails\u003e\n\u003csummary\u003e日志处理器（Logging Handler）\u003c/summary\u003e\n\n您还可以使用内置的[处理器类](https://rich.readthedocs.io/en/latest/logging.html)来对 Python 的 logging 模块的输出进行格式化和着色。下面是输出示例：\n\n![记录](https://github.com/textualize/rich/raw/master/imgs/logging.png)\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eEmoji 表情\u003c/summary\u003e\n\n将名称放在两个冒号之间即可在控制台输出中插入 emoji 表情符。示例如下：\n\n```python\n\u003e\u003e\u003e console.print(\":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:\")\n😃 🧛 💩 👍 🦝\n```\n\n请谨慎地使用此功能。\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e表格（Tables）\u003c/summary\u003e\n\nRich 可以使用 Unicode 框字符来呈现多变的[表格](https://rich.readthedocs.io/en/latest/tables.html)。Rich 包含多种边框，样式，单元格对齐等格式设置的选项。下面是一个简单的示例：\n\n```python\nfrom rich.console import Console\nfrom rich.table import Column, Table\n\nconsole = Console()\n\ntable = Table(show_header=True, header_style=\"bold magenta\")\ntable.add_column(\"Date\", style=\"dim\", width=12)\ntable.add_column(\"Title\")\ntable.add_column(\"Production Budget\", justify=\"right\")\ntable.add_column(\"Box Office\", justify=\"right\")\ntable.add_row(\n    \"Dec 20, 2019\", \"Star Wars: The Rise of Skywalker\", \"$275,000,000\", \"$375,126,118\"\n)\ntable.add_row(\n    \"May 25, 2018\",\n    \"[red]Solo[/red]: A Star Wars Story\",\n    \"$275,000,000\",\n    \"$393,151,347\",\n)\ntable.add_row(\n    \"Dec 15, 2017\",\n    \"Star Wars Ep. VIII: The Last Jedi\",\n    \"$262,000,000\",\n    \"[bold]$1,332,539,889[/bold]\",\n)\n\nconsole.print(table)\n```\n\n该示例的输出如下：\n\n![表格](https://github.com/textualize/rich/raw/master/imgs/table.png)\n\n请注意，控制台标记的呈现方式与`print()`和`log()`相同。实际上，由 Rich 渲染的任何内容都可以添加到标题/行（甚至其他表格）中。\n\n`Table`类很聪明，可以调整列的大小以适合终端的可用宽度，并能根据需要对文字折行。下面是相同的示例，输出与比上表小的终端上：\n\n![表格 2](https://github.com/textualize/rich/raw/master/imgs/table2.png)\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e进度条（Progress Bars）\u003c/summary\u003e\n\nRich 可以渲染多种“无闪烁”的[进度](https://rich.readthedocs.io/en/latest/progress.html)条图形，以跟踪长时间运行的任务。\n\n基本用法：用`track`函数调用任何程序并迭代结果。下面是一个例子：\n\n```python\nfrom rich.progress import track\n\nfor step in track(range(100)):\n    do_step(step)\n```\n\n添加多个进度条并不难。以下是从文档中获取的示例：\n\n![进度](https://github.com/textualize/rich/raw/master/imgs/progress.gif)\n\n这些列可以配置为显示您所需的任何详细信息。内置列包括完成百分比，文件大小，文件速度和剩余时间。下面是显示正在进行的下载的示例：\n\n![进度](https://github.com/textualize/rich/raw/master/imgs/downloader.gif)\n\n要自己尝试一下，请参阅[examples/downloader.py](https://github.com/textualize/rich/blob/master/examples/downloader.py)，它可以在显示进度的同时下载多个 URL。\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e状态动画（Status）\u003c/summary\u003e\n\n对于那些很难计算进度的情况，你可以使用 [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) 方法，它会展示一个“环形旋转（spinner）”的动画和文字信息。这个动画并不会妨碍你正常使用控制台。下面是个例子：\n\n```python\nfrom time import sleep\nfrom rich.console import Console\n\nconsole = Console()\ntasks = [f\"task {n}\" for n in range(1, 11)]\n\nwith console.status(\"[bold green]Working on tasks...\") as status:\n    while tasks:\n        task = tasks.pop(0)\n        sleep(1)\n        console.log(f\"{task} complete\")\n```\n\n这会往终端生成以下输出：\n\n![status](https://github.com/textualize/rich/raw/master/imgs/status.gif)\n\n这个旋转动画借鉴自 [cli-spinners](https://www.npmjs.com/package/cli-spinners) 项目。你可以通过`spinner`参数指定一种动画效果。执行以下命令来查看所有可选值：\n\n```\npython -m rich.spinner\n```\n\n这会往终端输出以下内容：\n\n![spinners](https://github.com/textualize/rich/raw/master/imgs/spinners.gif)\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e树（Tree）\u003c/summary\u003e\n\nRich 可以渲染一个包含引导线的[树（tree）](https://rich.readthedocs.io/en/latest/tree.html)。对于展示文件目录结构和其他分级数据来说，树是理想选择。\n\n树的标签可以是简单文本或任何 Rich 能渲染的东西。执行以下命令查看演示：\n\n```\npython -m rich.tree\n```\n\n这会产生以下输出：\n\n![markdown](https://github.com/textualize/rich/raw/master/imgs/tree.png)\n\n[tree.py](https://github.com/textualize/rich/blob/master/examples/tree.py) 是一个展示任意目录的文件树视图的样例文件，类似于 Linux 中的 `tree` 命令。\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e列（Columns）\u003c/summary\u003e\n\nRich 可以将内容通过排列整齐的，具有相等或最佳的宽度的[列](https://rich.readthedocs.io/en/latest/columns.html)来呈现。下面是（macOS / Linux）`ls`命令的一个非常基本的克隆，用于用列来显示目录列表：\n\n```python\nimport os\nimport sys\n\nfrom rich import print\nfrom rich.columns import Columns\n\ndirectory = os.listdir(sys.argv[1])\nprint(Columns(directory))\n```\n\n以下屏幕截图是[列示例](https://github.com/textualize/rich/blob/master/examples/columns.py)的输出，该列显示了从 API 提取的数据：\n\n![列](https://github.com/textualize/rich/raw/master/imgs/columns.png)\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eMarkdown\u003c/summary\u003e\n\nRich 可以呈现[markdown](https://rich.readthedocs.io/en/latest/markdown.html)，并可相当不错的将其格式转移到终端。\n\n为了渲染 markdown，请导入`Markdown`类，并使用包含 markdown 代码的字符串来构造它，然后将其打印到控制台。例子如下：\n\n```python\nfrom rich.console import Console\nfrom rich.markdown import Markdown\n\nconsole = Console()\nwith open(\"README.md\") as readme:\n    markdown = Markdown(readme.read())\nconsole.print(markdown)\n```\n\n该例子的输出如下图：\n\n![markdown](https://github.com/textualize/rich/raw/master/imgs/markdown.png)\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e语法高亮（Syntax Highlighting）\u003c/summary\u003e\n\nRich 使用[pygments](https://pygments.org/)库来实现[语法高亮显示](https://rich.readthedocs.io/en/latest/syntax.html)。用法类似于渲染 markdown。构造一个`Syntax`对象并将其打印到控制台。下面是一个例子：\n\n```python\nfrom rich.console import Console\nfrom rich.syntax import Syntax\n\nmy_code = '''\ndef iter_first_last(values: Iterable[T]) -\u003e Iterable[Tuple[bool, bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for first and last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    first = True\n    for value in iter_values:\n        yield first, False, previous_value\n        first = False\n        previous_value = value\n    yield first, True, previous_value\n'''\nsyntax = Syntax(my_code, \"python\", theme=\"monokai\", line_numbers=True)\nconsole = Console()\nconsole.print(syntax)\n```\n\n输出如下：\n\n![语法](https://github.com/textualize/rich/raw/master/imgs/syntax.png)\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e栈回溯信息（Tracebacks）\u003c/summary\u003e\n\nRich 可以渲染出漂亮的[栈回溯信息](https://rich.readthedocs.io/en/latest/traceback.html)，它比标准的 Python 格式更容易阅读，且能显示更多的代码。您可以将 Rich 设置为默认的栈回溯处理程序，这样所有未捕获的异常都将由 Rich 为渲染。\n\n下面是在 OSX（在 Linux 上也类似）系统的效果：\n\n![回溯](https://github.com/textualize/rich/raw/master/imgs/traceback.png)\n\n\u003c/details\u003e\n\n所有的 Rich 可渲染对象都采用了 [Console Protocol](https://rich.readthedocs.io/en/latest/protocol.html) 协议，你可以用该协议实现你独有的 Rich 内容。\n\n## 使用 Rich 的项目\n\n这里是一些使用 Rich 的项目:\n\n- [BrancoLab/BrainRender](https://github.com/BrancoLab/BrainRender)\n  一个用于三维神经解剖数据可视化的 python 包\n- [Ciphey/Ciphey](https://github.com/Ciphey/Ciphey)\n  自动解密工具\n- [emeryberger/scalene](https://github.com/emeryberger/scalene)\n  一个高性能、高精度的 Python CPU 和内存剖析器\n- [hedythedev/StarCli](https://github.com/hedythedev/starcli)\n  通过命令行浏览 GitHub 热门项目\n- [intel/cve-bin-tool](https://github.com/intel/cve-bin-tool)\n  这个工具可以扫描一些常见的、有漏洞的组件（openssl、libpng、libxml2、expat和其他一些组件），让你知道你的系统是否包含有已知漏洞的常用库。\n- [nf-core/tools](https://github.com/nf)\n  包含 nf-core 社区帮助工具的 Python 包\n- [cansarigol/pdbr](https://github.com/cansarigol/pdbr)\n  pdb + rich 的库，增强调试功能\n- [plant99/felicette](https://github.com/plant99/felicette)\n  傻瓜式卫星图像\n- [seleniumbase/SeleniumBase](https://github.com/seleniumbase/SeleniumBase)\n  使用 Selenium 和 pytest 使自动化和测试速度提高10倍，包括电池\n- [smacke/ffsubsync](https://github.com/smacke/ffsubsync)\n  自动将字幕与视频同步\n- [tryolabs/norfair](https://github.com/tryolabs/norfair)\n  轻量级 Python 库，用于向任何检测器添加实时 2D 对象跟踪\n- +[还有很多](https://github.com/textualize/rich/network/dependents)!\n","funding_links":[],"categories":["Python","Command-line Tools","HarmonyOS","Development","Desktop App Development","命令行界面开发","emoji","terminal","See more CLI libs","CLI Development","命令行工具","Command-line Interface Development","📚 فهرست","Uncategorized","Logging","Utilities","📦 Additional Python Libraries","Python 🐍"],"sub_categories":["Terminal Rendering","Windows Manager","Pretty-Printing","Python Toolkit","pytest: xonsh not found","کتابخانه هاي TUI","Uncategorized","Code Quality \u0026 Development"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FTextualize%2Frich","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FTextualize%2Frich","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FTextualize%2Frich/lists"}