Debian Codegraph @

README.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 • [Indonesian readme](https://github.com/textualize/rich/blob/master/README.id.md)
25 • [فارسی readme](https://github.com/textualize/rich/blob/master/README.fa.md)
26 • [Türkçe readme](https://github.com/textualize/rich/blob/master/README.tr.md)
27 • [Polskie readme](https://github.com/textualize/rich/blob/master/README.pl.md)
28
29
30 Rich is a Python library for _rich_ text and beautiful formatting in the terminal.
31
32 The [Rich API](https://rich.readthedocs.io/en/latest/) makes it easy to add color and style to terminal output. Rich can also render pretty tables, progress bars, markdown, syntax highlighted source code, tracebacks, and more — out of the box.
33
34 ![Features](https://github.com/textualize/rich/raw/master/imgs/features.png)
35
36 For a video introduction to Rich see [calmcode.io](https://calmcode.io/rich/introduction.html) by [@fishnets88](https://twitter.com/fishnets88).
37
38 See what [people are saying about Rich](https://www.willmcgugan.com/blog/pages/post/rich-tweets/).
39
40 ## Compatibility
41
42 Rich works with Linux, macOS and Windows. True color / emoji works with new Windows Terminal, classic terminal is limited to 16 colors. Rich requires Python 3.8 or later.
43
44 Rich works with [Jupyter notebooks](https://jupyter.org/) with no additional configuration required.
45
46 ## Installing
47
48 Install with `pip` or your favorite PyPI package manager.
49
50 ```sh
51 python -m pip install rich
52 ```
53
54 Run the following to test Rich output on your terminal:
55
56 ```sh
57 python -m rich
58 ```
59
60 ## Rich Print
61
62 To effortlessly add rich output to your application, you can import the [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) method, which has the same signature as the builtin Python function. Try this:
63
64 ```python
65 from rich import print
66
67 print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())
68 ```
69
70 ![Hello World](https://github.com/textualize/rich/raw/master/imgs/print.png)
71
72 ## Rich REPL
73
74 Rich can be installed in the Python REPL, so that any data structures will be pretty printed and highlighted.
75
76 ```python
77 >>> from rich import pretty
78 >>> pretty.install()
79 ```
80
81 ![REPL](https://github.com/textualize/rich/raw/master/imgs/repl.png)
82
83 ## Using the Console
84
85 For more control over rich terminal content, import and construct a [Console](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console) object.
86
87 ```python
88 from rich.console import Console
89
90 console = Console()
91 ```
92
93 The Console object has a `print` method which has an intentionally similar interface to the builtin `print` function. Here's an example of use:
94
95 ```python
96 console.print("Hello", "World!")
97 ```
98
99 As you might expect, this will print `"Hello World!"` to the terminal. Note that unlike the builtin `print` function, Rich will word-wrap your text to fit within the terminal width.
100
101 There are a few ways of adding color and style to your output. You can set a style for the entire output by adding a `style` keyword argument. Here's an example:
102
103 ```python
104 console.print("Hello", "World!", style="bold red")
105 ```
106
107 The output will be something like the following:
108
109 ![Hello World](https://github.com/textualize/rich/raw/master/imgs/hello_world.png)
110
111 That's fine for styling a line of text at a time. For more finely grained styling, Rich renders a special markup which is similar in syntax to [bbcode](https://en.wikipedia.org/wiki/BBCode). Here's an example:
112
113 ```python
114 console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].")
115 ```
116
117 ![Console Markup](https://github.com/textualize/rich/raw/master/imgs/where_there_is_a_will.png)
118
119 You can use a Console object to generate sophisticated output with minimal effort. See the [Console API](https://rich.readthedocs.io/en/latest/console.html) docs for details.
120
121 ## Rich Inspect
122
123 Rich has an [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) function which can produce a report on any Python object, such as class, instance, or builtin.
124
125 ```python
126 >>> my_list = ["foo", "bar"]
127 >>> from rich import inspect
128 >>> inspect(my_list, methods=True)
129 ```
130
131 ![Log](https://github.com/textualize/rich/raw/master/imgs/inspect.png)
132
133 See the [inspect docs](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect) for details.
134
135 # Rich Library
136
137 Rich contains a number of builtin _renderables_ you can use to create elegant output in your CLI and help you debug your code.
138
139 Click the following headings for details:
140
141 <details>
142 <summary>Log</summary>
143
144 The Console object has a `log()` method which has a similar interface to `print()`, but also renders a column for the current time and the file and line which made the call. By default Rich will do syntax highlighting for Python structures and for repr strings. If you log a collection (i.e. a dict or a list) Rich will pretty print it so that it fits in the available space. Here's an example of some of these features.
145
146 ```python
147 from rich.console import Console
148 console = Console()
149
150 test_data = [
151 {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",},
152 {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
153 {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"},
154 ]
155
156 def test_log():
157 enabled = False
158 context = {
159 "foo": "bar",
160 }
161 movies = ["Deadpool", "Rise of the Skywalker"]
162 console.log("Hello from", console, "!")
163 console.log(test_data, log_locals=True)
164
165
166 test_log()
167 ```
168
169 The above produces the following output:
170
171 ![Log](https://github.com/textualize/rich/raw/master/imgs/log.png)
172
173 Note the `log_locals` argument, which outputs a table containing the local variables where the log method was called.
174
175 The log method could be used for logging to the terminal for long running applications such as servers, but is also a very nice debugging aid.
176
177 </details>
178 <details>
179 <summary>Logging Handler</summary>
180
181 You can also use the builtin [Handler class](https://rich.readthedocs.io/en/latest/logging.html) to format and colorize output from Python's logging module. Here's an example of the output:
182
183 ![Logging](https://github.com/textualize/rich/raw/master/imgs/logging.png)
184
185 </details>
186
187 <details>
188 <summary>Emoji</summary>
189
190 To insert an emoji in to console output place the name between two colons. Here's an example:
191
192 ```python
193 >>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:")
194 😃 🧛 💩 👍 🦝
195 ```
196
197 Please use this feature wisely.
198
199 </details>
200
201 <details>
202 <summary>Tables</summary>
203
204 Rich can render flexible [tables](https://rich.readthedocs.io/en/latest/tables.html) with unicode box characters. There is a large variety of formatting options for borders, styles, cell alignment etc.
205
206 ![table movie](https://github.com/textualize/rich/raw/master/imgs/table_movie.gif)
207
208 The animation above was generated with [table_movie.py](https://github.com/textualize/rich/blob/master/examples/table_movie.py) in the examples directory.
209
210 Here's a simpler table example:
211
212 ```python
213 from rich.console import Console
214 from rich.table import Table
215
216 console = Console()
217
218 table = Table(show_header=True, header_style="bold magenta")
219 table.add_column("Date", style="dim", width=12)
220 table.add_column("Title")
221 table.add_column("Production Budget", justify="right")
222 table.add_column("Box Office", justify="right")
223 table.add_row(
224 "Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
225 )
226 table.add_row(
227 "May 25, 2018",
228 "[red]Solo[/red]: A Star Wars Story",
229 "$275,000,000",
230 "$393,151,347",
231 )
232 table.add_row(
233 "Dec 15, 2017",
234 "Star Wars Ep. VIII: The Last Jedi",
235 "$262,000,000",
236 "[bold]$1,332,539,889[/bold]",
237 )
238
239 console.print(table)
240 ```
241
242 This produces the following output:
243
244 ![table](https://github.com/textualize/rich/raw/master/imgs/table.png)
245
246 Note that console markup is rendered in the same way as `print()` and `log()`. In fact, anything that is renderable by Rich may be included in the headers / rows (even other tables).
247
248 The `Table` class is smart enough to resize columns to fit the available width of the terminal, wrapping text as required. Here's the same example, with the terminal made smaller than the table above:
249
250 ![table2](https://github.com/textualize/rich/raw/master/imgs/table2.png)
251
252 </details>
253
254 <details>
255 <summary>Progress Bars</summary>
256
257 Rich can render multiple flicker-free [progress](https://rich.readthedocs.io/en/latest/progress.html) bars to track long-running tasks.
258
259 For basic usage, wrap any sequence in the `track` function and iterate over the result. Here's an example:
260
261 ```python
262 from rich.progress import track
263
264 for step in track(range(100)):
265 do_step(step)
266 ```
267
268 It's not much harder to add multiple progress bars. Here's an example taken from the docs:
269
270 ![progress](https://github.com/textualize/rich/raw/master/imgs/progress.gif)
271
272 The columns may be configured to show any details you want. Built-in columns include percentage complete, file size, file speed, and time remaining. Here's another example showing a download in progress:
273
274 ![progress](https://github.com/textualize/rich/raw/master/imgs/downloader.gif)
275
276 To try this out yourself, see [examples/downloader.py](https://github.com/textualize/rich/blob/master/examples/downloader.py) which can download multiple URLs simultaneously while displaying progress.
277
278 </details>
279
280 <details>
281 <summary>Status</summary>
282
283 For situations where it is hard to calculate progress, you can use the [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) method which will display a 'spinner' animation and message. The animation won't prevent you from using the console as normal. Here's an example:
284
285 ```python
286 from time import sleep
287 from rich.console import Console
288
289 console = Console()
290 tasks = [f"task {n}" for n in range(1, 11)]
291
292 with console.status("[bold green]Working on tasks...") as status:
293 while tasks:
294 task = tasks.pop(0)
295 sleep(1)
296 console.log(f"{task} complete")
297 ```
298
299 This generates the following output in the terminal.
300
301 ![status](https://github.com/textualize/rich/raw/master/imgs/status.gif)
302
303 The spinner animations were borrowed from [cli-spinners](https://www.npmjs.com/package/cli-spinners). You can select a spinner by specifying the `spinner` parameter. Run the following command to see the available values:
304
305 ```
306 python -m rich.spinner
307 ```
308
309 The above command generates the following output in the terminal:
310
311 ![spinners](https://github.com/textualize/rich/raw/master/imgs/spinners.gif)
312
313 </details>
314
315 <details>
316 <summary>Tree</summary>
317
318 Rich can render a [tree](https://rich.readthedocs.io/en/latest/tree.html) with guide lines. A tree is ideal for displaying a file structure, or any other hierarchical data.
319
320 The labels of the tree can be simple text or anything else Rich can render. Run the following for a demonstration:
321
322 ```
323 python -m rich.tree
324 ```
325
326 This generates the following output:
327
328 ![markdown](https://github.com/textualize/rich/raw/master/imgs/tree.png)
329
330 See the [tree.py](https://github.com/textualize/rich/blob/master/examples/tree.py) example for a script that displays a tree view of any directory, similar to the linux `tree` command.
331
332 </details>
333
334 <details>
335 <summary>Columns</summary>
336
337 Rich can render content in neat [columns](https://rich.readthedocs.io/en/latest/columns.html) with equal or optimal width. Here's a very basic clone of the (MacOS / Linux) `ls` command which displays a directory listing in columns:
338
339 ```python
340 import os
341 import sys
342
343 from rich import print
344 from rich.columns import Columns
345
346 directory = os.listdir(sys.argv[1])
347 print(Columns(directory))
348 ```
349
350 The following screenshot is the output from the [columns example](https://github.com/textualize/rich/blob/master/examples/columns.py) which displays data pulled from an API in columns:
351
352 ![columns](https://github.com/textualize/rich/raw/master/imgs/columns.png)
353
354 </details>
355
356 <details>
357 <summary>Markdown</summary>
358
359 Rich can render [markdown](https://rich.readthedocs.io/en/latest/markdown.html) and does a reasonable job of translating the formatting to the terminal.
360
361 To render markdown import the `Markdown` class and construct it with a string containing markdown code. Then print it to the console. Here's an example:
362
363 ```python
364 from rich.console import Console
365 from rich.markdown import Markdown
366
367 console = Console()
368 with open("README.md") as readme:
369 markdown = Markdown(readme.read())
370 console.print(markdown)
371 ```
372
373 This will produce output something like the following:
374
375 ![markdown](https://github.com/textualize/rich/raw/master/imgs/markdown.png)
376
377 </details>
378
379 <details>
380 <summary>Syntax Highlighting</summary>
381
382 Rich uses the [pygments](https://pygments.org/) library to implement [syntax highlighting](https://rich.readthedocs.io/en/latest/syntax.html). Usage is similar to rendering markdown; construct a `Syntax` object and print it to the console. Here's an example:
383
384 ```python
385 from rich.console import Console
386 from rich.syntax import Syntax
387
388 my_code = '''
389 def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
390 """Iterate and generate a tuple with a flag for first and last value."""
391 iter_values = iter(values)
392 try:
393 previous_value = next(iter_values)
394 except StopIteration:
395 return
396 first = True
397 for value in iter_values:
398 yield first, False, previous_value
399 first = False
400 previous_value = value
401 yield first, True, previous_value
402 '''
403 syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True)
404 console = Console()
405 console.print(syntax)
406 ```
407
408 This will produce the following output:
409
410 ![syntax](https://github.com/textualize/rich/raw/master/imgs/syntax.png)
411
412 </details>
413
414 <details>
415 <summary>Tracebacks</summary>
416
417 Rich can render [beautiful tracebacks](https://rich.readthedocs.io/en/latest/traceback.html) which are easier to read and show more code than standard Python tracebacks. You can set Rich as the default traceback handler so all uncaught exceptions will be rendered by Rich.
418
419 Here's what it looks like on OSX (similar on Linux):
420
421 ![traceback](https://github.com/textualize/rich/raw/master/imgs/traceback.png)
422
423 </details>
424
425 All Rich renderables make use of the [Console Protocol](https://rich.readthedocs.io/en/latest/protocol.html), which you can also use to implement your own Rich content.
426
427 # Rich CLI
428
429
430 See also [Rich CLI](https://github.com/textualize/rich-cli) for a command line application powered by Rich. Syntax highlight code, render markdown, display CSVs in tables, and more, directly from the command prompt.
431
432
433 ![Rich CLI](https://raw.githubusercontent.com/Textualize/rich-cli/main/imgs/rich-cli-splash.jpg)
434
435 # Textual
436
437 See also Rich's sister project, [Textual](https://github.com/Textualize/textual), which you can use to build sophisticated User Interfaces in the terminal.
438
439 ![textual-splash](https://github.com/user-attachments/assets/4caeb77e-48c0-4cf7-b14d-c53ded855ffd)
440
441 # Toad
442
443 [Toad](https://github.com/batrachianai/toad) is a unified interface for agentic coding. Built with Rich and Textual.
444
445 ![toad](https://github.com/user-attachments/assets/6678b707-1aeb-420f-99ad-abfcd4356771)