Debian Codegraph @

README.cn.md

raw
1 [![Supported Python Versions](https://img.shields.io/pypi/pyversions/rich)](https://pypi.org/project/rich/) [![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich)
2
3 [![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich)
4 [![codecov](https://img.shields.io/codecov/c/github/Textualize/rich?label=codecov&logo=codecov)](https://codecov.io/gh/Textualize/rich)
5 [![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/)
6 [![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan)
7
8 ![Logo](https://github.com/textualize/rich/raw/master/imgs/logo.svg)
9
10 [English readme](https://github.com/textualize/rich/blob/master/README.md)
11 • [简体中文 readme](https://github.com/textualize/rich/blob/master/README.cn.md)
12 • [正體中文 readme](https://github.com/textualize/rich/blob/master/README.zh-tw.md)
13 • [Lengua española readme](https://github.com/textualize/rich/blob/master/README.es.md)
14 • [Deutsche readme](https://github.com/textualize/rich/blob/master/README.de.md)
15 • [Läs på svenska](https://github.com/textualize/rich/blob/master/README.sv.md)
16 • [日本語 readme](https://github.com/textualize/rich/blob/master/README.ja.md)
17 • [한국어 readme](https://github.com/textualize/rich/blob/master/README.kr.md)
18 • [Français readme](https://github.com/textualize/rich/blob/master/README.fr.md)
19 • [Schwizerdütsch readme](https://github.com/textualize/rich/blob/master/README.de-ch.md)
20 • [हिन्दी readme](https://github.com/textualize/rich/blob/master/README.hi.md)
21 • [Português brasileiro readme](https://github.com/textualize/rich/blob/master/README.pt-br.md)
22 • [Italian readme](https://github.com/textualize/rich/blob/master/README.it.md)
23 • [Русский readme](https://github.com/textualize/rich/blob/master/README.ru.md)
24 • [فارسی readme](https://github.com/textualize/rich/blob/master/README.fa.md)
25 • [Türkçe readme](https://github.com/textualize/rich/blob/master/README.tr.md)
26 • [Polskie readme](https://github.com/textualize/rich/blob/master/README.pl.md)
27
28 Rich 是一个 Python 库,可以为您在终端中提供富文本和精美格式。
29
30 [Rich 的 API](https://rich.readthedocs.io/en/latest/) 让在终端输出颜色和样式变得很简单。此外,Rich 还可以绘制漂亮的表格、进度条、markdown、语法高亮的源代码以及栈回溯信息(tracebacks)等——开箱即用。
31
32 ![功能纵览](https://github.com/textualize/rich/raw/master/imgs/features.png)
33
34 有关 Rich 的视频介绍,请参见
35 [@fishnets88](https://twitter.com/fishnets88) 录制的
36 [calmcode.io](https://calmcode.io/rich/introduction.html)。
37
38 ## 兼容性
39
40 Rich 适用于 Linux,OSX 和 Windows。真彩色/表情符号可与新的 Windows 终端一起使用,Windows 的经典终端仅限 8 种颜色。
41
42 Rich 还可以与 [Jupyter 笔记本](https://jupyter.org/)一起使用,而无需其他配置。
43
44 ## 安装说明
45
46 使用`pip`或其他 PyPI 软件包管理器进行安装。
47
48 ```sh
49 python -m pip install rich
50 ```
51
52 ## Rich 的打印功能
53
54 想毫不费力地将 Rich 的输出功能添加到您的应用程序中,您只需导入 [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) 方法,它和 Python 内置的同名函数有着完全一致的函数签名。试试看:
55
56 ```python
57 from rich import print
58
59 print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())
60 ```
61
62 ![Hello World](https://github.com/textualize/rich/raw/master/imgs/print.png)
63
64 ## 在交互式命令行(REPL)中使用 Rich
65
66 Rich 可以被安装到 Python 交互式命令行中,那样做以后,任何数据结构都可以被漂亮的打印出来,自带语法高亮。
67
68 ```python
69 >>> from rich import pretty
70 >>> pretty.install()
71 ```
72
73 ![REPL](https://github.com/textualize/rich/raw/master/imgs/repl.png)
74
75 ## 使用控制台
76
77 想要对 Rich 终端内容进行更多控制,请您导入并构造一个[控制台](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console)对象。
78
79 ```python
80 from rich.console import Console
81
82 console = Console()
83 ```
84
85 Console 对象包含一个`print`方法,它和语言内置的`print`函数有着相似的接口。下面是一段使用样例:
86
87 ```python
88 console.print("Hello", "World!")
89 ```
90
91 您可能已经料到,这时终端上会显示“ Hello World!”。请注意,与内置的“print”函数不同,Rich 会将文字自动换行以适合终端宽度。
92
93 有好几种方法可以为输出添加颜色和样式。您可以通过添加`style`关键字参数来为整个输出设置样式。例子如下:
94
95 ```python
96 console.print("Hello", "World!", style="bold red")
97 ```
98
99 输出如下图:
100
101 ![Hello World](https://github.com/textualize/rich/raw/master/imgs/hello_world.png)
102
103 这个范例一次只设置了一行文字的样式。如果想获得更细腻更复杂的样式,Rich 可以渲染一个特殊的标记,其语法类似于[bbcode](https://en.wikipedia.org/wiki/BBCode)。示例如下:
104
105 ```python
106 console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].")
107 ```
108
109 ![控制台标记](https://github.com/textualize/rich/raw/master/imgs/where_there_is_a_will.png)
110
111 使用`Console`对象,你可以花最少的工夫生成复杂的输出。更详细的内容可查阅 [Console API](https://rich.readthedocs.io/en/latest/console.html) 文档。
112
113 ## Rich Inspect
114
115 Rich 提供一个 [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) 函数来给任意的 Python 对象打印报告,比如类(class)、实例(instance)和内置对象(builtin)等。
116
117 ```python
118 >>> my_list = ["foo", "bar"]
119 >>> from rich import inspect
120 >>> inspect(my_list, methods=True)
121 ```
122
123 ![Log](https://github.com/textualize/rich/raw/master/imgs/inspect.png)
124
125 查看 [inspect 文档](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect)详细了解。
126
127 # Rich 库内容
128
129 Rich 包含了一系列内置的 _可渲染类型(renderables)_ ,你可以用它们为命令行程序构建出优雅的输出,也可以拿它们来辅助调试你的代码。
130
131 点击以下标题查看详细:
132
133 <details>
134 <summary>日志(Log)</summary>
135
136 Console 对象有一个与`print()`类似的`log()`方法,但它会多输出一列内容,里面包含当前时间以及调用方法的文件行号。默认情况下,Rich 将针对 Python 结构和 repr 字符串添加语法高亮。如果您记录一个集合(如字典或列表),Rich 会把它漂亮地打印出来,使其切合可用空间。下面是其中一些功能的示例:
137
138 ```python
139 from rich.console import Console
140 console = Console()
141
142 test_data = [
143 {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",},
144 {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
145 {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"},
146 ]
147
148 def test_log():
149 enabled = False
150 context = {
151 "foo": "bar",
152 }
153 movies = ["Deadpool", "Rise of the Skywalker"]
154 console.log("Hello from", console, "!")
155 console.log(test_data, log_locals=True)
156
157
158 test_log()
159 ```
160
161 以上范例的输出如下:
162
163 ![日志](https://github.com/textualize/rich/raw/master/imgs/log.png)
164
165 注意其中的`log_locals`参数会输出一个表格,该表格包含调用 log 方法的局部变量。
166
167 log 方法既可用于将常驻进程(例如服务器进程)的日志打印到终端,在调试时也是个好帮手。
168
169 </details>
170 <details>
171 <summary>日志处理器(Logging Handler)</summary>
172
173 您还可以使用内置的[处理器类](https://rich.readthedocs.io/en/latest/logging.html)来对 Python 的 logging 模块的输出进行格式化和着色。下面是输出示例:
174
175 ![记录](https://github.com/textualize/rich/raw/master/imgs/logging.png)
176
177 </details>
178
179 <details>
180 <summary>Emoji 表情</summary>
181
182 将名称放在两个冒号之间即可在控制台输出中插入 emoji 表情符。示例如下:
183
184 ```python
185 >>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:")
186 😃 🧛 💩 👍 🦝
187 ```
188
189 请谨慎地使用此功能。
190
191 </details>
192
193 <details>
194 <summary>表格(Tables)</summary>
195
196 Rich 可以使用 Unicode 框字符来呈现多变的[表格](https://rich.readthedocs.io/en/latest/tables.html)。Rich 包含多种边框,样式,单元格对齐等格式设置的选项。下面是一个简单的示例:
197
198 ```python
199 from rich.console import Console
200 from rich.table import Column, Table
201
202 console = Console()
203
204 table = Table(show_header=True, header_style="bold magenta")
205 table.add_column("Date", style="dim", width=12)
206 table.add_column("Title")
207 table.add_column("Production Budget", justify="right")
208 table.add_column("Box Office", justify="right")
209 table.add_row(
210 "Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
211 )
212 table.add_row(
213 "May 25, 2018",
214 "[red]Solo[/red]: A Star Wars Story",
215 "$275,000,000",
216 "$393,151,347",
217 )
218 table.add_row(
219 "Dec 15, 2017",
220 "Star Wars Ep. VIII: The Last Jedi",
221 "$262,000,000",
222 "[bold]$1,332,539,889[/bold]",
223 )
224
225 console.print(table)
226 ```
227
228 该示例的输出如下:
229
230 ![表格](https://github.com/textualize/rich/raw/master/imgs/table.png)
231
232 请注意,控制台标记的呈现方式与`print()`和`log()`相同。实际上,由 Rich 渲染的任何内容都可以添加到标题/行(甚至其他表格)中。
233
234 `Table`类很聪明,可以调整列的大小以适合终端的可用宽度,并能根据需要对文字折行。下面是相同的示例,输出与比上表小的终端上:
235
236 ![表格 2](https://github.com/textualize/rich/raw/master/imgs/table2.png)
237
238 </details>
239
240 <details>
241 <summary>进度条(Progress Bars)</summary>
242
243 Rich 可以渲染多种“无闪烁”的[进度](https://rich.readthedocs.io/en/latest/progress.html)条图形,以跟踪长时间运行的任务。
244
245 基本用法:用`track`函数调用任何程序并迭代结果。下面是一个例子:
246
247 ```python
248 from rich.progress import track
249
250 for step in track(range(100)):
251 do_step(step)
252 ```
253
254 添加多个进度条并不难。以下是从文档中获取的示例:
255
256 ![进度](https://github.com/textualize/rich/raw/master/imgs/progress.gif)
257
258 这些列可以配置为显示您所需的任何详细信息。内置列包括完成百分比,文件大小,文件速度和剩余时间。下面是显示正在进行的下载的示例:
259
260 ![进度](https://github.com/textualize/rich/raw/master/imgs/downloader.gif)
261
262 要自己尝试一下,请参阅[examples/downloader.py](https://github.com/textualize/rich/blob/master/examples/downloader.py),它可以在显示进度的同时下载多个 URL。
263
264 </details>
265
266 <details>
267 <summary>状态动画(Status)</summary>
268
269 对于那些很难计算进度的情况,你可以使用 [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) 方法,它会展示一个“环形旋转(spinner)”的动画和文字信息。这个动画并不会妨碍你正常使用控制台。下面是个例子:
270
271 ```python
272 from time import sleep
273 from rich.console import Console
274
275 console = Console()
276 tasks = [f"task {n}" for n in range(1, 11)]
277
278 with console.status("[bold green]Working on tasks...") as status:
279 while tasks:
280 task = tasks.pop(0)
281 sleep(1)
282 console.log(f"{task} complete")
283 ```
284
285 这会往终端生成以下输出:
286
287 ![status](https://github.com/textualize/rich/raw/master/imgs/status.gif)
288
289 这个旋转动画借鉴自 [cli-spinners](https://www.npmjs.com/package/cli-spinners) 项目。你可以通过`spinner`参数指定一种动画效果。执行以下命令来查看所有可选值:
290
291 ```
292 python -m rich.spinner
293 ```
294
295 这会往终端输出以下内容:
296
297 ![spinners](https://github.com/textualize/rich/raw/master/imgs/spinners.gif)
298
299 </details>
300
301 <details>
302 <summary>树(Tree)</summary>
303
304 Rich 可以渲染一个包含引导线的[树(tree)](https://rich.readthedocs.io/en/latest/tree.html)。对于展示文件目录结构和其他分级数据来说,树是理想选择。
305
306 树的标签可以是简单文本或任何 Rich 能渲染的东西。执行以下命令查看演示:
307
308 ```
309 python -m rich.tree
310 ```
311
312 这会产生以下输出:
313
314 ![markdown](https://github.com/textualize/rich/raw/master/imgs/tree.png)
315
316 [tree.py](https://github.com/textualize/rich/blob/master/examples/tree.py) 是一个展示任意目录的文件树视图的样例文件,类似于 Linux 中的 `tree` 命令。
317
318 </details>
319
320 <details>
321 <summary>列(Columns)</summary>
322
323 Rich 可以将内容通过排列整齐的,具有相等或最佳的宽度的[列](https://rich.readthedocs.io/en/latest/columns.html)来呈现。下面是(macOS / Linux)`ls`命令的一个非常基本的克隆,用于用列来显示目录列表:
324
325 ```python
326 import os
327 import sys
328
329 from rich import print
330 from rich.columns import Columns
331
332 directory = os.listdir(sys.argv[1])
333 print(Columns(directory))
334 ```
335
336 以下屏幕截图是[列示例](https://github.com/textualize/rich/blob/master/examples/columns.py)的输出,该列显示了从 API 提取的数据:
337
338 ![列](https://github.com/textualize/rich/raw/master/imgs/columns.png)
339
340 </details>
341
342 <details>
343 <summary>Markdown</summary>
344
345 Rich 可以呈现[markdown](https://rich.readthedocs.io/en/latest/markdown.html),并可相当不错的将其格式转移到终端。
346
347 为了渲染 markdown,请导入`Markdown`类,并使用包含 markdown 代码的字符串来构造它,然后将其打印到控制台。例子如下:
348
349 ```python
350 from rich.console import Console
351 from rich.markdown import Markdown
352
353 console = Console()
354 with open("README.md") as readme:
355 markdown = Markdown(readme.read())
356 console.print(markdown)
357 ```
358
359 该例子的输出如下图:
360
361 ![markdown](https://github.com/textualize/rich/raw/master/imgs/markdown.png)
362
363 </details>
364
365 <details>
366 <summary>语法高亮(Syntax Highlighting)</summary>
367
368 Rich 使用[pygments](https://pygments.org/)库来实现[语法高亮显示](https://rich.readthedocs.io/en/latest/syntax.html)。用法类似于渲染 markdown。构造一个`Syntax`对象并将其打印到控制台。下面是一个例子:
369
370 ```python
371 from rich.console import Console
372 from rich.syntax import Syntax
373
374 my_code = '''
375 def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
376 """Iterate and generate a tuple with a flag for first and last value."""
377 iter_values = iter(values)
378 try:
379 previous_value = next(iter_values)
380 except StopIteration:
381 return
382 first = True
383 for value in iter_values:
384 yield first, False, previous_value
385 first = False
386 previous_value = value
387 yield first, True, previous_value
388 '''
389 syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True)
390 console = Console()
391 console.print(syntax)
392 ```
393
394 输出如下:
395
396 ![语法](https://github.com/textualize/rich/raw/master/imgs/syntax.png)
397
398 </details>
399
400 <details>
401 <summary>栈回溯信息(Tracebacks)</summary>
402
403 Rich 可以渲染出漂亮的[栈回溯信息](https://rich.readthedocs.io/en/latest/traceback.html),它比标准的 Python 格式更容易阅读,且能显示更多的代码。您可以将 Rich 设置为默认的栈回溯处理程序,这样所有未捕获的异常都将由 Rich 为渲染。
404
405 下面是在 OSX(在 Linux 上也类似)系统的效果:
406
407 ![回溯](https://github.com/textualize/rich/raw/master/imgs/traceback.png)
408
409 </details>
410
411 所有的 Rich 可渲染对象都采用了 [Console Protocol](https://rich.readthedocs.io/en/latest/protocol.html) 协议,你可以用该协议实现你独有的 Rich 内容。
412
413 ## 使用 Rich 的项目
414
415 这里是一些使用 Rich 的项目:
416
417 - [BrancoLab/BrainRender](https://github.com/BrancoLab/BrainRender)
418 一个用于三维神经解剖数据可视化的 python 包
419 - [Ciphey/Ciphey](https://github.com/Ciphey/Ciphey)
420 自动解密工具
421 - [emeryberger/scalene](https://github.com/emeryberger/scalene)
422 一个高性能、高精度的 Python CPU 和内存剖析器
423 - [hedythedev/StarCli](https://github.com/hedythedev/starcli)
424 通过命令行浏览 GitHub 热门项目
425 - [intel/cve-bin-tool](https://github.com/intel/cve-bin-tool)
426 这个工具可以扫描一些常见的、有漏洞的组件(openssl、libpng、libxml2、expat和其他一些组件),让你知道你的系统是否包含有已知漏洞的常用库。
427 - [nf-core/tools](https://github.com/nf)
428 包含 nf-core 社区帮助工具的 Python 包
429 - [cansarigol/pdbr](https://github.com/cansarigol/pdbr)
430 pdb + rich 的库,增强调试功能
431 - [plant99/felicette](https://github.com/plant99/felicette)
432 傻瓜式卫星图像
433 - [seleniumbase/SeleniumBase](https://github.com/seleniumbase/SeleniumBase)
434 使用 Selenium 和 pytest 使自动化和测试速度提高10倍,包括电池
435 - [smacke/ffsubsync](https://github.com/smacke/ffsubsync)
436 自动将字幕与视频同步
437 - [tryolabs/norfair](https://github.com/tryolabs/norfair)
438 轻量级 Python 库,用于向任何检测器添加实时 2D 对象跟踪
439 - +[还有很多](https://github.com/textualize/rich/network/dependents)!