Rich
Rich
Release 13.6.0
Will McGugan
1 Introduction 1
1.1 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Rich in the REPL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.5 Rich Inspect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Console API 5
2.1 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Color systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.5 Printing JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.6 Low level output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.7 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.8 Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.9 Justify / Alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.10 Overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.11 Console style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.12 Soft Wrapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.13 Cropping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.14 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.15 Exporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.16 Error console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.17 File output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.18 Capturing output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.19 Paging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.20 Alternate screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.21 Terminal detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.22 Interactive mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.23 Environment variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3 Styles 15
3.1 Defining Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.2 Style Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.3 Style Themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4 Console Markup 19
4.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.2 Rendering Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
i
4.3 Markup API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5 Rich Text 23
5.1 Text attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6 Highlighting 25
6.1 Custom Highlighters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
6.2 Builtin Highlighters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
7 Pretty Printing 27
7.1 pprint method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
7.2 Pretty renderable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
7.3 Rich Repr Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
7.4 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
8 Logging Handler 33
8.1 Handle exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
8.2 Suppressing Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
9 Traceback 35
9.1 Printing tracebacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
9.2 Traceback Handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
9.3 Suppressing Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
9.4 Max Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
10 Prompt 39
11 Columns 41
12 Render Groups 43
13 Markdown 45
14 Padding 47
15 Panel 49
16 Progress Display 51
16.1 Basic Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
16.2 Advanced usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
16.3 Multiple Progress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
16.4 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
17 Syntax 57
17.1 Line numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
17.2 Theme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
17.3 Background color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
17.4 Syntax CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
18 Tables 59
18.1 Table Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
18.2 Border Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
18.3 Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
18.4 Empty Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
18.5 Adding Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
18.6 Column Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
ii
18.7 Vertical Alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
18.8 Grids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
19 Tree 63
19.1 Tree Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
19.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
20 Live Display 65
20.1 Basic usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
20.2 Updating the renderable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
20.3 Alternate screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
20.4 Transient display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
20.5 Auto refresh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
20.6 Vertical overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
20.7 Print / log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
20.8 Redirecting stdout / stderr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
21 Layout 69
21.1 Creating layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
21.2 Setting renderables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
21.3 Fixed size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
21.4 Ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
21.5 Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
21.6 Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
21.7 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
22 Console Protocol 73
22.1 Console Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
22.2 Console Render . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
23 Reference 75
23.1 rich.align . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
23.2 rich.bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
23.3 rich.color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
23.4 rich.columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
23.5 rich.console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
23.6 rich.emoji . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
23.7 rich.highlighter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
23.8 rich . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
23.9 rich.json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
23.10 rich.layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
23.11 rich.live . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
23.12 rich.logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
23.13 rich.markdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
23.14 rich.markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
23.15 rich.measure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
23.16 rich.padding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
23.17 rich.panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
23.18 rich.pretty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
23.19 rich.progress_bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
23.20 rich.progress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
23.21 rich.prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
23.22 rich.protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
23.23 rich.rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
23.24 rich.segment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
iii
23.25 rich.spinner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
23.26 rich.status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
23.27 rich.style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
23.28 rich.styled . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
23.29 rich.syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
23.30 rich.table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
23.31 rich.text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
23.32 rich.theme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
23.33 rich.traceback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
23.34 rich.tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
23.35 rich.abc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
24 Appendix 185
24.1 Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
24.2 Standard Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Index 191
iv
CHAPTER
ONE
INTRODUCTION
Rich is a Python library for writing rich text (with color and style) to the terminal, and for displaying advanced content
such as tables, markdown, and syntax highlighted code.
Use Rich to make your command line applications visually appealing and present data in a more readable way. Rich
can also be a useful debugging aid by pretty printing and syntax highlighting data structures.
1.1 Requirements
Note: PyCharm users will need to enable “emulate terminal” in output console option in run/debug configuration to
see styled output.
1.2 Installation
You can install Rich from PyPI with pip or your favorite package manager:
Add the -U switch to update to the current version, if Rich is already installed.
If you intend to use Rich with Jupyter then there are some additional dependencies which you can install with the
following command:
1
Rich, Release 13.6.0
The quickest way to get up and running with Rich is to import the alternative print function which takes the same
arguments as the built-in print and may be used as a drop-in replacement. Here’s how you would do that:
You can then print strings or objects to the terminal in the usual way. Rich will do some basic syntax highlighting and
format data structures to make them easier to read.
Strings may contain Console Markup which can be used to insert color and styles in to the output.
The following demonstrates both console markup and pretty formatting of Python objects:
This writes the following output to the terminal (including all the colors and styles):
If you would rather not shadow Python’s built-in print, you can import rich.print as rprint (for example):
Rich may be installed in the REPL so that Python data structures are automatically pretty printed with syntax high-
lighting. Here’s how:
You can also use this feature to try out Rich renderables. Here’s an example:
Rich also includes an IPython extension that will do this same pretty install + pretty tracebacks. Here’s how to load it:
You can also have it load by default by adding “rich” to the c.InteractiveShellApp.extension variable in IPython
Configuration.
2 Chapter 1. Introduction
Rich, Release 13.6.0
Rich has an inspect() function which can generate a report on any Python object. It is a fantastic debug aid, and a
good example of the output that Rich can generate. Here is a simple example:
4 Chapter 1. Introduction
CHAPTER
TWO
CONSOLE API
For complete control over terminal formatting, Rich offers a Console class. Most applications will require a single
Console instance, so you may want to create one at the module level or as an attribute of your top-level object. For
example, you could add a file called “console.py” to your project:
Then you can import the console from anywhere in your project like this:
The console object handles the mechanics of generating ANSI escape sequences for color and style. It will auto-detect
the capabilities of the terminal and convert colors if necessary.
2.1 Attributes
There are several “standards” for writing color to the terminal which are not all universally supported. Rich will auto-
detect the appropriate color system, or you can set it manually by supplying a value for color_system to the Console
constructor.
You can set color_system to one of the following values:
• None Disables color entirely.
• "auto" Will auto-detect the color system.
• "standard" Can display 8 colors, with normal and bright variations, for 16 colors in total.
• "256" Can display the 16 colors from “standard” plus a fixed palette of 240 colors.
• "truecolor" Can display 16.7 million colors, which is likely all the colors your monitor can display.
5
Rich, Release 13.6.0
• "windows" Can display 8 colors in legacy Windows terminal. New Windows terminal can display “truecolor”.
Warning: Be careful when setting a color system, if you set a higher color system than your terminal supports,
your text may be unreadable.
2.3 Printing
To write rich content to the terminal use the print() method. Rich will convert any object to a string via its (__str__)
method and perform some simple syntax highlighting. It will also do pretty printing of any containers, such as dicts
and lists. If you print a string it will render Console Markup. Here are some examples:
console.print([1, 2, 3])
console.print("[blue underline]Looks like a link")
console.print(locals())
console.print("FOO", style="white on blue")
You can also use print() to render objects that support the Console Protocol, which includes Rich’s built-in objects
such as Text, Table, and Syntax – or other custom objects.
2.4 Logging
The log() method offers the same capabilities as print, but adds some features useful for debugging a running appli-
cation. Logging writes the current time in a column to the left, and the file and line where the method was called to a
column on the right. Here’s an example:
To help with debugging, the log() method has a log_locals parameter. If you set this to True, Rich will display a
table of local variables where the method was called.
The print_json() method will pretty print (format and style) a string containing JSON. Here’s a short example:
Because printing JSON is a common requirement, you may import print_json from the main namespace:
You can also pretty print JSON via the command line with the following:
In additional to print() and log(), Rich has an out() method which provides a lower-level way of writing to the
terminal. The out() method converts all the positional arguments to strings and won’t pretty print, word wrap, or apply
markup to the output, but can apply a basic style and will optionally do highlighting.
Here’s an example:
2.7 Rules
The rule() method will draw a horizontal line with an optional title, which is a good way of dividing your terminal
output into sections.
The rule method also accepts a style parameter to set the style of the line, and an align parameter to align the title
(“left”, “center”, or “right”).
2.8 Status
Rich can display a status message with a ‘spinner’ animation that won’t interfere with regular console output. Run the
following command for a demo of this feature:
python -m rich.status
To display a status message, call status() with the status message (which may be a string, Text, or other renderable).
The result is a context manager which starts and stops the status display around a block of code. Here’s an example:
with console.status("Working..."):
do_work()
You can change the spinner animation via the spinner parameter:
Run the following command to see the available choices for spinner:
python -m rich.spinner
Both print and log support a justify argument which if set must be one of “default”, “left”, “right”, “center”, or “full”.
If “left”, any text printed (or logged) will be left aligned, if “right” text will be aligned to the right of the terminal, if
“center” the text will be centered, and if “full” the text will be lined up with both the left and right edges of the terminal
(like printed text in a book).
The default for justify is "default" which will generally look the same as "left" but with a subtle difference.
Left justify will pad the right of the text with spaces, while a default justify will not. You will only notice the difference
if you set a background color with the style argument. The following example demonstrates the difference:
console = Console(width=20)
2.10 Overflow
Overflow is what happens when text you print is larger than the available space. Overflow may occur if you print long
‘words’ such as URLs for instance, or if you have text inside a panel or table cell with restricted space.
You can specify how Rich should handle overflow with the overflow argument to print() which should be one of
the following strings: “fold”, “crop”, “ellipsis”, or “ignore”. The default is “fold” which will put any excess characters
on the following line, creating as many new lines as required to fit the text.
The “crop” method truncates the text at the end of the line, discarding any characters that would overflow.
The “ellipsis” method is similar to “crop”, but will insert an ellipsis character (”. . . ”) at the end of any text that has
been truncated.
The following code demonstrates the basic overflow methods:
console = Console(width=14)
supercali = "supercalifragilisticexpialidocious"
The Console has a style attribute which you can use to apply a style to everything you print. By default style is
None meaning no extra style is applied, but you can set it to any valid style. Here’s an example of a Console with a
style attribute set:
Rich word wraps text you print by inserting line breaks. You can disable this behavior by setting soft_wrap=True
when calling print(). With soft wrapping enabled any text that doesn’t fit will run on to the following line(s), just
like the built-in print.
2.13 Cropping
The print() method has a boolean crop argument. The default value for crop is True which tells Rich to crop any
content that would otherwise run on to the next line. You generally don’t need to think about cropping, as Rich will
resize content to fit within the available width.
2.14 Input
The console class has an input() method which works in the same way as Python’s built-in input() function, but
can use anything that Rich can print as a prompt. For example, here’s a colorful prompt with an emoji:
If Python’s builtin readline module is previously loaded, elaborate line editing and history features will be available.
2.15 Exporting
The Console class can export anything written to it as either text, svg, or html. To enable exporting, first set
record=True on the constructor. This tells Rich to save a copy of any data you print() or log(). Here’s an example:
After you have written content, you can call export_text(), export_svg() or export_html() to get the console
output as a string. You can also call save_text(), save_svg(), or save_html() to write the contents directly to
disk.
For examples of the html output generated by Rich Console, see Standard Colors.
When using export_svg() or save_svg(), the width of the SVG will match the width of your terminal window (in
terms of characters), while the height will scale automatically to accommodate the console output.
You can open the SVG in a web browser. You can also insert it in to a webpage with an <img> tag or by copying the
markup in to your HTML.
The image below shows an example of an SVG exported by Rich.
You can customize the theme used during SVG export by importing the desired theme from the rich.terminal_theme
module and passing it to export_svg() or save_svg() via the theme parameter:
console = Console(record=True)
console.save_svg("example.svg", theme=MONOKAI)
Alternatively, you can create a theme of your own by constructing a rich.terminal_theme.TerminalTheme in-
stance yourself and passing that in.
Note: The SVGs reference the Fira Code font. If you embed a Rich SVG in your page, you may also want to add a
link to the Fira Code CSS
The Console object will write to sys.stdout by default (so that you see output in the terminal). If you construct the
Console with stderr=True Rich will write to sys.stderr. You may want to use this to create an error console so
you can split error messages from regular output. Here’s an example:
You might also want to set the style parameter on the Console to make error messages visually distinct. Here’s how
you might do that:
You can tell the Console object to write to a file by setting the file argument on the constructor – which should be a
file-like object opened for writing text. You could use this to write to a file without the output ever appearing on the
terminal. Here’s an example:
import sys
from rich.console import Console
from datetime import datetime
Note that when writing to a file you may want to explicitly set the width argument if you don’t want to wrap the output
to the current console width.
There may be situations where you want to capture the output from a Console rather than writing it directly to the
terminal. You can do this with the capture() method which returns a context manager. On exit from this context
manager, call get() to return the string that would have been written to the terminal. Here’s an example:
An alternative way of capturing output is to set the Console file to a io.StringIO. This is the recommended method
if you are testing console output in unit tests. Here’s an example:
2.19 Paging
If you have some long output to present to the user you can use a pager to display it. A pager is typically an application
on your operating system which will at least support pressing a key to scroll, but will often support scrolling up and
down through the text and other features.
You can page output from a Console by calling pager() which returns a context manager. When the pager exits,
anything that was printed will be sent to the pager. Here’s an example:
Since the default pager on most platforms don’t support color, Rich will strip color from the output. If you know that
your pager supports color, you can set styles=True when calling the pager() method.
Note: Rich will look at MANPAGER then the PAGER environment variables (MANPAGER takes priority) to get the pager
command. On Linux and macOS you can set one of these to less -r to enable paging with ANSI styles.
Warning: This feature is currently experimental. You might want to wait before using it in production.
Terminals support an ‘alternate screen’ mode which is separate from the regular terminal and allows for full-screen
applications that leave your stream of input and commands intact. Rich supports this mode via the set_alt_screen()
method, although it is recommended that you use screen() which returns a context manager that disables alternate
mode on exit.
Here’s an example of an alternate screen:
console = Console()
with console.screen():
console.print(locals())
sleep(5)
The above code will display a pretty printed dictionary on the alternate screen before returning to the command prompt
after 5 seconds.
You can also provide a renderable to screen() which will be displayed in the alternate screen when you call update().
Here’s an example:
console = Console()
Updating the screen with a renderable allows Rich to crop the contents to fit the screen without scrolling.
For a more powerful way of building full screen interfaces with Rich, see Live Display.
Note: If you ever find yourself stuck in alternate mode after exiting Python code, type reset in the terminal
If Rich detects that it is not writing to a terminal it will strip control codes from the output. If you want to write control
codes to a regular file then set force_terminal=True on the constructor.
Letting Rich auto-detect terminals is useful as it will write plain text when you pipe output to a file or other application.
Rich will remove animations such as progress bars and status indicators when not writing to a terminal as you
probably don’t want to write these out to a text file (for example). You can override this behavior by setting the
force_interactive argument on the constructor. Set it to True to enable animations or False to disable them.
Note: Some CI systems support ANSI color and style but not anything that moves the cursor or selectively refreshes
parts of the terminal. For these you might want to set force_terminal to True and force_interactive to False.
Note: The NO_COLOR environment variable removes color only. Styles such as dim, bold, italic, underline etc. are
preserved.
If width / height arguments are not explicitly provided as arguments to Console then the environment variables
COLUMNS/LINES can be used to set the console width/height. JUPYTER_COLUMNS/JUPYTER_LINES behave similarly
and are used in Jupyter.
THREE
STYLES
In various places in the Rich API you can set a “style” which defines the color of the text and various attributes such
as bold, italic etc. A style may be given as a string containing a style definition or as an instance of a Style class.
A style definition is a string containing one or more words to set colors and attributes.
To specify a foreground color use one of the 256 Standard Colors. For example, to print “Hello” in magenta:
console.print("Hello", style="magenta")
You may also use the color’s number (an integer between 0 and 255) with the syntax "color(<number>)". The
following will give the equivalent output:
console.print("Hello", style="color(5)")
Alternatively you can use a CSS-like syntax to specify a color with a “#” followed by three pairs of hex characters, or
in RGB form with three decimal integers. The following two lines both print “Hello” in the same color (purple):
console.print("Hello", style="#af00ff")
console.print("Hello", style="rgb(175,0,255)")
The hex and rgb forms allow you to select from the full truecolor set of 16.7 million colors.
Note: Some terminals only support 256 colors. Rich will attempt to pick the closest color it can if your color isn’t
available.
By itself, a color will change the foreground color. To specify a background color, precede the color with the word
“on”. For example, the following prints text in red on a white background:
You can also set a color with the word "default" which will reset the color to a default managed by your terminal
software. This works for backgrounds as well, so the style of "default on default" is what your terminal starts
with.
You can set a style attribute by adding one or more of the following words:
• "bold" or "b" for bold text.
• "blink" for text that flashes (use this one sparingly).
15
Rich, Release 13.6.0
• "blink2" for text that flashes rapidly (not supported by most terminals).
• "conceal" for concealed text (not supported by most terminals).
• "italic" or "i" for italic text (not supported on Windows).
• "reverse" or "r" for text with foreground and background colors reversed.
• "strike" or "s" for text with a line through it.
• "underline" or "u" for underlined text.
Rich also supports the following styles, which are not well supported and may not display in your terminal:
• "underline2" or "uu" for doubly underlined text.
• "frame" for framed text.
• "encircle" for encircled text.
• "overline" or "o" for overlined text.
Style attributes and colors may be used in combination with each other. For example:
Styles may be negated by prefixing the attribute with the word “not”. This can be used to turn off styles if they overlap.
For example:
This will print “foo” and “baz” in bold, but “bar” will be in normal text.
Styles may also have a "link" attribute, which will turn any styled text in to a hyperlink (if supported by your terminal
software).
To add a link to a style, the definition should contain the word "link" followed by a URL. The following example will
make a clickable link:
Note: If you are familiar with HTML you may find applying links in this way a little odd, but the terminal considers
a link to be another attribute just like bold, italic etc.
Ultimately the style definition is parsed and an instance of a Style class is created. If you prefer, you can use the Style
class in place of the style definition. Here’s an example:
It is slightly quicker to construct a Style class like this, since a style definition takes a little time to parse – but only on
the first call, as Rich will cache parsed style definitions.
Styles may be combined by adding them together, which is useful if you want to modify attributes of an existing style.
Here’s an example:
16 Chapter 3. Styles
Rich, Release 13.6.0
base_style = Style.parse("cyan")
console.print("Hello, World", style = base_style + Style(underline=True))
You can parse a style definition explicitly with the parse() method, which accepts the style definition and returns a
Style instance. For example, the following two lines are equivalent:
If you re-use styles it can be a maintenance headache if you ever want to modify an attribute or color – you would have
to change every line where the style is used. Rich provides a Theme class which you can use to define custom styles
that you can refer to by name. That way you only need to update your styles in one place.
Style themes can make your code more semantic, for instance a style called "warning" better expresses intent that
"italic magenta underline".
To use a style theme, construct a Theme instance and pass it to the Console constructor. Here’s an example:
Note: style names must be lower case, start with a letter, and only contain letters or the characters ".", "-", "_".
The Theme class will inherit the default styles built-in to Rich. If your custom theme contains the name of an existing
style, it will replace it. This allows you to customize the defaults as easily as you can create your own styles. For
instance, here’s how you can change how Rich highlights numbers:
You can disable inheriting the default theme by setting inherit=False on the rich.theme.Theme constructor.
To see the default theme, run the following commands:
python -m rich.theme
python -m rich.default_styles
If you prefer, you can write your styles in an external config file rather than in Python. Here’s an example of the format:
[styles]
info = dim cyan
warning = magenta
danger = bold red
18 Chapter 3. Styles
CHAPTER
FOUR
CONSOLE MARKUP
Rich supports a simple markup which you can use to insert color and styles virtually everywhere Rich would accept a
string (e.g. print() and log()).
Run the following command to see some examples:
python -m rich.markup
4.1 Syntax
Console markup uses a syntax inspired by bbcode. If you write the style (see Styles) in square brackets, e.g. [bold
red], that style will apply until it is closed with a corresponding [/bold red].
Here’s a simple example:
If you don’t close a style, it will apply until the end of the string. Which is sometimes convenient if you want to style a
single line. For example:
There is a shorthand for closing a style. If you omit the style name from the closing tag, Rich will close the last style.
For example:
These markup tags may be use in combination with each other and don’t need to be strictly nested. The following
example demonstrates overlapping of markup tags:
19
Rich, Release 13.6.0
4.1.1 Errors
Rich will raise MarkupError if the markup contains one of the following errors:
• Mismatched tags, e.g. "[bold]Hello[/red]"
• No matching tag for implicit close, e.g. "no tags[/]"
4.1.2 Links
Console markup can output hyperlinks with the following syntax: [link=URL]text[/link]. Here’s an example:
print("Visit my [link=https://www.willmcgugan.com]blog[/link]!")
If your terminal software supports hyperlinks, you will be able to click the word “blog” which will typically open a
browser. If your terminal doesn’t support hyperlinks, you will see the text but it won’t be clickable.
4.1.3 Escaping
Occasionally you may want to print something that Rich would interpret as markup. You can escape a tag by preceding
it with a backslash. Here’s an example:
Without the backslash, Rich will assume that [bar] is a tag and remove it from the output if there is no “bar” style.
Note: If you want to prevent the backslash from escaping the tag and output a literal backslash before a tag you can
enter two backslashes.
def greet(name):
console.print(f"Hello {name}!")
Calling greet("Will") will print a greeting, but if you were to call greet("[blink]Gotcha![/blink]") then you
will also get blinking text, which may not be desirable. The solution is to escape the arguments:
4.1.4 Emoji
If you add an emoji code to markup it will be replaced with the equivalent unicode character. An emoji code consists
of the name of the emoji surrounded be colons (:). Here’s an example:
Some emojis have two variants, the “emoji” variant displays in full color, and the “text” variant displays in monochrome
(whatever your default colors are set to). You can specify the variant you want by adding either “-emoji” or “-text” to
the emoji code. Here’s an example:
To see a list of all the emojis available, run the following command:
python -m rich.emoji
By default, Rich will render console markup when you explicitly pass a string to print() or implicitly when you
embed a string in another renderable object such as Table or Panel.
Console markup is convenient, but you may wish to disable it if the syntax clashes with the string you want to print.
You can do this by setting markup=False on the print() method or on the Console constructor.
You can convert a string to styled text by calling from_markup(), which returns a Text instance you can print or add
more styles to.
FIVE
RICH TEXT
Rich has a Text class you can use to mark up strings with color and style attributes. You can use a Text instance
anywhere a string is accepted, which gives you a lot of control over presentation.
You can consider this class to be like a string with marked up regions of text. Unlike a built-in str, a Text instance is
mutable, and most methods operate in-place rather than returning a new instance.
One way to add a style to Text is the stylize() method which applies a style to a start and end offset. Here is an
example:
console = Console()
text = Text("Hello, World!")
text.stylize("bold magenta", 0, 6)
console.print(text)
This will print “Hello, World!” to the terminal, with the first word in bold magenta.
Alternatively, you can construct styled text by calling append() to add a string and style to the end of the Text. Here’s
an example:
text = Text()
text.append("Hello", style="bold magenta")
text.append(" World!")
console.print(text)
If you would like to use text that is already formatted with ANSI codes, call from_ansi() to convert it to a Text
object:
Since building Text instances from parts is a common requirement, Rich offers assemble() which will combine strings
or pairs of string and Style, and return a Text instance. The follow example is equivalent to the code above:
You can apply a style to given words in the text with highlight_words() or for ultimate control call
highlight_regex() to highlight text matching a regular expression.
23
Rich, Release 13.6.0
The Text class has a number of parameters you can set on the constructor to modify how the text is displayed.
• justify should be “left”, “center”, “right”, or “full”, and will override default justify behavior.
• overflow should be “fold”, “crop”, or “ellipsis”, and will override default overflow.
• no_wrap prevents wrapping if the text is longer then the available width.
• tab_size Sets the number of characters in a tab.
A Text instance may be used in place of a plain string virtually everywhere in the Rich API, which gives you a lot of
control in how text renders within other Rich renderables. For instance, the following example right aligns text within
a Panel:
SIX
HIGHLIGHTING
Rich will automatically highlight patterns in text, such as numbers, strings, collections, booleans, None, and a few more
exotic patterns such as file paths, URLs and UUIDs.
You can disable highlighting either by setting highlight=False on print() or log(), or by setting
highlight=False on the Console constructor which disables it everywhere. If you disable highlighting on the
constructor, you can still selectively enable highlighting with highlight=True on print / log.
If the default highlighting doesn’t fit your needs, you can define a custom highlighter. The easiest way to do this is to
extend the RegexHighlighter class which applies a style to any text matching a list of regular expressions.
Here’s an example which highlights text that looks like an email address:
class EmailHighlighter(RegexHighlighter):
"""Apply style to anything that looks like an email."""
base_style = "example."
highlights = [r"(?P<email>[\w-]+@([\w-]+\.)+[\w-]+)"]
The highlights class variable should contain a list of regular expressions. The group names of any matching expres-
sions are prefixed with the base_style attribute and used as styles for matching text. In the example above, any email
addresses will have the style “example.email” applied, which we’ve defined in a custom Theme.
Setting the highlighter on the Console will apply highlighting to all text you print (if enabled). You can also use a
highlighter on a more granular level by using the instance as a callable and printing the result. For example, we could
use the email highlighter class like this:
console = Console(theme=theme)
highlight_emails = EmailHighlighter()
console.print(highlight_emails("Send funds to money@example.org"))
25
Rich, Release 13.6.0
While RegexHighlighter is quite powerful, you can also extend its base class Highlighter to implement a custom
scheme for highlighting. It contains a single method highlight which is passed the Text to highlight.
Here’s a silly example that highlights every character with a different color:
class RainbowHighlighter(Highlighter):
def highlight(self, text):
for index in range(len(text)):
text.stylize(f"color({randint(16, 255)})", index, index + 1)
rainbow = RainbowHighlighter()
print(rainbow("I must not fear. Fear is the mind-killer."))
26 Chapter 6. Highlighting
CHAPTER
SEVEN
PRETTY PRINTING
In addition to syntax highlighting, Rich will format (i.e. pretty print) containers such as lists, dicts, and sets.
Run the following command to see an example of pretty printed output:
python -m rich.pretty
Note how the output will change to fit within the terminal width.
The pprint() method offers a few more arguments you can use to tweak how objects are pretty printed. Here’s how
you would import it:
Rich can draw indent guides to highlight the indent level of a data structure. These can make it easier to read more
deeply nested output. The pprint method enables indent guides by default. You can set indent_guides=False to
disable this feature.
Rich is quite conservative about expanding data structures and will try to fit as much in each line as it can. If you prefer,
you can tell Rich to fully expand all data structures by setting expand_all=True. Here’s an example:
27
Rich, Release 13.6.0
Very long data structures can be difficult to read and you may find yourself scrolling through multiple pages in the
terminal to find the data you are interested in. Rich can truncate containers and long strings to give you an overview
without swamping your terminal.
If you set the max_length argument to an integer, Rich will truncate containers with more than the given number of
elements. If data is truncated, Rich will display an ellipsis ... and the number of elements not shown.
Here’s an example:
If you set the max_string argument to an integer, Rich will truncate strings over that length. Truncated string will be
appended with the number of characters that have not been shown. Here’s an example:
Rich offers a Pretty class which you can use to insert pretty printed data in to another renderable.
The following example displays pretty printed data within a simple panel:
pretty = Pretty(locals())
panel = Panel(pretty)
print(panel)
There are a large number of options to tweak the pretty formatting, See the Pretty reference for details.
Rich is able to syntax highlight any output, but the formatting is restricted to built-in containers, dataclasses, and other
objects Rich knows about, such as objects generated by the attrs library. To add Rich formatting capabilities to custom
objects, you can implement the rich repr protocol.
Run the following command to see an example of what the Rich repr protocol can generate:
python -m rich.repr
First, let’s look at a class that might benefit from a Rich repr:
class Bird:
def __init__(self, name, eats=None, fly=True, extinct=False):
self.name = name
self.eats = list(eats) if eats else []
self.fly = fly
self.extinct = extinct
(continues on next page)
def __repr__(self):
return f"Bird({self.name!r}, eats={self.eats!r}, fly={self.fly!r}, extinct={self.
˓→extinct!r})"
BIRDS = {
"gull": Bird("gull", eats=["fish", "chips", "ice cream", "sausage rolls"]),
"penguin": Bird("penguin", eats=["fish"], fly=False),
"dodo": Bird("dodo", eats=["fruit"], fly=False, extinct=True)
}
print(BIRDS)
The output is long enough to wrap on to the next line, which can make it hard to read. The repr strings are informative
but a little verbose since they include default arguments. If we print this with Rich, things are improved somewhat:
{
'gull': Bird('gull', eats=['fish', 'chips', 'ice cream', 'sausage rolls'],
fly=True, extinct=False),
'penguin': Bird('penguin', eats=['fish'], fly=False, extinct=False),
'dodo': Bird('dodo', eats=['fruit'], fly=False, extinct=True)
}
Rich knows how to format the container dict, but the repr strings are still verbose, and there is some wrapping of the
output (assumes an 80 character terminal).
We can solve both these issues by adding the following __rich_repr__ method:
def __rich_repr__(self):
yield self.name
yield "eats", self.eats
yield "fly", self.fly, True
yield "extinct", self.extinct, False
Now if we print the same object with Rich we would see the following:
{
'gull': Bird(
'gull',
eats=['fish', 'chips', 'ice cream', 'sausage rolls']
),
'penguin': Bird('penguin', eats=['fish'], fly=False),
'dodo': Bird('dodo', eats=['fruit'], fly=False, extinct=True)
}
The default arguments have been omitted, and the output has been formatted nicely. The output remains readable even
if we have less room in the terminal, or our objects are part of a deeply nested data structure:
{
'gull': Bird(
'gull',
eats=[
'fish',
'chips',
'ice cream',
'sausage rolls'
]
),
'penguin': Bird(
'penguin',
eats=['fish'],
fly=False
),
'dodo': Bird(
'dodo',
eats=['fruit'],
fly=False,
extinct=True
)
}
You can add a __rich_repr__ method to any class to enable the Rich formatting. This method should return an
iterable of tuples. You could return a list of tuples, but it’s easier to express with the yield keywords, making it a
generator.
Each tuple specifies an element in the output.
• yield value will generate a positional argument.
• yield name, value will generate a keyword argument.
• yield name, value, default will generate a keyword argument if value is not equal to default.
If you use None as the name, then it will be treated as a positional argument as well, in order to support having tuple
positional arguments.
You can also tell Rich to generate the angular bracket style of repr, which tend to be used where there is no easy way
to recreate the object’s constructor. To do this set the function attribute "angular" to True immediately after your
__rich_repr__ method. For example:
__rich_repr__.angular = True
This will change the output of the Rich repr example to the following:
{
'gull': <Bird 'gull' eats=['fish', 'chips', 'ice cream', 'sausage rolls']>,
'penguin': <Bird 'penguin' eats=['fish'] fly=False>,
'dodo': <Bird 'dodo' eats=['fruit'] fly=False extinct=True>
}
Note that you can add __rich_repr__ methods to third-party libraries without including Rich as a dependency. If
Rich is not installed, then nothing will break. Hopefully more third-party libraries will adopt Rich repr methods in the
future.
7.3.1 Typing
If you want to type the Rich repr method you can import and return rich.repr.Result, which will help catch logical
errors:
import rich.repr
class Bird:
def __init__(self, name, eats=None, fly=True, extinct=False):
self.name = name
self.eats = list(eats) if eats else []
self.fly = fly
self.extinct = extinct
Rich can generate a rich repr automatically if the parameters are named the same as your attributes.
To automatically build a rich repr, use the auto() class decorator. The Bird example above follows the above rule, so
we don’t strictly need to implement our own __rich_repr__. The following code would generate the same repr:
import rich.repr
@rich.repr.auto
class Bird:
def __init__(self, name, eats=None, fly=True, extinct=False):
self.name = name
self.eats = list(eats) if eats else []
self.fly = fly
self.extinct = extinct
BIRDS = {
"gull": Bird("gull", eats=["fish", "chips", "ice cream", "sausage rolls"]),
"penguin": Bird("penguin", eats=["fish"], fly=False),
"dodo": Bird("dodo", eats=["fruit"], fly=False, extinct=True)
}
from rich import print
print(BIRDS)
Note that the decorator will also create a __repr__, so you will get an auto-generated repr even if you don’t print with
Rich.
If you want to auto-generate the angular type of repr, then set angular=True on the decorator:
@rich.repr.auto(angular=True)
class Bird:
def __init__(self, name, eats=None, fly=True, extinct=False):
self.name = name
self.eats = list(eats) if eats else []
self.fly = fly
self.extinct = extinct
7.4 Example
EIGHT
LOGGING HANDLER
Rich supplies a logging handler which will format and colorize text written by Python’s logging module.
Here’s an example of how to set up a rich logger:
import logging
from rich.logging import RichHandler
FORMAT = "%(message)s"
logging.basicConfig(
level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
)
log = logging.getLogger("rich")
log.info("Hello, World!")
Rich logs won’t render Console Markup in logging by default as most libraries won’t be aware of the need to escape
literal square brackets, but you can enable it by setting markup=True on the handler. Alternatively you can enable it
per log message by supplying the extra argument as follows:
The RichHandler class may be configured to use Rich’s Traceback class to format exceptions, which provides more
context than a built-in exception. To get beautiful exceptions in your logs set rich_tracebacks=True on the handler
constructor:
import logging
from rich.logging import RichHandler
logging.basicConfig(
level="NOTSET",
format="%(message)s",
datefmt="[%X]",
handlers=[RichHandler(rich_tracebacks=True)]
(continues on next page)
33
Rich, Release 13.6.0
log = logging.getLogger("rich")
try:
print(1 / 0)
except Exception:
log.exception("unable print!")
There are a number of other options you can use to configure logging output, see the RichHandler reference for details.
If you are working with a framework (click, django etc), you may only be interested in seeing the code from your own
application within the traceback. You can exclude framework code by setting the suppress argument on Traceback,
install, and Console.print_exception, which should be a list of modules or str paths.
Here’s how you would exclude click from Rich exceptions:
import click
import logging
from rich.logging import RichHandler
logging.basicConfig(
level="NOTSET",
format="%(message)s",
datefmt="[%X]",
handlers=[RichHandler(rich_tracebacks=True, tracebacks_suppress=[click])]
)
Suppressed frames will show the line and file only, without any code.
NINE
TRACEBACK
Rich can render Python tracebacks with syntax highlighting and formatting. Rich tracebacks are easier to read and
show more code than standard Python tracebacks.
To see an example of a Rich traceback, running the following command:
python -m rich.traceback
The print_exception() method will print a traceback for the current exception being handled. Here’s an example:
try:
do_something()
except Exception:
console.print_exception(show_locals=True)
The show_locals=True parameter causes Rich to display the value of local variables for each frame of the traceback.
See exception.py for a larger example.
Rich can be installed as the default traceback handler so that all uncaught exceptions will be rendered with highlighting.
Here’s how:
There are a few options to configure the traceback handler, see install() for details.
35
Rich, Release 13.6.0
In some cases you may want to have the traceback handler installed automatically without having to worry about
importing the code in your module. You can do that by modifying the sitecustomize.py in your virtual environment.
Typically it would be located in your virtual environment path, underneath the site-packages folder, something like this:
./.venv/lib/python3.9/site-packages/sitecustomize.py
In most cases this file will not exist. If it doesn’t exist, you can create it by:
$ touch .venv/lib/python3.9/site-packages/sitecustomize.py
At this point, the traceback will be installed for any code that is run within the virtual environment.
Note: If you plan on sharing your code, it is probably best to include the traceback install in your main entry point
module.
If you are working with a framework (click, django etc), you may only be interested in seeing the code from your own
application within the traceback. You can exclude framework code by setting the suppress argument on Traceback,
install, Console.print_exception, and RichHandler, which should be a list of modules or str paths.
Here’s how you would exclude click from Rich exceptions:
import click
from rich.traceback import install
install(suppress=[click])
Suppressed frames will show the line and file only, without any code.
A recursion error can generate very large tracebacks that take a while to render and contain a lot of repetitive frames.
Rich guards against this with a max_frames argument, which defaults to 100. If a traceback contains more than 100
frames then only the first 50, and last 50 will be shown. You can disable this feature by setting max_frames to 0.
Here’s an example of printing a recursive error:
def foo(n):
return bar(n)
36 Chapter 9. Traceback
Rich, Release 13.6.0
def bar(n):
return foo(n)
console = Console()
try:
foo(1)
except Exception:
console.print_exception(max_frames=20)
38 Chapter 9. Traceback
CHAPTER
TEN
PROMPT
Rich has a number of Prompt classes which ask a user for input and loop until a valid response is received (they all use
the Console API internally). Here’s a simple example:
The prompt may be given as a string (which may contain Console Markup and emoji code) or as a Text instance.
You can set a default value which will be returned if the user presses return without entering any text:
If you supply a list of choices, the prompt will loop until the user enters one of the choices:
In addition to Prompt which returns strings, you can also use IntPrompt which asks the user for an integer, and
FloatPrompt for floats.
The Confirm class is a specialized prompt which may be used to ask the user a simple yes / no question. Here’s an
example:
The Prompt class was designed to be customizable via inheritance. See prompt.py for examples.
To see some of the prompts in action, run the following command from the command line:
python -m rich.prompt
39
Rich, Release 13.6.0
ELEVEN
COLUMNS
Rich can render text or other Rich renderables in neat columns with the Columns class. To use, construct a Columns
instance with an iterable of renderables and print it to the Console.
The following example is a very basic clone of the ls command in OSX / Linux to list directory contents:
import os
import sys
if len(sys.argv) < 2:
print("Usage: python columns.py DIRECTORY")
else:
directory = os.listdir(sys.argv[1])
columns = Columns(directory, equal=True, expand=True)
print(columns)
See columns.py for an example which outputs columns containing more than just text.
41
Rich, Release 13.6.0
TWELVE
RENDER GROUPS
The Group class allows you to group several renderables together so they may be rendered in a context where only a
single renderable may be supplied. For instance, you might want to display several renderables within a Panel.
To render two panels within a third panel, you would construct a Group with the child renderables as positional argu-
ments then wrap the result in another Panel:
panel_group = Group(
Panel("Hello", style="on blue"),
Panel("World", style="on red"),
)
print(Panel(panel_group))
This pattern is nice when you know in advance what renderables will be in a group, but can get awkward if you have
a larger number of renderables, especially if they are dynamic. Rich provides a group() decorator to help with these
situations. The decorator builds a group from an iterator of renderables. The following is the equivalent of the previous
example using the decorator:
@group()
def get_panels():
yield Panel("Hello", style="on blue")
yield Panel("World", style="on red")
print(Panel(get_panels()))
43
Rich, Release 13.6.0
THIRTEEN
MARKDOWN
Rich can render Markdown to the console. To render markdown, construct a Markdown object then print it to the
console. Markdown is a great way of adding rich content to your command line applications. Here’s an example of
use:
MARKDOWN = """
# This is an h1
console = Console()
md = Markdown(MARKDOWN)
console.print(md)
Note that code blocks are rendered with full syntax highlighting!
You can also use the Markdown class from the command line. The following example displays a readme in the terminal:
Run the following to see the full list of arguments for the markdown command:
python -m rich.markdown -h
45
Rich, Release 13.6.0
FOURTEEN
PADDING
The Padding class may be used to add whitespace around text or other renderable. The following example will print
the word “Hello” with a padding of 1 character, so there will be a blank line above and below, and a space on the left
and right edges:
You can specify the padding on a more granular level by using a tuple of values rather than a single value. A tuple of
2 values sets the top/bottom and left/right padding, whereas a tuple of 4 values sets the padding for top, right, bottom,
and left sides. You may recognize this scheme if you are familiar with CSS.
For example, the following displays 2 blank lines above and below the text, and a padding of 4 spaces on the left and
right sides:
The Padding class can also accept a style argument which applies a style to the padding and contents, and an expand
switch which can be set to False to prevent the padding from extending to the full width of the terminal. Here’s an
example which demonstrates both these arguments:
Note that, as with all Rich renderables, you can use Padding in any context. For instance, if you want to emphasize an
item in a Table you could add a Padding object to a row with a padding of 1 and a style of “on red”.
47
Rich, Release 13.6.0
FIFTEEN
PANEL
To draw a border around text or other renderable, construct a Panel with the renderable as the first positional argument.
Here’s an example:
You can change the style of the panel by setting the box argument to the Panel constructor. See Box for a list of available
box styles.
Panels will extend to the full width of the terminal. You can make panel fit the content by setting expand=False on
the constructor, or by creating the Panel with fit(). For example:
The Panel constructor accepts a title argument which will draw a title on the top of the panel, as well as a subtitle
argument which will draw a subtitle on the bottom of the panel:
49
Rich, Release 13.6.0
SIXTEEN
PROGRESS DISPLAY
Rich can display continuously updated information regarding the progress of long running tasks / file copies etc. The
information displayed is configurable, the default will display a description of the ‘task’, a progress bar, percentage
complete, and estimated time remaining.
Rich progress display supports multiple tasks, each with a bar and progress information. You can use this to track
concurrent tasks where the work is happening in threads or processes.
To see how the progress display looks, try this from the command line:
python -m rich.progress
Note: Progress works with Jupyter notebooks, with the caveat that auto-refresh is disabled. You will need to explicitly
call refresh() or set refresh=True when calling update(). Or use the track() function which does a refresh
automatically on each loop.
For basic usage call the track() function, which accepts a sequence (such as a list or range object) and an optional
description of the job you are working on. The track function will yield values from the sequence and update the
progress information on each iteration. Here’s an example:
import time
from rich.progress import track
If you require multiple tasks in the display, or wish to configure the columns in the progress display, you can work
directly with the Progress class. Once you have constructed a Progress object, add task(s) with (add_task()) and
update progress with update().
The Progress class is designed to be used as a context manager which will start and stop the progress display automat-
ically.
Here’s a simple example:
51
Rich, Release 13.6.0
import time
The total value associated with a task is the number of steps that must be completed for the progress to reach 100%.
A step in this context is whatever makes sense for your application; it could be number of bytes of a file read, or number
of images processed, etc.
When you call add_task() you get back a Task ID. Use this ID to call update() whenever you have completed some
work, or any information has changed. Typically you will need to update completed every time you have completed a
step. You can do this by updated completed directly or by setting advance which will add to the current completed
value.
The update() method collects keyword arguments which are also associated with the task. Use this to supply any
additional information you would like to render in the progress display. The additional arguments are stored in task.
fields and may be referenced in Column classes.
You can show or hide tasks by updating the tasks visible value. Tasks are visible by default, but you can also add an
invisible task by calling add_task() with visible=False.
Normally when you exit the progress context manager (or call stop()) the last refreshed display remains in the ter-
minal with the cursor on the following line. You can also make the progress display disappear on exit by setting
transient=True on the Progress constructor. Here’s an example:
Transient progress displays are useful if you want more minimal output in the terminal when tasks are complete.
When you add a task it is automatically started, which means it will show a progress bar at 0% and the time remaining
will be calculated from the current time. This may not work well if there is a long delay before you can start updating
progress; you may need to wait for a response from a server or count files in a directory (for example). In these cases
you can call add_task() with start=False or total=None which will display a pulsing animation that lets the user
know something is working. This is known as an indeterminate progress bar. When you have the number of steps you
can call start_task() which will display the progress bar at 0%, then update() as normal.
By default, the progress information will refresh 10 times a second. You can set the refresh rate with the
refresh_per_second argument on the Progress constructor. You should set this to something lower than 10 if
you know your updates will not be that frequent.
You might want to disable auto-refresh entirely if your updates are not very frequent, which you can do by setting
auto_refresh=False on the constructor. If you disable auto-refresh you will need to call refresh() manually after
updating your task(s).
16.2.6 Expand
The progress bar(s) will use only as much of the width of the terminal as required to show the task information. If you
set the expand argument on the Progress constructor, then Rich will stretch the progress display to the full available
width.
16.2.7 Columns
You may customize the columns in the progress display with the positional arguments to the Progress constructor.
The columns are specified as either a format string or a ProgressColumn object.
Format strings will be rendered with a single value “task” which will be a Task instance. For example "{task.
description}" would display the task description in the column, and "{task.completed} of {task.total}"
would display how many of the total steps have been completed. Additional fields passed via keyword arguments to
~rich.progress.Progress.update are store in task.fields. You can add them to a format string with the following
syntax: "extra info: {task.fields[extra]}".
The default columns are equivalent to the following:
progress = Progress(
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TaskProgressColumn(),
TimeRemainingColumn(),
)
To create a Progress with your own columns in addition to the defaults, use get_default_columns():
progress = Progress(
SpinnerColumn(),
*Progress.get_default_columns(),
TimeElapsedColumn(),
)
Rich builds a Table for the tasks in the Progress instance. You can customize how the columns of this tasks table are
created by specifying the table_column argument in the Column constructor, which should be a Column instance.
The following example demonstrates a progress bar where the description takes one third of the width of the terminal,
and the bar takes up the remaining two thirds:
with progress:
for n in progress.track(range(100)):
progress.print(n)
sleep(0.1)
The Progress class will create an internal Console object which you can access via progress.console. If you print
or log to this console, the output will be displayed above the progress display. Here’s an example:
If you have another Console object you want to use, pass it in to the Progress constructor. Here’s an example:
To avoid breaking the progress display visuals, Rich will redirect stdout and stderr so that you can use the
built-in print statement. This feature is enabled by default, but you can disable by setting redirect_stdout or
redirect_stderr to False
16.2.11 Customizing
If the Progress class doesn’t offer exactly what you need in terms of a progress display, you can override the
get_renderables method. For example, the following class will render a Panel around the progress display:
class MyProgress(Progress):
def get_renderables(self):
yield Panel(self.make_tasks_table(self.tasks))
Rich provides an easy way to generate a progress bar while reading a file. If you call open() it will return a context
manager which displays a progress bar while you read. This is particularly useful when you can’t easily modify the
code that does the reading.
The following example demonstrates how we might show progress when reading a JSON file:
import json
import rich.progress
If you already have a file object, you can call wrap_file() which returns a context manager that wraps your file so
that it displays a progress bar. If you use this function you will need to set the number of bytes or characters you expect
to read.
Here’s an example that reads a url from the internet:
response = urlopen("https://www.textualize.io")
size = int(response.headers["Content-Length"])
If you expect to be reading from multiple files, you can use open() or wrap_file() to add a file progress to an existing
Progress instance.
See cp_progress.py <https://github.com/willmcgugan/rich/blob/master/examples/cp_progress.py> for a minimal clone
of the cp command which shows a progress bar as the file is copied.
You can’t have different columns per task with a single Progress instance. However, you can have as many Progress
instances as you like in a Live Display. See live_progress.py and dynamic_progress.py for examples of using multiple
Progress instances.
16.4 Example
See downloader.py for a realistic application of a progress display. This script can download multiple concurrent files
with a progress bar, transfer speed and file size.
SEVENTEEN
SYNTAX
Rich can syntax highlight various programming languages with line numbers.
To syntax highlight code, construct a Syntax object and print it to the console. Here’s an example:
console = Console()
with open("syntax.py", "rt") as code_file:
syntax = Syntax(code_file.read(), "python")
console.print(syntax)
You may also use the from_path() alternative constructor which will load the code from disk and auto-detect the file
type. The example above could be re-written as follows:
console = Console()
syntax = Syntax.from_path("syntax.py")
console.print(syntax)
If you set line_numbers=True, Rich will render a column for line numbers:
17.2 Theme
The Syntax constructor (and from_path()) accept a theme attribute which should be the name of a Pygments theme. It
may also be one of the special case theme names “ansi_dark” or “ansi_light” which will use the color theme configured
by the terminal.
57
Rich, Release 13.6.0
You can override the background color from the theme by supplying a background_color argument to the constructor.
This should be a string in the same format a style definition accepts, e.g. “red”, “#ff0000”, “rgb(255,0,0)” etc. You
may also set the special value “default” which will use the default background color set in the terminal.
You can use this class from the command line. Here’s how you would syntax highlight a file called “syntax.py”:
python -m rich.syntax -h
EIGHTEEN
TABLES
Rich’s Table class offers a variety of ways to render tabular data to the terminal.
To render a table, construct a Table object, add columns with add_column(), and rows with add_row() – then print
it to the console.
Here’s an example:
console = Console()
console.print(table)
Note: You are not limited to adding text in the add_row method. You can add anything that Rich knows how to render
(including another table).
59
Rich, Release 13.6.0
There are a number of keyword arguments on the Table constructor you can use to define how a table should look.
• title Sets the title of the table (text show above the table).
• caption Sets the table caption (text show below the table).
• width Sets the desired width of the table (disables automatic width calculation).
• min_width Sets a minimum width for the table.
• box Sets one of the Box styles for the table grid, or None for no grid.
• safe_box Set to True to force the table to generate ASCII characters rather than unicode.
• padding An integer, or tuple of 1, 2, or 4 values to set the padding on cells.
• collapse_padding If True the padding of neighboring cells will be merged.
• pad_edge Set to False to remove padding around the edge of the table.
• expand Set to True to expand the table to the full available size.
• show_header Set to True to show a header, False to disable it.
• show_footer Set to True to show a footer, False to disable it.
• show_edge Set to False to disable the edge line around the table.
• show_lines Set to True to show lines between rows as well as header / footer.
• leading Additional space between rows.
• style A Style to apply to the entire table, e.g. “on blue”
• row_styles Set to a list of styles to style alternating rows. e.g. ["dim", ""] to create zebra stripes
• header_style Set the default style for the header.
• footer_style Set the default style for the footer.
• border_style Set a style for border characters.
• title_style Set a style for the title.
• caption_style Set a style for the caption.
• title_justify Set the title justify method (“left”, “right”, “center”, or “full”)
• caption_justify Set the caption justify method (“left”, “right”, “center”, or “full”)
• highlight Set to True to enable automatic highlighting of cell contents.
You can set the border style by importing one of the preset Box objects and setting the box argument in the table
constructor. Here’s an example that modifies the look of the Star Wars table:
18.3 Lines
By default, Tables will show a line under the header only. If you want to show lines between all rows add
show_lines=True to the constructor.
You can also force a line on the next row by setting end_section=True on the call to add_row(), or by calling the
add_section() to add a line between the current and subsequent rows.
Printing a table with no columns results in a blank line. If you are building a table dynamically and the data source has
no columns, you might want to print something different. Here’s how you might do that:
if table.columns:
print(table)
else:
print("[i]No data...[/i]")
You may also add columns by specifying them in the positional arguments of the Table constructor. For example, we
could construct a table with three columns like this:
This allows you to specify the text of the column only. If you want to set other attributes, such as width and style, you
can add a Column class. Here’s an example:
18.3. Lines 61
Rich, Release 13.6.0
There are a number of options you can set on a column to modify how it will look.
• header_style Sets the style of the header, e.g. “bold magenta”.
• footer_style Sets the style of the footer.
• style Sets a style that applies to the column. You could use this to highlight a column by setting the background
with “on green” for example.
• justify Sets the text justify to one of “left”, “center”, “right”, or “full”.
• vertical Sets the vertical alignment of the cells in a column, to one of “top”, “middle”, or “bottom”.
• width Explicitly set the width of a row to a given number of characters (disables automatic calculation).
• min_width When set to an integer will prevent the column from shrinking below this amount.
• max_width When set to an integer will prevent the column from growing beyond this amount.
• ratio Defines a ratio to set the column width. For instance, if there are 3 columns with a total of 6 ratio, and
ratio=2 then the column will be a third of the available size.
• no_wrap Set to True to prevent this column from wrapping.
You can define the vertical alignment of a column by setting the vertical parameter of the column. You can also do
this per-cell by wrapping your text or renderable with a Align class:
table.add_row(Align("Title", vertical="middle"))
18.8 Grids
The Table class can also make a great layout tool. If you disable headers and borders you can use it to position content
within the terminal. The alternative constructor grid() can create such a table for you.
For instance, the following code displays two pieces of text aligned to both the left and right edges of the terminal on
a single line:
grid = Table.grid(expand=True)
grid.add_column()
grid.add_column(justify="right")
grid.add_row("Raising shields", "[bold magenta]COMPLETED [green]:heavy_check_mark:")
print(grid)
NINETEEN
TREE
Rich has a Tree class which can generate a tree view in the terminal. A tree view is a great way of presenting the
contents of a filesystem or any other hierarchical data. Each branch of the tree can have a label which may be text or
any other Rich renderable.
Run the following command to see a demonstration of a Rich tree:
python -m rich.tree
The following code creates and prints a tree with a simple text label:
With only a single Tree instance this will output nothing more than the text “Rich Tree”. Things get more interesting
when we call add() to add more branches to the Tree. The following code adds two more branches:
tree.add("foo")
tree.add("bar")
print(tree)
The tree will now have two branches connected to the original tree with guide lines.
When you call add() a new Tree instance is returned. You can use this instance to add more branches to, and build up
a more complex tree. Let’s add a few more levels to the tree:
baz_tree = tree.add("baz")
baz_tree.add("[red]Red").add("[green]Green").add("[blue]Blue")
print(tree)
63
Rich, Release 13.6.0
The Tree constructor and add() method allows you to specify a style argument which sets a style for the entire branch,
and guide_style which sets the style for the guide lines. These styles are inherited by the branches and will apply to
any sub-trees as well.
If you set guide_style to bold, Rich will select the thicker variations of unicode line characters. Similarly, if you
select the “underline2” style you will get double line style of unicode characters.
19.2 Examples
For a more practical demonstration, see tree.py which can generate a tree view of a directory in your hard drive.
TWENTY
LIVE DISPLAY
Progress bars and status indicators use a live display to animate parts of the terminal. You can build custom live displays
with the Live class.
For a demonstration of a live display, run the following command:
python -m rich.live
Note: If you see ellipsis “. . . ”, this indicates that the terminal is not tall enough to show the full table.
To create a live display, construct a Live object with a renderable and use it as a context manager. The live display will
persist for the duration of the context. You can update the renderable to update the display:
import time
table = Table()
table.add_column("Row ID")
table.add_column("Description")
table.add_column("Level")
65
Rich, Release 13.6.0
You can also change the renderable on-the-fly by calling the update() method. This may be useful if the information
you wish to display is too dynamic to generate by updating a single renderable. Here is an example:
import random
import time
You can opt to show a Live display in the “alternate screen” by setting screen=True on the constructor. This will
allow your live display to go full screen and restore the command prompt on exit.
You can use this feature in combination with Layout to display sophisticated terminal “applications”.
Normally when you exit live context manager (or call stop()) the last refreshed item remains in the terminal with the
cursor on the following line. You can also make the live display disappear on exit by setting transient=True on the
Live constructor.
By default, the live display will refresh 4 times a second. You can set the refresh rate with the refresh_per_second
argument on the Live constructor. You should set this to something lower than 4 if you know your updates will not be
that frequent or higher for a smoother feeling.
You might want to disable auto-refresh entirely if your updates are not very frequent, which you can do by setting
auto_refresh=False on the constructor. If you disable auto-refresh you will need to call refresh() manually or
update() with refresh=True.
By default, the live display will display ellipsis if the renderable is too large for the terminal. You can adjust this by
setting the vertical_overflow argument on the Live constructor.
• “crop” Show renderable up to the terminal height. The rest is hidden.
• “ellipsis” Similar to crop except last line of the terminal is replaced with “. . . ”. This is the default behavior.
• “visible” Will allow the whole renderable to be shown. Note that the display cannot be properly cleared in this
mode.
Note: Once the live display stops on a non-transient renderable, the last frame will render as visible since it doesn’t
have to be cleared.
The Live class will create an internal Console object which you can access via live.console. If you print or log to
this console, the output will be displayed above the live display. Here’s an example:
import time
table = Table()
table.add_column("Row ID")
table.add_column("Description")
table.add_column("Level")
If you have another Console object you want to use, pass it in to the Live constructor. Here’s an example:
Note: If you are passing in a file console, the live display only show the last item once the live context is left.
To avoid breaking the live display visuals, Rich will redirect stdout and stderr so that you can use the builtin print
statement. This feature is enabled by default, but you can disable by setting redirect_stdout or redirect_stderr
to False.
Note that only a single live context may be active at any one time. The following will raise a LiveError because status
also uses Live:
In practice this is rarely a problem because you can display any combination of renderables in a Live context.
20.8.2 Examples
TWENTYONE
LAYOUT
Rich offers a Layout class which can be used to divide the screen area in to parts, where each part may contain
independent content. It can be used with Live Display to create full-screen “applications” but may be used standalone.
To see an example of a Layout, run the following from the command line:
python -m rich.layout
layout = Layout()
print(layout)
This will draw a box the size of the terminal with some information regarding the layout. The box is a “placeholder”
because we have yet to add any content to it. Before we do that, let’s create a more interesting layout by calling the
split_column() method to divide the layout in to two sub-layouts:
layout.split_column(
Layout(name="upper"),
Layout(name="lower")
)
print(layout)
This will divide the terminal screen in to two equal sized portions, one on top of the other. The name attribute is an
internal identifier we can use to look up the sub-layout later. Let’s use that to create another split, this time we will call
split_row() to split the lower layout in to a row of two sub-layouts:
layout["lower"].split_row(
Layout(name="left"),
Layout(name="right"),
)
print(layout)
You should now see the screen area divided in to 3 portions; an upper half and a lower half that is split in to two quarters.
You can continue to call split() in this way to create as many parts to the screen as you wish.
69
Rich, Release 13.6.0
The first position argument to Layout can be any Rich renderable, which will be sized to fit within the layout’s area.
Here’s how we might divide the “right” layout in to two panels:
layout["right"].split(
Layout(Panel("Hello")),
Layout(Panel("World!"))
)
You can also call update() to set or replace the current renderable:
layout["left"].update(
"The mystery of life isn't a problem to solve, but a reality to experience."
)
print(layout)
You can set a layout to use a fixed size by setting the size argument on the Layout constructor or by setting the attribute.
Here’s an example:
layout["upper"].size = 10
print(layout)
This will set the upper portion to be exactly 10 rows, no matter the size of the terminal. If the parent layout is horizontal
rather than vertical, then the size applies to the number of characters rather that rows.
21.4 Ratio
In addition to a fixed size, you can also make a flexible layout setting the ratio argument on the constructor or by
assigning to the attribute. The ratio defines how much of the screen the layout should occupy in relation to other
layouts. For example, let’s reset the size and set the ratio of the upper layout to 2:
layout["upper"].size = None
layout["upper"].ratio = 2
print(layout)
This makes the top layout take up two thirds of the space. This is because the default ratio is 1, giving the upper and
lower layouts a combined total of 3. As the upper layout has a ratio of 2, it takes up two thirds of the space, leaving the
remaining third for the lower layout.
A layout with a ratio set may also have a minimum size to prevent it from getting too small. For instance, here’s how
we could set the minimum size of the lower sub-layout so that it won’t shrink beyond 10 rows:
layout["lower"].minimum_size = 10
21.5 Visibility
You can make a layout invisible by setting the visible attribute to False. Here’s an example:
layout["upper"].visible = False
print(layout)
The top layout is now invisible, and the “lower” layout will expand to fill the available space. Set visible to True to
bring it back:
layout["upper"].visible = True
print(layout)
You could use this to toggle parts of your interface based on your application’s configuration.
21.6 Tree
To help visualize complex layouts you can print the tree attribute which will display a summary of the layout as a tree:
print(layout.tree)
21.7 Example
See fullscreen.py for an example that combines Layout and Live to create a fullscreen “application”.
21.5. Visibility 71
Rich, Release 13.6.0
TWENTYTWO
CONSOLE PROTOCOL
Rich supports a simple protocol to add rich formatting capabilities to custom objects, so you can print() your object
with color, styles and formatting.
Use this for presentation or to display additional debugging information that might be hard to parse from a typical
__repr__ string.
The easiest way to customize console output for your object is to implement a __rich__ method. This method accepts
no arguments, and should return an object that Rich knows how to render, such as a Text or Table. If you return a
plain string it will be rendered as Console Markup. Here’s an example:
class MyObject:
def __rich__(self) -> str:
return "[bold cyan]MyObject()"
If you were to print or log an instance of MyObject it would render as MyObject() in bold cyan. Naturally, you would
want to put this to better use, perhaps by adding specialized syntax highlighting.
The __rich__ method is limited to a single renderable object. For more advanced rendering, add a
__rich_console__ method to your class.
The __rich_console__ method should accept a Console and a ConsoleOptions instance. It should return an
iterable of other renderable objects. Although that means it could return a container such as a list, it generally easier
implemented by using the yield statement (making the method a generator).
Here’s an example of a __rich_console__ method:
@dataclass
class Student:
id: int
name: str
age: int
(continues on next page)
73
Rich, Release 13.6.0
If you were to print a Student instance, it would render a simple table to the terminal.
For complete control over how a custom object is rendered to the terminal, you can yield Segment objects. A Segment
consists of a piece of text and an optional Style. The following example writes multi-colored text when rendering a
MyObject instance:
class MyObject:
def __rich_console__(self, console: Console, options: ConsoleOptions) ->␣
˓→RenderResult:
Sometimes Rich needs to know how many characters an object will take up when rendering. The Table class, for
instance, will use this information to calculate the optimal dimensions for the columns. If you aren’t using one of the
renderable objects in the Rich module, you will need to supply a __rich_measure__ method which accepts a Console
and ConsoleOptions and returns a Measurement object. The Measurement object should contain the minimum and
maximum number of characters required to render.
For example, if we are rendering a chess board, it would require a minimum of 8 characters to render. The maximum
can be left as the maximum available width (assuming a centered board):
class ChessBoard:
def __rich_measure__(self, console: Console, options: ConsoleOptions) -> Measurement:
return Measurement(8, options.max_width)
TWENTYTHREE
REFERENCE
23.1 rich.align
75
Rich, Release 13.6.0
23.2 rich.bar
23.3 rich.color
23.2. rich.bar 77
Rich, Release 13.6.0
Returns
A new Color instance.
Return type
Color
classmethod from_rgb(red, green, blue)
Create a truecolor from three color components in the range(0->255).
Parameters
• red (float) – Red component in range 0-255.
• green (float) – Green component in range 0-255.
• blue (float) – Blue component in range 0-255.
Returns
A new color object.
Return type
Color
classmethod from_triplet(triplet)
Create a truecolor RGB color from a triplet of values.
Parameters
triplet (ColorTriplet) – A color triplet containing red, green and blue components.
Returns
A new color object.
Return type
Color
get_ansi_codes(foreground=True)
Get the ANSI escape codes for this color.
Parameters
foreground (bool) –
Return type
Tuple[str, . . . ]
get_truecolor(theme=None, foreground=True)
Get an equivalent color triplet for this color.
Parameters
• theme (TerminalTheme, optional) – Optional terminal theme, or None to use default.
Defaults to None.
• foreground (bool, optional) – True for a foreground color, or False for background.
Defaults to True.
Returns
A color triplet containing RGB components.
Return type
ColorTriplet
property is_default: bool
Check if the color is a default color.
23.3. rich.color 79
Rich, Release 13.6.0
23.4 rich.columns
23.5 rich.console
class rich.console.Capture(console)
Context manager to capture the result of printing to the console. See capture() for how to use.
Parameters
console (Console) – A console instance to capture output.
get()
Get the result of the capture.
Return type
str
exception rich.console.CaptureError
An error in the Capture context manager.
23.5. rich.console 81
Rich, Release 13.6.0
• log_path (bool, optional) – Boolean to enable the logging of the caller by log(). De-
faults to True.
• log_time_format (Union[str, TimeFormatterCallable], optional) – If
log_time is enabled, either string for strftime or callable that formats the time. Defaults to
“[%X] “.
• highlighter (HighlighterType, optional) – Default highlighter.
• legacy_windows (bool, optional) – Enable legacy Windows mode, or None to auto
detect. Defaults to None.
• safe_box (bool, optional) – Restrict box options that don’t render on legacy Windows.
• get_datetime (Callable[[], datetime], optional) – Callable that gets the current
time as a datetime.datetime object (used by Console.log), or None for datetime.now.
• get_time (Callable[[], time], optional) – Callable that gets the current time in
seconds, default uses time.monotonic.
• _environ (Mapping[str, str]) –
begin_capture()
Begin capturing console output. Call end_capture() to exit capture mode and return output.
Return type
None
bell()
Play a ‘bell’ sound (if supported by the terminal).
Return type
None
capture()
A context manager to capture the result of print() or log() in a string, rather than writing it to the console.
Example
Returns
Context manager with disables writing to the terminal.
Return type
Capture
clear(home=True)
Clear the screen.
Parameters
home (bool, optional) – Also move the cursor to ‘home’ position. Defaults to True.
Return type
None
clear_live()
Clear the Live instance.
Return type
None
property color_system: Optional[str]
Get color system string.
Returns
“standard”, “256” or “truecolor”.
Return type
Optional[str]
control(*control)
Insert non-printing control codes.
Parameters
• control_codes (str) – Control codes, such as those that may move the cursor.
• control (Control) –
Return type
None
property encoding: str
Get the encoding of the console file, e.g. "utf-8".
Returns
A standard encoding string.
Return type
str
end_capture()
End capture mode and return captured string.
Returns
Console output.
Return type
str
export_html(*, theme=None, clear=True, code_format=None, inline_styles=False)
Generate HTML from console contents (requires record=True argument in constructor).
Parameters
• theme (TerminalTheme, optional) – TerminalTheme object containing console col-
ors.
• clear (bool, optional) – Clear record buffer after exporting. Defaults to True.
• code_format (str, optional) – Format string to render HTML. In addition to ‘{fore-
ground}’, ‘{background}’, and ‘{code}’, should contain ‘{stylesheet}’ if inline_styles is
False.
• inline_styles (bool, optional) – If True styles will be inlined in to spans, which
makes files larger but easier to cut and paste markup. If False, styles will be embedded in
a style tag. Defaults to False.
23.5. rich.console 83
Rich, Release 13.6.0
Returns
String containing console contents as HTML.
Return type
str
export_svg(*, title='Rich', theme=None, clear=True, code_format='<svg class="rich-terminal"
viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg">\n <!-- Generated with
Rich https://www.textualize.io -->\n <style>\n\n @font-face {{\n font-family: "Fira Code";\n src:
local("FiraCode-Regular"),\n
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2")
format("woff2"),\n
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff")
format("woff");\n font-style: normal;\n font-weight: 400;\n }}\n @font-face {{\n font-family:
"Fira Code";\n src: local("FiraCode-Bold"),\n
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2")
format("woff2"),\n
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff")
format("woff");\n font-style: bold;\n font-weight: 700;\n }}\n\n .{unique_id}-matrix {{\n
font-family: Fira Code, monospace;\n font-size: {char_height}px;\n line-height:
{line_height}px;\n font-variant-east-asian: full-width;\n }}\n\n .{unique_id}-title {{\n font-size:
18px;\n font-weight: bold;\n font-family: arial;\n }}\n\n {styles}\n </style>\n\n <defs>\n
<clipPath id="{unique_id}-clip-terminal">\n <rect x="0" y="0" width="{terminal_width}"
height="{terminal_height}" />\n </clipPath>\n {lines}\n </defs>\n\n {chrome}\n <g
transform="translate({terminal_x}, {terminal_y})"
clip-path="url(#{unique_id}-clip-terminal)">\n {backgrounds}\n <g
class="{unique_id}-matrix">\n {matrix}\n </g>\n </g>\n</svg>\n', font_aspect_ratio=0.61,
unique_id=None)
Generate an SVG from the console contents (requires record=True in Console constructor).
Parameters
• title (str, optional) – The title of the tab in the output image
• theme (TerminalTheme, optional) – The TerminalTheme object to use to style the
terminal
• clear (bool, optional) – Clear record buffer after exporting. Defaults to True
• code_format (str, optional) – Format string used to generate the SVG. Rich will
inject a number of variables into the string in order to form the final SVG output. The
default template used and the variables injected by Rich can be found by inspecting the
console.CONSOLE_SVG_FORMAT variable.
• font_aspect_ratio (float, optional) – The width to height ratio of the font used
in the code_format string. Defaults to 0.61, which is the width to height ratio of Fira
Code (the default font). If you aren’t specifying a different font inside code_format, you
probably don’t need this.
• unique_id (str, optional) – unique id that is used as the prefix for various elements
(CSS styles, node ids). If not set, this defaults to a computed value based on the recorded
content.
Return type
str
export_text(*, clear=True, styles=False)
Generate text from console contents (requires record=True argument in constructor).
Parameters
• clear (bool, optional) – Clear record buffer after exporting. Defaults to True.
• styles (bool, optional) – If True, ansi escape codes will be included. False for
plain text. Defaults to False.
Returns
String containing console contents.
Return type
str
property file: IO[str]
Get the file object to write to.
get_style(name, *, default=None)
Get a Style instance by its theme name or parse a definition.
Parameters
• name (str) – The name of a style or a style definition.
• default (Optional[Union[str, Style]]) –
Returns
A Style object.
Return type
Style
Raises
MissingStyle – If no style could be parsed from name.
property height: int
Get the height of the console.
Returns
The height (in lines) of the console.
Return type
int
input(prompt='', *, markup=True, emoji=True, password=False, stream=None)
Displays a prompt and waits for input from the user. The prompt may contain color / style.
It works in the same way as Python’s builtin input() function and provides elaborate line editing and
history features if Python’s builtin readline module is previously loaded.
Parameters
• prompt (Union[str, Text]) – Text to render in the prompt.
• markup (bool, optional) – Enable console markup (requires a str prompt). Defaults to
True.
• emoji (bool, optional) – Enable emoji (requires a str prompt). Defaults to True.
• password (bool) – (bool, optional): Hide typed text. Defaults to False.
• stream (Optional[TextIO]) – (TextIO, optional): Optional file to read input from
(rather than stdin). Defaults to None.
Returns
Text read from stdin.
23.5. rich.console 85
Rich, Release 13.6.0
Return type
str
property is_alt_screen: bool
Check if the alt screen was enabled.
Returns
True if the alt screen was enabled, otherwise False.
Return type
bool
property is_dumb_terminal: bool
Detect dumb terminal.
Returns
True if writing to a dumb terminal, otherwise False.
Return type
bool
property is_terminal: bool
Check if the console is writing to a terminal.
Returns
True if the console writing to a device capable of understanding terminal codes, otherwise
False.
Return type
bool
line(count=1)
Write new line(s).
Parameters
count (int, optional) – Number of new lines. Defaults to 1.
Return type
None
log(*objects, sep=' ', end='\n', style=None, justify=None, emoji=None, markup=None, highlight=None,
log_locals=False, _stack_offset=1)
Log rich content to the terminal.
Parameters
• objects (positional args) – Objects to log to the terminal.
• sep (str, optional) – String to write between print data. Defaults to ” “.
• end (str, optional) – String to write at end of print data. Defaults to “\n”.
• style (Union[str, Style], optional) – A style to apply to output. Defaults to None.
• justify (str, optional) – One of “left”, “right”, “center”, or “full”. Defaults to None.
• emoji (Optional[bool], optional) – Enable emoji code, or None to use console de-
fault. Defaults to None.
• markup (Optional[bool], optional) – Enable markup, or None to use console de-
fault. Defaults to None.
• highlight (Optional[bool], optional) – Enable automatic highlighting, or None to
use console default. Defaults to None.
• log_locals (bool, optional) – Boolean to enable logging of locals where log() was
called. Defaults to False.
• _stack_offset (int, optional) – Offset of caller from end of call stack. Defaults to
1.
Return type
None
measure(renderable, *, options=None)
Measure a renderable. Returns a Measurement object which contains information regarding the number
of characters required to print the renderable.
Parameters
• renderable (RenderableType) – Any renderable or string.
• options (Optional[ConsoleOptions], optional) – Options to use when measur-
ing, or None to use default options. Defaults to None.
Returns
A measurement of the renderable.
Return type
Measurement
property options: ConsoleOptions
Get default console options.
out(*objects, sep=' ', end='\n', style=None, highlight=None)
Output to the terminal. This is a low-level way of writing to the terminal which unlike print() won’t
pretty print, wrap text, or apply markup, but will optionally apply highlighting and a basic style.
Parameters
• sep (str, optional) – String to write between print data. Defaults to ” “.
• end (str, optional) – String to write at end of print data. Defaults to “\n”.
• style (Union[str, Style], optional) – A style to apply to output. Defaults to None.
• highlight (Optional[bool], optional) – Enable automatic highlighting, or None to
use console default. Defaults to None.
• objects (Any) –
Return type
None
pager(pager=None, styles=False, links=False)
A context manager to display anything printed within a “pager”. The pager application is defined by the
system and will typically support at least pressing a key to scroll.
Parameters
• pager (Pager, optional) – A pager object, or None to use SystemPager. Defaults to
None.
• styles (bool, optional) – Show styles in pager. Defaults to False.
• links (bool, optional) – Show links in pager. Defaults to False.
Return type
PagerContext
23.5. rich.console 87
Rich, Release 13.6.0
Example
Returns
A context manager.
Return type
PagerContext
Parameters
• pager (Optional[Pager]) –
• styles (bool) –
• links (bool) –
pop_render_hook()
Pop the last renderhook from the stack.
Return type
None
pop_theme()
Remove theme from top of stack, restoring previous theme.
Return type
None
print(*objects, sep=' ', end='\n', style=None, justify=None, overflow=None, no_wrap=None, emoji=None,
markup=None, highlight=None, width=None, height=None, crop=True, soft_wrap=None,
new_line_start=False)
Print to the console.
Parameters
• objects (positional args) – Objects to log to the terminal.
• sep (str, optional) – String to write between print data. Defaults to ” “.
• end (str, optional) – String to write at end of print data. Defaults to “\n”.
• style (Union[str, Style], optional) – A style to apply to output. Defaults to None.
• justify (str, optional) – Justify method: “default”, “left”, “right”, “center”, or
“full”. Defaults to None.
• overflow (str, optional) – Overflow method: “ignore”, “crop”, “fold”, or “ellipsis”.
Defaults to None.
• no_wrap (Optional[bool], optional) – Disable word wrapping. Defaults to None.
• emoji (Optional[bool], optional) – Enable emoji code, or None to use console de-
fault. Defaults to None.
• markup (Optional[bool], optional) – Enable markup, or None to use console de-
fault. Defaults to None.
23.5. rich.console 89
Rich, Release 13.6.0
• allow_nan (bool, optional) – Allow NaN and Infinity values. Defaults to True.
• default (Callable, optional) – A callable that converts values that can not be en-
coded in to something that can be JSON encoded. Defaults to None.
• sort_keys (bool, optional) – Sort dictionary keys. Defaults to False.
Return type
None
push_render_hook(hook)
Add a new render hook to the stack.
Parameters
hook (RenderHook) – Render hook instance.
Return type
None
push_theme(theme, *, inherit=True)
Push a new theme on to the top of the stack, replacing the styles from the previous theme. Generally
speaking, you should call use_theme() to get a context manager, rather than calling this method directly.
Parameters
• theme (Theme) – A theme instance.
• inherit (bool, optional) – Inherit existing styles. Defaults to True.
Return type
None
render(renderable, options=None)
Render an object in to an iterable of Segment instances.
This method contains the logic for rendering objects with the console protocol. You are unlikely to need to
use it directly, unless you are extending the library.
Parameters
• renderable (RenderableType) – An object supporting the console protocol, or an object
that may be converted to a string.
• options (ConsoleOptions, optional) – An options object, or None to use
self.options. Defaults to None.
Returns
An iterable of segments that may be rendered.
Return type
Iterable[Segment]
render_lines(renderable, options=None, *, style=None, pad=True, new_lines=False)
Render objects in to a list of lines.
The output of render_lines is useful when further formatting of rendered console text is required,
such as the Panel class which draws a border around any renderable object.
Args:
renderable (RenderableType): Any object renderable in the console. options (Op-
tional[ConsoleOptions], optional): Console options, or None to use self.options. Default
to None. style (Style, optional): Optional style to apply to renderables. Defaults to None.
pad (bool, optional): Pad lines shorter than render width. Defaults to True. new_lines (bool,
optional): Include “
Parameters
• renderable (Union[ConsoleRenderable, RichCast, str]) –
• options (Optional[ConsoleOptions]) –
• style (Optional[Style]) –
• pad (bool) –
• new_lines (bool) –
Return type
List[List[Segment]]
23.5. rich.console 91
Rich, Release 13.6.0
Return type
None
save_html(path, *, theme=None, clear=True, code_format='<!DOCTYPE
html>\n<html>\n<head>\n<meta charset="UTF-8">\n<style>\n{stylesheet}\nbody {{\n color:
{foreground};\n background-color: {background};\n}}\n</style>\n</head>\n<body>\n <pre
style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier
New\',monospace"><code>{code}</code></pre>\n</body>\n</html>\n', inline_styles=False)
Generate HTML from console contents and write to a file (requires record=True argument in constructor).
Parameters
• path (str) – Path to write html file.
• theme (TerminalTheme, optional) – TerminalTheme object containing console col-
ors.
• clear (bool, optional) – Clear record buffer after exporting. Defaults to True.
• code_format (str, optional) – Format string to render HTML. In addition to ‘{fore-
ground}’, ‘{background}’, and ‘{code}’, should contain ‘{stylesheet}’ if inline_styles is
False.
• inline_styles (bool, optional) – If True styles will be inlined in to spans, which
makes files larger but easier to cut and paste markup. If False, styles will be embedded in
a style tag. Defaults to False.
Return type
None
save_svg(path, *, title='Rich', theme=None, clear=True, code_format='<svg class="rich-terminal"
viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg">\n <!-- Generated with
Rich https://www.textualize.io -->\n <style>\n\n @font-face {{\n font-family: "Fira Code";\n src:
local("FiraCode-Regular"),\n
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2")
format("woff2"),\n
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff")
format("woff");\n font-style: normal;\n font-weight: 400;\n }}\n @font-face {{\n font-family: "Fira
Code";\n src: local("FiraCode-Bold"),\n
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2")
format("woff2"),\n
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff")
format("woff");\n font-style: bold;\n font-weight: 700;\n }}\n\n .{unique_id}-matrix {{\n
font-family: Fira Code, monospace;\n font-size: {char_height}px;\n line-height: {line_height}px;\n
font-variant-east-asian: full-width;\n }}\n\n .{unique_id}-title {{\n font-size: 18px;\n font-weight:
bold;\n font-family: arial;\n }}\n\n {styles}\n </style>\n\n <defs>\n <clipPath
id="{unique_id}-clip-terminal">\n <rect x="0" y="0" width="{terminal_width}"
height="{terminal_height}" />\n </clipPath>\n {lines}\n </defs>\n\n {chrome}\n <g
transform="translate({terminal_x}, {terminal_y})"
clip-path="url(#{unique_id}-clip-terminal)">\n {backgrounds}\n <g
class="{unique_id}-matrix">\n {matrix}\n </g>\n </g>\n</svg>\n', font_aspect_ratio=0.61,
unique_id=None)
Generate an SVG file from the console contents (requires record=True in Console constructor).
Parameters
• path (str) – The path to write the SVG to.
• title (str, optional) – The title of the tab in the output image
23.5. rich.console 93
Rich, Release 13.6.0
Return type
bool
set_live(live)
Set Live instance. Used by Live context manager.
Parameters
live (Live) – Live instance using this Console.
Raises
errors.LiveError – If this Console has a Live context currently active.
Return type
None
set_window_title(title)
Set the title of the console terminal window.
Warning: There is no means within Rich of “resetting” the window title to its previous value, meaning the
title you set will persist even after your application exits.
fish shell resets the window title before and after each command by default, negating this issue. Windows
Terminal and command prompt will also reset the title for you. Most other shells and terminals, however,
do not do this.
Some terminals may require configuration changes before you can set the title. Some terminals may not
support setting the title at all.
Other software (including the terminal itself, the shell, custom prompts, plugins, etc.) may also set the
terminal window title. This could result in whatever value you write using this method being overwritten.
Parameters
title (str) – The new title of the terminal window.
Returns
True if the control code to change the terminal title was
written, otherwise False. Note that a return value of True does not guarantee that the win-
dow title has actually changed, since the feature may be unsupported/disabled in some
terminals.
Return type
bool
show_cursor(show=True)
Show or hide the cursor.
Parameters
show (bool, optional) – Set visibility of the cursor.
Return type
bool
property size: ConsoleDimensions
Get the size of the console.
Returns
A named tuple containing the dimensions.
Return type
ConsoleDimensions
23.5. rich.console 95
Rich, Release 13.6.0
use_theme(theme, *, inherit=True)
Use a different theme for the duration of the context manager.
Parameters
• theme (Theme) – Theme instance to user.
• inherit (bool, optional) – Inherit existing console styles. Defaults to True.
Returns
[description]
Return type
ThemeContext
property width: int
Get the width of the console.
Returns
The width (in characters) of the console.
Return type
int
class rich.console.ConsoleDimensions(width, height)
Size of the terminal.
Parameters
• width (int) –
• height (int) –
property height
The height of the console in lines.
property width
The width of the console in ‘cells’.
class rich.console.ConsoleOptions(size, legacy_windows, min_width, max_width, is_terminal, encoding,
max_height, justify=None, overflow=None, no_wrap=False,
highlight=None, markup=None, height=None)
Options for __rich_console__ method.
Parameters
• size (ConsoleDimensions) –
• legacy_windows (bool) –
• min_width (int) –
• max_width (int) –
• is_terminal (bool) –
• encoding (str) –
• max_height (int) –
• justify (Optional[typing_extensions.Literal[default, left, center,
right, full]]) –
• overflow (Optional[typing_extensions.Literal[fold, crop, ellipsis,
ignore]]) –
• no_wrap (Optional[bool]) –
• highlight (Optional[bool]) –
• markup (Optional[bool]) –
• height (Optional[int]) –
property ascii_only: bool
Check if renderables should use ascii only.
copy()
Return a copy of the options.
Returns
a copy of self.
Return type
ConsoleOptions
encoding: str
Encoding of terminal.
highlight: Optional[bool] = None
Highlight override for render_str.
is_terminal: bool
True if the target is a terminal, otherwise False.
justify: Optional[typing_extensions.Literal[default, left, center, right, full]] =
None
Justify value override for renderable.
legacy_windows: bool
flag for legacy windows.
Type
legacy_windows
markup: Optional[bool] = None
Enable markup when rendering strings.
max_height: int
Height of container (starts as terminal)
max_width: int
Maximum width of renderable.
min_width: int
Minimum width of renderable.
no_wrap: Optional[bool] = False
Disable wrapping for text.
overflow: Optional[typing_extensions.Literal[fold, crop, ellipsis, ignore]] = None
Overflow value override for renderable.
reset_height()
Return a copy of the options with height set to None.
23.5. rich.console 97
Rich, Release 13.6.0
Returns
New console options instance.
Return type
~ConsoleOptions
size: ConsoleDimensions
Size of console.
update(*, width=<rich.console.NoChange object>, min_width=<rich.console.NoChange object>,
max_width=<rich.console.NoChange object>, justify=<rich.console.NoChange object>,
overflow=<rich.console.NoChange object>, no_wrap=<rich.console.NoChange object>,
highlight=<rich.console.NoChange object>, markup=<rich.console.NoChange object>,
height=<rich.console.NoChange object>)
Update values, return a copy.
Parameters
• width (Union[int, NoChange]) –
• min_width (Union[int, NoChange]) –
• max_width (Union[int, NoChange]) –
• justify (Union[typing_extensions.Literal[default, left, center,
right, full], None, NoChange]) –
• overflow (Union[typing_extensions.Literal[fold, crop, ellipsis,
ignore], None, NoChange]) –
• no_wrap (Union[bool, None, NoChange]) –
• highlight (Union[bool, None, NoChange]) –
• markup (Union[bool, None, NoChange]) –
• height (Union[int, None, NoChange]) –
Return type
ConsoleOptions
update_dimensions(width, height)
Update the width and height, and return a copy.
Parameters
• width (int) – New width (sets both min_width and max_width).
• height (int) – New height.
Returns
New console options instance.
Return type
~ConsoleOptions
update_height(height)
Update the height, and return a copy.
Parameters
height (int) – New height
Returns
New Console options instance.
Return type
~ConsoleOptions
update_width(width)
Update just the width, return a copy.
Parameters
width (int) – New width (sets both min_width and max_width)
Returns
New console options instance.
Return type
~ConsoleOptions
class rich.console.ConsoleRenderable(*args, **kwds)
An object that supports the console protocol.
class rich.console.ConsoleThreadLocals(theme_stack, buffer=<factory>, buffer_index=0)
Thread local values for Console context.
Parameters
• theme_stack (ThemeStack) –
• buffer (List[Segment]) –
• buffer_index (int) –
class rich.console.Group(*renderables, fit=True)
Takes a group of renderables and returns a renderable object that renders the group.
Parameters
• renderables (Iterable[RenderableType]) – An iterable of renderable objects.
• fit (bool, optional) – Fit dimension of group to contents, or fill available space. De-
faults to True.
class rich.console.NewLine(count=1)
A renderable to generate new line(s)
Parameters
count (int) –
class rich.console.PagerContext(console, pager=None, styles=False, links=False)
A context manager that ‘pages’ content. See pager() for usage.
Parameters
• console (Console) –
• pager (Optional[Pager]) –
• styles (bool) –
• links (bool) –
class rich.console.RenderHook
Provides hooks in to the render process.
23.5. rich.console 99
Rich, Release 13.6.0
abstract process_renderables(renderables)
Called with a list of objects to render.
This method can return a new list of renderables, or modify and return the same list.
Parameters
renderables (List[ConsoleRenderable]) – A number of renderable objects.
Returns
A replacement list of renderables.
Return type
List[ConsoleRenderable]
rich.console.RenderableType
A string or any object that may be rendered by Rich.
alias of Union[ConsoleRenderable, RichCast, str]
class rich.console.RichCast(*args, **kwds)
An object that may be ‘cast’ to a console renderable.
class rich.console.ScreenContext(console, hide_cursor, style='')
A context manager that enables an alternative screen. See screen() for usage.
Parameters
• console (Console) –
• hide_cursor (bool) –
• style (Union[str, Style]) –
update(*renderables, style=None)
Update the screen.
Parameters
• renderable (RenderableType, optional) – Optional renderable to replace current
renderable, or None for no change. Defaults to None.
• style (Optional[Union[str, Style]]) – (Style, optional): Replacement style, or
None for no change. Defaults to None.
• renderables (Union[ConsoleRenderable, RichCast, str]) –
Return type
None
class rich.console.ScreenUpdate(lines, x, y)
Render a list of lines at a given offset.
Parameters
• lines (List[List[Segment]]) –
• x (int) –
• y (int) –
class rich.console.ThemeContext(console, theme, inherit=True)
A context manager to use a temporary theme. See use_theme() for usage.
Parameters
• console (Console) –
• theme (Theme) –
• inherit (bool) –
rich.console.detect_legacy_windows()
Detect legacy Windows.
Return type
bool
rich.console.group(fit=True)
A decorator that turns an iterable of renderables in to a group.
Parameters
fit (bool, optional) – Fit dimension of group to contents, or fill available space. Defaults
to True.
Return type
Callable[[. . . ], Callable[[. . . ], Group]]
23.6 rich.emoji
Parameters
• name (str) –
• style (Union[str, Style]) –
• variant (Optional[typing_extensions.Literal[emoji, text]]) –
classmethod replace(text)
Replace emoji markup with corresponding unicode characters.
Parameters
text (str) – A string with emojis codes, e.g. “Hello :smiley:!”
Returns
A string with emoji codes replaces with actual emoji.
Return type
str
23.7 rich.highlighter
class rich.highlighter.Highlighter
Abstract base class for highlighters.
__call__(text)
Highlight a str or Text instance.
Parameters
text (Union[str, ~Text]) – Text to highlight.
Raises
TypeError – If not called with text or str.
Returns
A test instance with highlighting applied.
Return type
Text
abstract highlight(text)
Apply highlighting in place to text.
Parameters
text (~Text) – A text object highlight.
Return type
None
class rich.highlighter.ISO8601Highlighter
Highlights the ISO8601 date time strings. Regex reference: https://www.oreilly.com/library/view/
regular-expressions-cookbook/9781449327453/ch04s07.html
class rich.highlighter.JSONHighlighter
Highlights JSON
highlight(text)
Highlight rich.text.Text using regular expressions.
Parameters
text (~Text) – Text to highlighted.
Return type
None
class rich.highlighter.NullHighlighter
A highlighter object that doesn’t highlight.
May be used to disable highlighting entirely.
highlight(text)
Nothing to do
Parameters
text (Text) –
Return type
None
class rich.highlighter.RegexHighlighter
Applies highlighting from a list of regular expressions.
highlight(text)
Highlight rich.text.Text using regular expressions.
Parameters
text (~Text) – Text to highlighted.
Return type
None
class rich.highlighter.ReprHighlighter
Highlights the text typically produced from __repr__ methods.
23.8 rich
Parameters
• obj (Any) – An object to inspect.
• title (str, optional) – Title to display over inspect result, or None use type. Defaults
to None.
• help (bool, optional) – Show full help text rather than just first paragraph. Defaults to
False.
• methods (bool, optional) – Enable inspection of callables. Defaults to False.
• docs (bool, optional) – Also render doc strings. Defaults to True.
• private (bool, optional) – Show private attributes (beginning with underscore). De-
faults to False.
• dunder (bool, optional) – Show attributes starting with double underscore. Defaults to
False.
• sort (bool, optional) – Sort attributes alphabetically. Defaults to True.
• all (bool, optional) – Show all attributes. Defaults to False.
• value (bool, optional) – Pretty print value. Defaults to True.
• console (Optional[Console]) –
Return type
None
23.9 rich.json
23.10 rich.layout
class rich.layout.ColumnSplitter
Split a layout region in to columns.
divide(children, region)
Divide a region amongst several child layouts.
Parameters
• children (Sequence(Layout)) – A number of child layouts.
• region (Region) – A rectangular region to divide.
Return type
Iterable[Tuple[Layout, Region]]
get_tree_icon()
Get the icon (emoji) used in layout.tree
Return type
str
class rich.layout.Layout(renderable=None, *, name=None, size=None, minimum_size=1, ratio=1,
visible=True)
A renderable to divide a fixed height in to rows or columns.
Parameters
• renderable (RenderableType, optional) – Renderable content, or None for place-
holder. Defaults to None.
• name (str, optional) – Optional identifier for Layout. Defaults to None.
• size (int, optional) – Optional fixed size of layout. Defaults to None.
• minimum_size (int, optional) – Minimum size of layout. Defaults to 1.
• ratio (int, optional) – Optional ratio for flexible layout. Defaults to 1.
• visible (bool, optional) – Visibility of layout. Defaults to True.
add_split(*layouts)
Add a new layout(s) to existing split.
Parameters
*layouts (Union[Layout, RenderableType]) – Positional arguments should be render-
ables or (sub) Layout instances.
Return type
None
property children: List[Layout]
Gets (visible) layout children.
get(name)
Get a named layout, or None if it doesn’t exist.
Parameters
name (str) – Name of layout.
Returns
Layout instance or None if no layout was found.
Return type
Optional[Layout]
property map: Dict[Layout, LayoutRender]
Get a map of the last render.
refresh_screen(console, layout_name)
Refresh a sub-layout.
Parameters
• console (Console) – Console instance where Layout is to be rendered.
• layout_name (str) – Name of layout.
Return type
None
render(console, options)
Render the sub_layouts.
Parameters
• console (Console) – Console instance.
• options (ConsoleOptions) – Console options.
Returns
A dict that maps Layout on to a tuple of Region, lines
Return type
RenderMap
property renderable: Union[ConsoleRenderable, RichCast, str]
Layout renderable.
split(*layouts, splitter='column')
Split the layout in to multiple sub-layouts.
Parameters
• *layouts (Layout) – Positional arguments should be (sub) Layout instances.
• splitter (Union[Splitter, str]) – Splitter instance or name of splitter.
Return type
None
split_column(*layouts)
Split the layout in to a column (layouts stacked on top of each other).
Parameters
*layouts (Layout) – Positional arguments should be (sub) Layout instances.
Return type
None
split_row(*layouts)
Split the layout in to a row (layouts side by side).
Parameters
*layouts (Layout) – Positional arguments should be (sub) Layout instances.
Return type
None
property tree: Tree
Get a tree renderable to show layout structure.
unsplit()
Reset splits to initial state.
Return type
None
update(renderable)
Update renderable.
Parameters
renderable (RenderableType) – New renderable object.
Return type
None
exception rich.layout.LayoutError
Layout related error.
class rich.layout.LayoutRender(region, render)
An individual layout render.
Parameters
• region (Region) –
• render (List[List[Segment]]) –
property region
Alias for field number 0
property render
Alias for field number 1
exception rich.layout.NoSplitter
Requested splitter does not exist.
class rich.layout.RowSplitter
Split a layout region in to rows.
divide(children, region)
Divide a region amongst several child layouts.
Parameters
• children (Sequence(Layout)) – A number of child layouts.
• region (Region) – A rectangular region to divide.
Return type
Iterable[Tuple[Layout, Region]]
get_tree_icon()
Get the icon (emoji) used in layout.tree
Return type
str
class rich.layout.Splitter
Base class for a splitter.
abstract divide(children, region)
Divide a region amongst several child layouts.
Parameters
• children (Sequence(Layout)) – A number of child layouts.
• region (Region) – A rectangular region to divide.
Return type
Iterable[Tuple[Layout, Region]]
abstract get_tree_icon()
Get the icon (emoji) used in layout.tree
Return type
str
23.11 rich.live
process_renderables(renderables)
Process renderables to restore cursor and display progress.
Parameters
renderables (List[ConsoleRenderable]) –
Return type
List[ConsoleRenderable]
refresh()
Update the display of the Live Render.
Return type
None
property renderable: Union[ConsoleRenderable, RichCast, str]
Get the renderable that is being displayed
Returns
Displayed renderable.
Return type
RenderableType
start(refresh=False)
Start live rendering display.
Parameters
refresh (bool, optional) – Also refresh. Defaults to False.
Return type
None
stop()
Stop live rendering display.
Return type
None
update(renderable, *, refresh=False)
Update the renderable that is being displayed
Parameters
• renderable (RenderableType) – New renderable to use.
• refresh (bool, optional) – Refresh the display. Defaults to False.
Return type
None
23.12 rich.logging
Note: Be careful when enabling console markup in log messages if you have configured logging for libraries not
under your control. If a dependency writes messages containing square brackets, it may not produce the intended
output.
Parameters
• level (Union[int, str], optional) – Log level. Defaults to logging.NOTSET.
• console (Console, optional) – Optional console instance to write logs. Default will use a
global console instance writing to stdout.
• show_time (bool, optional) – Show a column for the time. Defaults to True.
• omit_repeated_times (bool, optional) – Omit repetition of the same time. Defaults
to True.
• show_level (bool, optional) – Show a column for the level. Defaults to True.
• show_path (bool, optional) – Show the path to the original log call. Defaults to True.
• enable_link_path (bool, optional) – Enable terminal link of path column to file. De-
faults to True.
• highlighter (Highlighter, optional) – Highlighter to style log messages, or None to
use ReprHighlighter. Defaults to None.
• markup (bool, optional) – Enable console markup in log messages. Defaults to False.
• rich_tracebacks (bool, optional) – Enable rich tracebacks with syntax highlighting
and formatting. Defaults to False.
• tracebacks_width (Optional[int], optional) – Number of characters used to render
tracebacks, or None for full width. Defaults to None.
• tracebacks_extra_lines (int, optional) – Additional lines of code to render trace-
backs, or None for full width. Defaults to None.
• tracebacks_theme (str, optional) – Override pygments theme used in traceback.
• tracebacks_word_wrap (bool, optional) – Enable word wrapping of long tracebacks
lines. Defaults to True.
• tracebacks_show_locals (bool, optional) – Enable display of locals in tracebacks.
Defaults to False.
HIGHLIGHTER_CLASS
alias of ReprHighlighter
emit(record)
Invoked by logging.
Parameters
record (LogRecord) –
Return type
None
get_level_text(record)
Get the level name from the record.
Parameters
record (LogRecord) – LogRecord instance.
Returns
A tuple of the style and level name.
Return type
Text
render(*, record, traceback, message_renderable)
Render log for display.
Parameters
• record (LogRecord) – logging Record.
• traceback (Optional[Traceback]) – Traceback instance or None for no Traceback.
• message_renderable (ConsoleRenderable) – Renderable (typically Text) containing
log message contents.
Returns
Renderable to display log.
Return type
ConsoleRenderable
render_message(record, message)
Render message text in to Text.
Parameters
23.13 rich.markdown
class rich.markdown.BlockQuote
A block quote.
on_child_close(context, child)
Called when a child element is closed.
This method allows a parent element to take over rendering of its children.
Parameters
• context (MarkdownContext) – The markdown context.
• child (MarkdownElement) – The child markdown element.
Returns
Return True to render the element, or False to not render the element.
Return type
bool
class rich.markdown.CodeBlock(lexer_name, theme)
A code block with syntax highlighting.
Parameters
• lexer_name (str) –
• theme (str) –
classmethod create(markdown, token)
Factory to create markdown element,
Parameters
• markdown (Markdown) – The parent Markdown object.
• token (Token) – A node from markdown-it.
Returns
A new markdown element
Return type
MarkdownElement
class rich.markdown.Heading(tag)
A heading.
Parameters
tag (str) –
Parameters
• text (str) –
• href (str) –
classmethod create(markdown, token)
Factory to create markdown element,
Parameters
• markdown (Markdown) – The parent Markdown object.
• token (Token) – A node from markdown-it.
Returns
A new markdown element
Return type
MarkdownElement
class rich.markdown.ListElement(list_type, list_start)
A list element.
Parameters
• list_type (str) –
• list_start (int | None) –
classmethod create(markdown, token)
Factory to create markdown element,
Parameters
• markdown (Markdown) – The parent Markdown object.
• token (Token) – A node from markdown-it.
Returns
A new markdown element
Return type
MarkdownElement
on_child_close(context, child)
Called when a child element is closed.
This method allows a parent element to take over rendering of its children.
Parameters
• context (MarkdownContext) – The markdown context.
• child (MarkdownElement) – The child markdown element.
Returns
Return True to render the element, or False to not render the element.
Return type
bool
class rich.markdown.ListItem
An item in a list.
on_child_close(context, child)
Called when a child element is closed.
This method allows a parent element to take over rendering of its children.
Parameters
• context (MarkdownContext) – The markdown context.
• child (MarkdownElement) – The child markdown element.
Returns
Return True to render the element, or False to not render the element.
Return type
bool
class rich.markdown.Markdown(markup, code_theme='monokai', justify=None, style='none', hyperlinks=True,
inline_code_lexer=None, inline_code_theme=None)
A Markdown renderable.
Parameters
• markup (str) – A string containing markdown.
• code_theme (str, optional) – Pygments theme for code blocks. Defaults to “monokai”.
• justify (JustifyMethod, optional) – Justify value for paragraphs. Defaults to None.
• style (Union[str, Style], optional) – Optional style to apply to markdown.
• hyperlinks (bool, optional) – Enable hyperlinks. Defaults to True.
• inline_code_lexer (Optional[str]) – (str, optional): Lexer to use if inline code high-
lighting is enabled. Defaults to None.
• inline_code_theme (Optional[str]) – (Optional[str], optional): Pygments theme for
inline code highlighting, or None for no highlighting. Defaults to None.
class rich.markdown.MarkdownContext(console, options, style, inline_code_lexer=None,
inline_code_theme='monokai')
Manages the console render state.
Parameters
• console (Console) –
• options (ConsoleOptions) –
• style (Style) –
• inline_code_lexer (Optional[str]) –
• inline_code_theme (str) –
property current_style: Style
Current style which is the product of all styles on the stack.
enter_style(style_name)
Enter a style context.
Parameters
style_name (Union[str, Style]) –
Return type
Style
leave_style()
Leave a style context.
Return type
Style
on_text(text, node_type)
Called when the parser visits text.
Parameters
• text (str) –
• node_type (str) –
Return type
None
class rich.markdown.Paragraph(justify)
A Paragraph.
Parameters
justify (typing_extensions.Literal[default, left, center, right, full]) –
classmethod create(markdown, token)
Factory to create markdown element,
Parameters
• markdown (Markdown) – The parent Markdown object.
• token (Token) – A node from markdown-it.
Returns
A new markdown element
Return type
MarkdownElement
class rich.markdown.TableBodyElement
MarkdownElement corresponding to tbody_open and tbody_close.
on_child_close(context, child)
Called when a child element is closed.
This method allows a parent element to take over rendering of its children.
Parameters
• context (MarkdownContext) – The markdown context.
• child (MarkdownElement) – The child markdown element.
Returns
Return True to render the element, or False to not render the element.
Return type
bool
class rich.markdown.TableDataElement(justify)
MarkdownElement corresponding to td_open and td_close and th_open and th_close.
Parameters
justify (JustifyMethod) –
classmethod create(markdown, token)
Factory to create markdown element,
Parameters
• markdown (Markdown) – The parent Markdown object.
• token (Token) – A node from markdown-it.
Returns
A new markdown element
Return type
MarkdownElement
on_text(context, text)
Called when text is parsed.
Parameters
• context (MarkdownContext) – The markdown context.
• text (Union[str, Text]) –
Return type
None
class rich.markdown.TableElement
MarkdownElement corresponding to table_open.
on_child_close(context, child)
Called when a child element is closed.
This method allows a parent element to take over rendering of its children.
Parameters
• context (MarkdownContext) – The markdown context.
• child (MarkdownElement) – The child markdown element.
Returns
Return True to render the element, or False to not render the element.
Return type
bool
class rich.markdown.TableHeaderElement
MarkdownElement corresponding to thead_open and thead_close.
on_child_close(context, child)
Called when a child element is closed.
This method allows a parent element to take over rendering of its children.
Parameters
• context (MarkdownContext) – The markdown context.
on_child_close(context, child)
Called when a child element is closed.
This method allows a parent element to take over rendering of its children.
Parameters
• context (MarkdownContext) – The markdown context.
• child (MarkdownElement) – The child markdown element.
Returns
Return True to render the element, or False to not render the element.
Return type
bool
class rich.markdown.TextElement
Base class for elements that render text.
on_enter(context)
Called when the node is entered.
Parameters
context (MarkdownContext) – The markdown context.
Return type
None
on_leave(context)
Called when the parser leaves the element.
Parameters
context (MarkdownContext) – [description]
Return type
None
on_text(context, text)
Called when text is parsed.
Parameters
• context (MarkdownContext) – The markdown context.
• text (Union[str, Text]) –
Return type
None
class rich.markdown.UnknownElement
An unknown element.
Hopefully there will be no unknown elements, and we will have a MarkdownElement for everything in the
document.
23.14 rich.markup
23.15 rich.measure
with_maximum(width)
Get a RenderableWith where the widths are <= width.
Parameters
width (int) – Maximum desired width.
Returns
New Measurement object.
Return type
Measurement
with_minimum(width)
Get a RenderableWith where the widths are >= width.
Parameters
width (int) – Minimum desired width.
Returns
New Measurement object.
Return type
Measurement
rich.measure.measure_renderables(console, options, renderables)
Get a measurement that would fit a number of renderables.
Parameters
• console (Console) – Console instance.
• options (ConsoleOptions) – Console options.
• renderables (Iterable[RenderableType]) – One or more renderable objects.
Returns
Measurement object containing range of character widths required to
contain all given renderables.
Return type
Measurement
23.16 rich.padding
Example
Parameters
• renderable (RenderableType) – String or other renderable.
• pad (Union[int, Tuple[int]]) – Padding for top, right, bottom, and left borders. May
be specified with 1, 2, or 4 integers (CSS style).
23.17 rich.panel
Example
Parameters
• renderable (RenderableType) – A console renderable object.
• box (Box, optional) – A Box instance that defines the look of the border (see Box. De-
faults to box.ROUNDED.
• safe_box (bool, optional) – Disable box characters that don’t display on windows
legacy terminal with raster fonts. Defaults to True.
• expand (bool, optional) – If True the panel will stretch to fill the console width, other-
wise it will be sized to fit the contents. Defaults to True.
• style (str, optional) – The style of the panel (border and contents). Defaults to “none”.
• border_style (str, optional) – The style of the border. Defaults to “none”.
23.18 rich.pretty
• key_repr (str) –
• value_repr (str) –
• open_brace (str) –
• close_brace (str) –
• empty (str) –
• last (bool) –
• is_tuple (bool) –
• is_namedtuple (bool) –
• children (Optional[List[Node]]) –
• key_separator (str) –
• separator (str) –
check_length(start_length, max_length)
Check the length fits within a limit.
Parameters
• start_length (int) – Starting length of the line (indent, prefix, suffix).
• max_length (int) – Maximum length.
Returns
True if the node can be rendered within max length, otherwise False.
Return type
bool
iter_tokens()
Generate tokens for this node.
Return type
Iterable[str]
render(max_width=80, indent_size=4, expand_all=False)
Render the node to a pretty repr.
Parameters
• max_width (int, optional) – Maximum width of the repr. Defaults to 80.
• indent_size (int, optional) – Size of indents. Defaults to 4.
• expand_all (bool, optional) – Expand all levels. Defaults to False.
Returns
A repr string of the original object.
Return type
str
class rich.pretty.Pretty(_object, highlighter=None, *, indent_size=4, justify=None, overflow=None,
no_wrap=False, indent_guides=False, max_length=None, max_string=None,
max_depth=None, expand_all=False, margin=0, insert_line=False)
A rich renderable that pretty prints an object.
Parameters
rich.pretty.is_expandable(obj)
Check if an object may be expanded by pretty print.
Parameters
obj (Any) –
Return type
bool
rich.pretty.pprint(_object, *, console=None, indent_guides=True, max_length=None, max_string=None,
max_depth=None, expand_all=False)
A convenience function for pretty printing.
Parameters
• _object (Any) – Object to pretty print.
• console (Console, optional) – Console instance, or None to use default. Defaults to
None.
• max_length (int, optional) – Maximum length of containers before abbreviating, or
None for no abbreviation. Defaults to None.
• max_string (int, optional) – Maximum length of strings before truncating, or None to
disable. Defaults to None.
• max_depth (int, optional) – Maximum depth for nested data structures, or None for
unlimited depth. Defaults to None.
• indent_guides (bool, optional) – Enable indentation guides. Defaults to True.
• expand_all (bool, optional) – Expand all containers. Defaults to False.
Return type
None
rich.pretty.pretty_repr(_object, *, max_width=80, indent_size=4, max_length=None, max_string=None,
max_depth=None, expand_all=False)
Prettify repr string by expanding on to new lines to fit within a given width.
Parameters
• _object (Any) – Object to repr.
• max_width (int, optional) – Desired maximum width of repr string. Defaults to 80.
• indent_size (int, optional) – Number of spaces to indent. Defaults to 4.
• max_length (int, optional) – Maximum length of containers before abbreviating, or
None for no abbreviation. Defaults to None.
• max_string (int, optional) – Maximum length of string before truncating, or None to
disable truncating. Defaults to None.
• max_depth (int, optional) – Maximum depth of nested data structure, or None for no
depth. Defaults to None.
• expand_all (bool, optional) – Expand all containers regardless of available width. De-
faults to False.
Returns
A possibly multi-line representation of the object.
Return type
str
23.19 rich.progress_bar
update(completed, total=None)
Update progress with new values.
Parameters
• completed (float) – Number of steps completed.
• total (float, optional) – Total number of steps, or None to not change. Defaults to
None.
Return type
None
23.20 rich.progress
Return type
Text
class rich.progress.FileSizeColumn(table_column=None)
Renders completed filesize.
Parameters
table_column (Optional[Column]) –
render(task)
Show data completed.
Parameters
task (Task) –
Return type
Text
class rich.progress.MofNCompleteColumn(separator='/', table_column=None)
Renders completed count/total, e.g. ‘ 10/1000’.
Best for bounded tasks with int quantities.
Space pads the completed count so that progress length does not change as task progresses past powers of 10.
Parameters
• separator (str, optional) – Text to separate completed and total values. Defaults to
“/”.
• table_column (Optional[Column]) –
render(task)
Show completed/total.
Parameters
task (Task) –
Return type
Text
class rich.progress.Progress(*columns, console=None, auto_refresh=True, refresh_per_second=10,
speed_estimate_period=30.0, transient=False, redirect_stdout=True,
redirect_stderr=True, get_time=None, disable=False, expand=False)
Renders an auto-updating progress bar(s).
Parameters
• console (Console, optional) – Optional Console instance. Default will an internal Con-
sole instance writing to stdout.
• auto_refresh (bool, optional) – Enable auto refresh. If disabled, you will need to call
refresh().
• refresh_per_second (Optional[float], optional) – Number of times per second
to refresh the progress information or None to use default (10). Defaults to None.
• speed_estimate_period (float) – (float, optional): Period (in seconds) used to calculate
the speed estimate. Defaults to 30.
• transient (bool) – (bool, optional): Clear the progress on exit. Defaults to False.
• redirect_stdout (bool) – (bool, optional): Enable redirection of stdout, so print may
be used. Defaults to True.
You can also create a Progress instance using custom columns before and/or after the defaults, as in this
example:
progress = Progress(
SpinnerColumn(), *Progress.default_columns(), “Elapsed:”, TimeElapsedColumn(),
)
This code shows the creation of a Progress display, containing a spinner to the left, the default columns,
and a labeled elapsed time column.
Return type
Tuple[ProgressColumn, . . . ]
get_renderable()
Get a renderable for the progress display.
Return type
Union[ConsoleRenderable, RichCast, str]
get_renderables()
Get a number of renderables for the progress display.
Return type
Iterable[Union[ConsoleRenderable, RichCast, str]]
make_tasks_table(tasks)
Get a table to render the Progress display.
Parameters
tasks (Iterable[Task]) – An iterable of Task instances, one per row of the table.
Returns
A table instance.
Return type
Table
open(file: Union[str, PathLike[str], bytes], mode: typing_extensions.Literal[rb], buffering: int = -1,
encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None, *, total:
Optional[int] = None, task_id: Optional[TaskID] = None, description: str = 'Reading...') → BinaryIO
open(file: Union[str, PathLike[str], bytes], mode: Union[typing_extensions.Literal[r],
typing_extensions.Literal[rt]], buffering: int = -1, encoding: Optional[str] = None, errors:
Optional[str] = None, newline: Optional[str] = None, *, total: Optional[int] = None, task_id:
Optional[TaskID] = None, description: str = 'Reading...') → TextIO
Track progress while reading from a binary file.
Parameters
• path (Union[str, PathLike[str]]) – The path to the file to read.
• mode (str) – The mode to use to open the file. Only supports “r”, “rb” or “rt”.
• buffering (int) – The buffering strategy to use, see io.open().
• encoding (str, optional) – The encoding to use when reading in text mode, see io.
open().
• errors (str, optional) – The error handling strategy for decoding errors, see io.
open().
• newline (str, optional) – The strategy for handling newlines in text mode, see io.
open().
Parameters
task_id (TaskID) – ID of task.
Return type
None
stop()
Stop the progress display.
Return type
None
stop_task(task_id)
Stop a task.
This will freeze the elapsed time on the task.
Parameters
task_id (TaskID) – ID of task.
Return type
None
property task_ids: List[TaskID]
A list of task IDs.
property tasks: List[Task ]
Get a list of Task instances.
track(sequence, total=None, task_id=None, description='Working...', update_period=0.1)
Track progress by iterating over a sequence.
Parameters
• sequence (Sequence[ProgressType]) – A sequence of values you want to iterate over
and track progress.
• total (Optional[float]) – (float, optional): Total number of steps. Default is
len(sequence).
• task_id (Optional[TaskID]) – (TaskID): Task to track. Default is new task.
• description (str) – (str, optional): Description of task, if new task is created.
• update_period (float, optional) – Minimum time (in seconds) between calls to up-
date(). Defaults to 0.1.
Returns
An iterable of values taken from the provided sequence.
Return type
Iterable[ProgressType]
update(task_id, *, total=None, completed=None, advance=None, description=None, visible=None,
refresh=False, **fields)
Update information associated with a task.
Parameters
• task_id (TaskID) – Task id (returned by add_task).
• total (float, optional) – Updates task.total if not None.
• completed (float, optional) – Updates task.completed if not None.
property completed
Number of steps completed.
property timestamp
Timestamp of sample.
class rich.progress.RenderableColumn(renderable='', *, table_column=None)
A column to insert an arbitrary column.
Parameters
• renderable (RenderableType, optional) – Any renderable. Defaults to empty string.
• table_column (Optional[Column]) –
render(task)
Should return a renderable object.
Parameters
task (Task) –
Return type
Union[ConsoleRenderable, RichCast, str]
class rich.progress.SpinnerColumn(spinner_name='dots', style='progress.spinner', speed=1.0,
finished_text=' ', table_column=None)
A column with a ‘spinner’ animation.
Parameters
• spinner_name (str, optional) – Name of spinner animation. Defaults to “dots”.
• style (StyleType, optional) – Style of spinner. Defaults to “progress.spinner”.
• speed (float, optional) – Speed factor of spinner. Defaults to 1.0.
• finished_text (TextType, optional) – Text used when task is finished. Defaults to ”
“.
• table_column (Optional[Column]) –
render(task)
Should return a renderable object.
Parameters
task (Task) –
Return type
Union[ConsoleRenderable, RichCast, str]
set_spinner(spinner_name, spinner_style='progress.spinner', speed=1.0)
Set a new spinner.
Parameters
• spinner_name (str) – Spinner name, see python -m rich.spinner.
• spinner_style (Optional[StyleType], optional) – Spinner style. Defaults to
“progress.spinner”.
• speed (float, optional) – Speed factor of spinner. Defaults to 1.0.
Return type
None
• text_format (str) –
• style (Union[str, Style]) –
• justify (typing_extensions.Literal[default, left, center, right,
full]) –
• markup (bool) –
• highlighter (Optional[Highlighter]) –
• table_column (Optional[Column]) –
render(task)
Should return a renderable object.
Parameters
task (Task) –
Return type
Text
class rich.progress.TimeElapsedColumn(table_column=None)
Renders time elapsed.
Parameters
table_column (Optional[Column]) –
render(task)
Show time elapsed.
Parameters
task (Task) –
Return type
Text
class rich.progress.TimeRemainingColumn(compact=False, elapsed_when_finished=False,
table_column=None)
Renders estimated time remaining.
Parameters
• compact (bool, optional) – Render MM:SS when time remaining is less than an hour.
Defaults to False.
• elapsed_when_finished (bool, optional) – Render time elapsed when the task is fin-
ished. Defaults to False.
• table_column (Optional[Column]) –
render(task)
Show time remaining.
Parameters
task (Task) –
Return type
Text
class rich.progress.TotalFileSizeColumn(table_column=None)
Renders total filesize.
Parameters
table_column (Optional[Column]) –
render(task)
Show data completed.
Parameters
task (Task) –
Return type
Text
class rich.progress.TransferSpeedColumn(table_column=None)
Renders human readable transfer speed.
Parameters
table_column (Optional[Column]) –
render(task)
Show data transfer speed.
Parameters
task (Task) –
Return type
Text
rich.progress.open(file: Union[str, PathLike[str], bytes], mode: Union[typing_extensions.Literal[rt],
typing_extensions.Literal[r]], buffering: int = -1, encoding: Optional[str] = None, errors:
Optional[str] = None, newline: Optional[str] = None, *, total: Optional[int] = None,
description: str = 'Reading...', auto_refresh: bool = True, console: Optional[Console] =
None, transient: bool = False, get_time: Optional[Callable[[], float]] = None,
refresh_per_second: float = 10, style: Union[str, Style] = 'bar.back', complete_style:
Union[str, Style] = 'bar.complete', finished_style: Union[str, Style] = 'bar.finished',
pulse_style: Union[str, Style] = 'bar.pulse', disable: bool = False) →
AbstractContextManager[TextIO]
rich.progress.open(file: Union[str, PathLike[str], bytes], mode: typing_extensions.Literal[rb], buffering: int =
-1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] =
None, *, total: Optional[int] = None, description: str = 'Reading...', auto_refresh: bool =
True, console: Optional[Console] = None, transient: bool = False, get_time:
Optional[Callable[[], float]] = None, refresh_per_second: float = 10, style: Union[str,
Style] = 'bar.back', complete_style: Union[str, Style] = 'bar.complete', finished_style:
Union[str, Style] = 'bar.finished', pulse_style: Union[str, Style] = 'bar.pulse', disable: bool
= False) → AbstractContextManager[BinaryIO]
Read bytes from a file while tracking progress.
Parameters
• path (Union[str, PathLike[str], BinaryIO]) – The path to the file to read, or a
file-like object in binary mode.
• mode (str) – The mode to use to open the file. Only supports “r”, “rb” or “rt”.
• buffering (int) – The buffering strategy to use, see io.open().
• encoding (str, optional) – The encoding to use when reading in text mode, see io.
open().
• errors (str, optional) – The error handling strategy for decoding errors, see io.
open().
• newline (str, optional) – The strategy for handling newlines in text mode, see io.
open()
• total – (int, optional): Total number of bytes to read. Must be provided if reading from a
file handle. Default for a path is os.stat(file).st_size.
• description (str, optional) – Description of task show next to progress bar. Defaults
to “Reading”.
• auto_refresh (bool, optional) – Automatic refresh, disable to force a refresh after
each iteration. Default is True.
• transient – (bool, optional): Clear the progress on exit. Defaults to False.
• console (Console, optional) – Console to write to. Default creates internal Console
instance.
• refresh_per_second (float) – Number of times per second to refresh the progress in-
formation. Defaults to 10.
• style (StyleType, optional) – Style for the bar background. Defaults to “bar.back”.
• complete_style (StyleType, optional) – Style for the completed bar. Defaults to
“bar.complete”.
• finished_style (StyleType, optional) – Style for a finished bar. Defaults to
“bar.finished”.
• pulse_style (StyleType, optional) – Style for pulsing bars. Defaults to “bar.pulse”.
• disable (bool, optional) – Disable display of progress.
• encoding – The encoding to use when reading in text mode.
Returns
A context manager yielding a progress reader.
Return type
ContextManager[BinaryIO]
rich.progress.track(sequence, description='Working...', total=None, auto_refresh=True, console=None,
transient=False, get_time=None, refresh_per_second=10, style='bar.back',
complete_style='bar.complete', finished_style='bar.finished', pulse_style='bar.pulse',
update_period=0.1, disable=False, show_speed=True)
Track progress by iterating over a sequence.
Parameters
• sequence (Iterable[ProgressType]) – A sequence (must support “len”) you wish to
iterate over.
• description (str, optional) – Description of task show next to progress bar. Defaults
to “Working”.
• total (Optional[float]) – (float, optional): Total number of steps. Default is
len(sequence).
• auto_refresh (bool, optional) – Automatic refresh, disable to force a refresh after
each iteration. Default is True.
• transient (bool) – (bool, optional): Clear the progress on exit. Defaults to False.
• console (Console, optional) – Console to write to. Default creates internal Console
instance.
• refresh_per_second (float) – Number of times per second to refresh the progress in-
formation. Defaults to 10.
• style (StyleType, optional) – Style for the bar background. Defaults to “bar.back”.
• complete_style (StyleType, optional) – Style for the completed bar. Defaults to
“bar.complete”.
• finished_style (StyleType, optional) – Style for a finished bar. Defaults to
“bar.finished”.
• pulse_style (StyleType, optional) – Style for pulsing bars. Defaults to “bar.pulse”.
• update_period (float, optional) – Minimum time (in seconds) between calls to up-
date(). Defaults to 0.1.
• disable (bool, optional) – Disable display of progress.
• show_speed (bool, optional) – Show speed if total isn’t known. Defaults to True.
• get_time (Optional[Callable[[], float]]) –
Returns
An iterable of the values in the sequence.
Return type
Iterable[ProgressType]
rich.progress.wrap_file(file, total, *, description='Reading...', auto_refresh=True, console=None,
transient=False, get_time=None, refresh_per_second=10, style='bar.back',
complete_style='bar.complete', finished_style='bar.finished', pulse_style='bar.pulse',
disable=False)
Read bytes from a file while tracking progress.
Parameters
• file (Union[str, PathLike[str], BinaryIO]) – The path to the file to read, or a
file-like object in binary mode.
• total (int) – Total number of bytes to read.
• description (str, optional) – Description of task show next to progress bar. Defaults
to “Reading”.
• auto_refresh (bool, optional) – Automatic refresh, disable to force a refresh after
each iteration. Default is True.
• transient (bool) – (bool, optional): Clear the progress on exit. Defaults to False.
• console (Console, optional) – Console to write to. Default creates internal Console
instance.
• refresh_per_second (float) – Number of times per second to refresh the progress in-
formation. Defaults to 10.
• style (StyleType, optional) – Style for the bar background. Defaults to “bar.back”.
• complete_style (StyleType, optional) – Style for the completed bar. Defaults to
“bar.complete”.
• finished_style (StyleType, optional) – Style for a finished bar. Defaults to
“bar.finished”.
• pulse_style (StyleType, optional) – Style for pulsing bars. Defaults to “bar.pulse”.
• disable (bool, optional) – Disable display of progress.
23.21 rich.prompt
Example
>>> if Confirm.ask("Continue"):
run_job()
process_response(value)
Convert choices to a bool.
Parameters
value (str) –
Return type
bool
render_default(default)
Render the default as (y) or (n) rather than True/False.
Parameters
default (DefaultType) –
Return type
Text
response_type
alias of bool
class rich.prompt.FloatPrompt(prompt='', *, console=None, password=False, choices=None,
show_default=True, show_choices=True)
A prompt that returns a float.
Example
response_type
alias of float
class rich.prompt.IntPrompt(prompt='', *, console=None, password=False, choices=None,
show_default=True, show_choices=True)
A prompt that returns an integer.
Example
response_type
alias of int
exception rich.prompt.InvalidResponse(message)
Exception to indicate a response was invalid. Raise this within process_response() to indicate an error and provide
an error message.
Parameters
message (Union[str, Text]) – Error message.
Return type
None
class rich.prompt.Prompt(prompt='', *, console=None, password=False, choices=None, show_default=True,
show_choices=True)
A prompt that returns a str.
Example
response_type
alias of str
class rich.prompt.PromptBase(prompt='', *, console=None, password=False, choices=None,
show_default=True, show_choices=True)
Ask the user for input until a valid response is received. This is the base class, see one of the concrete classes for
examples.
Parameters
• prompt (TextType, optional) – Prompt text. Defaults to “”.
• console (Console, optional) – A Console instance or None to use global console. De-
faults to None.
• password (bool, optional) – Enable password input. Defaults to False.
• choices (List[str], optional) – A list of valid choices. Defaults to None.
• show_default (bool, optional) – Show default in prompt. Defaults to True.
• show_choices (bool, optional) – Show choices in prompt. Defaults to True.
classmethod ask(prompt: Union[str, Text] = '', *, console: Optional[Console] = None, password: bool =
False, choices: Optional[List[str]] = None, show_default: bool = True, show_choices:
bool = True, default: DefaultType, stream: Optional[TextIO] = None) →
Union[DefaultType, PromptType]
classmethod ask(prompt: Union[str, Text] = '', *, console: Optional[Console] = None, password: bool =
False, choices: Optional[List[str]] = None, show_default: bool = True, show_choices:
bool = True, stream: Optional[TextIO] = None) → PromptType
Shortcut to construct and run a prompt loop and return the result.
Example
Parameters
• prompt (TextType, optional) – Prompt text. Defaults to “”.
• console (Console, optional) – A Console instance or None to use global console.
Defaults to None.
• password (bool, optional) – Enable password input. Defaults to False.
• choices (List[str], optional) – A list of valid choices. Defaults to None.
• show_default (bool, optional) – Show default in prompt. Defaults to True.
• show_choices (bool, optional) – Show choices in prompt. Defaults to True.
• stream (TextIO, optional) – Optional text file open for reading to get input. Defaults
to None.
check_choice(value)
Check value is in the list of valid choices.
Parameters
value (str) – Value entered by user.
Returns
True if choice was valid, otherwise False.
Return type
bool
classmethod get_input(console, prompt, password, stream=None)
Get input from user.
Parameters
• console (Console) – Console instance.
• prompt (TextType) – Prompt text.
• password (bool) – Enable password entry.
• stream (Optional[TextIO]) –
Returns
String from user.
Return type
str
make_prompt(default)
Make prompt text.
Parameters
default (DefaultType) – Default value.
Returns
Text to display in prompt.
Return type
Text
on_validate_error(value, error)
Called to handle validation error.
Parameters
• value (str) – String entered by user.
• error (InvalidResponse) – Exception instance the initiated the error.
Return type
None
pre_prompt()
Hook to display something before the prompt.
Return type
None
process_response(value)
Process response from user, convert to prompt type.
Parameters
value (str) – String typed by user.
Raises
InvalidResponse – If value is invalid.
Returns
The value to be returned from ask method.
Return type
PromptType
render_default(default)
Turn the supplied default in to a Text instance.
Parameters
default (DefaultType) – Default value.
Returns
Text containing rendering of default value.
Return type
Text
response_type
alias of str
exception rich.prompt.PromptError
Exception base class for prompt related errors.
23.22 rich.protocol
rich.protocol.is_renderable(check_object)
Check if an object may be rendered by Rich.
Parameters
check_object (Any) –
Return type
bool
rich.protocol.rich_cast(renderable)
Cast an object to a renderable by calling __rich__ if present.
Parameters
renderable (object) – A potentially renderable object
Returns
The result of recursively calling __rich__.
Return type
object
23.23 rich.rule
23.24 rich.segment
class rich.segment.ControlType(value)
Non-printable control codes which typically translate to ANSI codes.
class rich.segment.Segment(text, style=None, control=None)
A piece of text with associated style. Segments are produced by the Console render process and are ultimately
converted in to strings to be written to the terminal.
Parameters
• text (str) – A piece of text.
• style (Style, optional) – An optional style to apply to the text.
• control (Tuple[ControlCode], optional) – Optional sequence of control codes.
cell_length
The cell length of this Segment.
Type
int
classmethod adjust_line_length(line, length, style=None, pad=True)
Adjust a line to a given width (cropping or padding as required).
Parameters
• segments (Iterable[Segment]) – A list of segments in a single line.
• length (int) – The desired width of the line.
• style (Style, optional) – The style of padding if used (space on the end). Defaults to
None.
• pad (bool, optional) – Pad lines with spaces if they are shorter than length. Defaults
to True.
• line (List[Segment]) –
Returns
A line of segments with the desired length.
Return type
List[Segment]
classmethod align_bottom(lines, width, height, style, new_lines=False)
Aligns render to bottom (adds extra lines above as required).
Args:
lines (List[List[Segment]]): A list of lines. width (int): Desired width. height (int, optional):
Desired height or None for no change. style (Style): Style of any padding added. Defaults to
None. new_lines (bool, optional): Padded lines should include “
“. Defaults to False.
Returns:
List[List[Segment]]: New list of lines.
Parameters
• lines (List[List[Segment]]) –
• width (int) –
• height (int) –
• style (Style) –
• new_lines (bool) –
Return type
List[List[Segment]]
“. Defaults to False.
Returns:
List[List[Segment]]: New list of lines.
Parameters
• lines (List[List[Segment]]) –
• width (int) –
• height (int) –
• style (Style) –
• new_lines (bool) –
Return type
List[List[Segment]]
Parameters
• lines (List[List[Segment]]) –
• width (int) –
• height (int) –
• style (Style) –
• new_lines (bool) –
Return type
List[List[Segment]]
Return type
Iterable[Segments]
property cell_length: int
The number of terminal cells required to display self.text.
Returns
A number of cells.
Return type
int
property control
Alias for field number 2
classmethod divide(segments, cuts)
Divides an iterable of segments in to portions.
Parameters
• cuts (Iterable[int]) – Cell positions where to divide.
• segments (Iterable[Segment]) –
Yields
[Iterable[List[Segment]]] – An iterable of Segments in List.
Return type
Iterable[List[Segment]]
classmethod filter_control(segments, is_control=False)
Filter segments by is_control attribute.
Parameters
• segments (Iterable[Segment]) – An iterable of Segment instances.
• is_control (bool, optional) – is_control flag to match in search.
Returns
And iterable of Segment instances.
Return type
Iterable[Segment]
classmethod get_line_length(line)
Get the length of list of segments.
Parameters
line (List[Segment]) – A line encoded as a list of Segments (assumes no ‘\n’ characters),
Returns
The length of the line.
Return type
int
classmethod get_shape(lines)
Get the shape (enclosing rectangle) of a list of lines.
Parameters
lines (List[List[Segment]]) – A list of lines (no ‘\n’ characters).
Returns
Width and height in characters.
Return type
Tuple[int, int]
property is_control: bool
Check if the segment contains control codes.
classmethod line()
Make a new line segment.
Return type
Segment
classmethod remove_color(segments)
Remove all color from an iterable of segments.
Parameters
segments (Iterable[Segment]) – An iterable segments.
Yields
Segment – Segments with colorless style.
Return type
Iterable[Segment]
classmethod set_shape(lines, width, height=None, style=None, new_lines=False)
Set the shape of a list of lines (enclosing rectangle).
Args:
lines (List[List[Segment]]): A list of lines. width (int): Desired width. height (int, optional):
Desired height or None for no change. style (Style, optional): Style of any padding added.
new_lines (bool, optional): Padded lines should include “
“. Defaults to False.
Returns:
List[List[Segment]]: New list of lines.
Parameters
• lines (List[List[Segment]]) –
• width (int) –
• height (Optional[int]) –
• style (Optional[Style]) –
• new_lines (bool) –
Return type
List[List[Segment]]
classmethod simplify(segments)
Simplify an iterable of segments by combining contiguous segments with the same style.
Parameters
segments (Iterable[Segment]) – An iterable of segments.
Returns
A possibly smaller iterable of segments that will render the same way.
Return type
Iterable[Segment]
classmethod split_and_crop_lines(segments, length, style=None, pad=True, include_new_lines=True)
Split segments in to lines, and crop lines greater than a given length.
Parameters
• segments (Iterable[Segment]) – An iterable of segments, probably generated from
console.render.
• length (int) – Desired line length.
• style (Style, optional) – Style to use for any padding.
• pad (bool) – Enable padding of lines that are less than length.
• include_new_lines (bool) –
Returns
An iterable of lines of segments.
Return type
Iterable[List[Segment]]
split_cells(cut)
Split segment in to two segments at the specified column.
If the cut point falls in the middle of a 2-cell wide character then it is replaced by two spaces, to preserve
the display width of the parent segment.
Returns
Two segments.
Return type
Tuple[Segment, Segment]
Parameters
cut (int) –
classmethod split_lines(segments)
Split a sequence of segments in to a list of lines.
Parameters
segments (Iterable[Segment]) – Segments potentially containing line feeds.
Yields
Iterable[List[Segment]] – Iterable of segment lists, one per line.
Return type
Iterable[List[Segment]]
classmethod strip_links(segments)
Remove all links from an iterable of styles.
Parameters
segments (Iterable[Segment]) – An iterable segments.
Yields
Segment – Segments with link removed.
Return type
Iterable[Segment]
classmethod strip_styles(segments)
Remove all styles from an iterable of segments.
Parameters
segments (Iterable[Segment]) – An iterable segments.
Yields
Segment – Segments with styles replace with None
Return type
Iterable[Segment]
property style
Alias for field number 1
property text
Alias for field number 0
class rich.segment.Segments(segments, new_lines=False)
A simple renderable to render an iterable of segments. This class may be useful if you want to print segments
outside of a __rich_console__ method.
Parameters
• segments (Iterable[Segment]) – An iterable of segments.
• new_lines (bool, optional) – Add new lines between segments. Defaults to False.
23.25 rich.spinner
23.26 rich.status
23.27 rich.style
classmethod from_meta(meta)
Create a new style with meta data.
Returns
A dictionary of meta data. Defaults to None.
Return type
meta (Optional[Dict[str, Any]])
Parameters
meta (Optional[Dict[str, Any]]) –
get_html_style(theme=None)
Get a CSS style rule.
Parameters
theme (Optional[TerminalTheme]) –
Return type
str
property link: Optional[str]
Link text, if set.
property link_id: str
Get a link id, used in ansi code for links.
property meta: Dict[str, Any]
Get meta information (can not be changed after construction).
classmethod normalize(style)
Normalize a style definition so that styles with the same effect have the same string representation.
Parameters
style (str) – A style definition.
Returns
Normal form of style definition.
Return type
str
classmethod null()
Create an ‘null’ style, equivalent to Style(), but more performant.
Return type
Style
classmethod on(meta=None, **handlers)
Create a blank style with meta information.
Example
style = Style.on(click=self.on_click)
Parameters
• meta (Optional[Dict[str, Any]], optional) – An optional dict of meta informa-
tion.
• **handlers (Any) – Keyword arguments are translated in to handlers.
Returns
A Style with meta information attached.
Return type
Style
classmethod parse(style_definition)
Parse a style definition.
Parameters
style_definition (str) – A string containing a style.
Raises
errors.StyleSyntaxError – If the style definition syntax is invalid.
Returns
A Style instance.
Return type
Style
classmethod pick_first(*values)
Pick first non-None style.
Parameters
values (Optional[Union[str, Style]]) –
Return type
Union[str, Style]
render(text='', *, color_system=ColorSystem.TRUECOLOR, legacy_windows=False)
Render the ANSI codes for the style.
Parameters
• text (str, optional) – A string to style. Defaults to “”.
• color_system (Optional[ColorSystem], optional) – Color system to render to.
Defaults to ColorSystem.TRUECOLOR.
• legacy_windows (bool) –
Returns
A string containing ANSI style codes.
Return type
str
test(text=None)
Write text with style directly to terminal.
This method is for testing purposes only.
Parameters
text (Optional[str], optional) – Text to style or None for style name.
Return type
None
property transparent_background: bool
Check if the style specified a transparent background.
update_link(link=None)
Get a copy with a different value for link.
Parameters
link (str, optional) – New value for link. Defaults to None.
Returns
A new Style instance.
Return type
Style
property without_color: Style
Get a copy of the style with color removed.
class rich.style.StyleStack(default_style)
A stack of styles.
Parameters
default_style (Style) –
property current: Style
Get the Style at the top of the stack.
pop()
Pop last style and discard.
Returns
New current style (also available as stack.current)
Return type
Style
push(style)
Push a new style on to the stack.
Parameters
style (Style) – New style to combine with current style.
Return type
None
23.28 rich.styled
23.29 rich.syntax
• path (AnyStr) – The path to the file containing the code you wish to know the lexer for.
• code (str, optional) – Optional string of code that will be used as a fallback if no lexer
is found for the supplied path.
Returns
The name of the Pygments lexer that best matches the supplied path/code.
Return type
str
highlight(code, line_range=None)
Highlight code and return a Text instance.
Parameters
• code (str) – Code to highlight.
• line_range (Tuple[int, int], optional) – Optional line range to highlight.
Returns
A text instance containing highlighted syntax.
Return type
Text
property lexer: Optional[Lexer]
The lexer for this syntax, or None if no lexer was found.
Tries to find the lexer by name if a string was passed to the constructor.
stylize_range(style, start, end)
Adds a custom style on a part of the code, that will be applied to the syntax display when it’s rendered.
Line numbers are 1-based, while column indexes are 0-based.
Parameters
• style (StyleType) – The style to apply.
• start (Tuple[int, int]) – The start of the range, in the form [line number, column
index].
• end (Tuple[int, int]) – The end of the range, in the form [line number, column index].
Return type
None
23.30 rich.table
• width (int, optional) – The width in characters of the table, or None to automatically
fit. Defaults to None.
• min_width (Optional[int], optional) – The minimum width of the table, or None for
no minimum. Defaults to None.
• box (box.Box, optional) – One of the constants in box.py used to draw the edges (see
Box), or None for no box lines. Defaults to box.HEAVY_HEAD.
• safe_box (Optional[bool], optional) – Disable box characters that don’t display on
windows legacy terminal with raster fonts. Defaults to True.
• padding (PaddingDimensions, optional) – Padding for cells (top, right, bottom, left).
Defaults to (0, 1).
• collapse_padding (bool, optional) – Enable collapsing of padding around cells. De-
faults to False.
• pad_edge (bool, optional) – Enable padding of edge cells. Defaults to True.
• expand (bool, optional) – Expand the table to fit the available space if True, otherwise
the table width will be auto-calculated. Defaults to False.
• show_header (bool, optional) – Show a header row. Defaults to True.
• show_footer (bool, optional) – Show a footer row. Defaults to False.
• show_edge (bool, optional) – Draw a box around the outside of the table. Defaults to
True.
• show_lines (bool, optional) – Draw lines between every row. Defaults to False.
• leading (bool, optional) – Number of blank lines between rows (precludes
show_lines). Defaults to 0.
• style (Union[str, Style], optional) – Default style for the table. Defaults to
“none”.
• row_styles (List[Union, str], optional) – Optional list of row styles, if more than
one style is given then the styles will alternate. Defaults to None.
• header_style (Union[str, Style], optional) – Style of the header. Defaults to “ta-
ble.header”.
• footer_style (Union[str, Style], optional) – Style of the footer. Defaults to “ta-
ble.footer”.
• border_style (Union[str, Style], optional) – Style of the border. Defaults to
None.
• title_style (Union[str, Style], optional) – Style of the title. Defaults to None.
• caption_style (Union[str, Style], optional) – Style of the caption. Defaults to
None.
• title_justify (str, optional) – Justify method for title. Defaults to “center”.
• caption_justify (str, optional) – Justify method for caption. Defaults to “center”.
• highlight (bool, optional) – Highlight cell contents (if str). Defaults to False.
• header (RenderableType) –
• footer (RenderableType) –
• justify (JustifyMethod) –
• vertical (VerticalAlignMethod) –
• overflow (OverflowMethod) –
• max_width (Optional[int]) –
• ratio (Optional[int]) –
• no_wrap (bool) –
• _index (int) –
• _cells (List[RenderableType]) –
property cells: Iterable[RenderableType]
Get all cells in the column, not including header.
copy()
Return a copy of this Column.
Return type
Column
property flexible: bool
Check if this column is flexible.
footer: RenderableType = ''
Renderable for the footer (typically a string)
Type
RenderableType
footer_style: Union[str, Style] = ''
The style of the footer.
Type
StyleType
header: RenderableType = ''
Renderable for the header (typically a string)
Type
RenderableType
header_style: Union[str, Style] = ''
The style of the header.
Type
StyleType
justify: JustifyMethod = 'left'
How to justify text within the column (“left”, “center”, “right”, or “full”)
Type
str
max_width: Optional[int] = None
Maximum width of column, or None for no maximum. Defaults to None.
Type
Optional[int]
23.31 rich.text
append_text(text)
Append another Text instance. This method is more performant that Text.append, but only works for Text.
Returns
Returns self for chaining.
Return type
Text
Parameters
text (Text) –
append_tokens(tokens)
Append iterable of str and style. Style may be a Style instance or a str style definition.
Parameters
• pairs (Iterable[Tuple[str, Optional[StyleType]]]) – An iterable of tuples
containing str content and style.
• tokens (Iterable[Tuple[str, Optional[Union[str, Style]]]]) –
Returns
Returns self for chaining.
Return type
Text
apply_meta(meta, start=0, end=None)
Apply meta data to the text, or a portion of the text.
Parameters
• meta (Dict[str, Any]) – A dict of meta information.
• start (int) – Start offset (negative indexing is supported). Defaults to 0.
• end (Optional[int], optional) – End offset (negative indexing is supported), or None
for end of text. Defaults to None.
Return type
None
classmethod assemble(*parts, style='', justify=None, overflow=None, no_wrap=None, end='\n',
tab_size=8, meta=None)
Construct a text instance by combining a sequence of strings with optional styles. The positional arguments
should be either strings, or a tuple of string + style.
Parameters
• style (Union[str, Style], optional) – Base style for text. Defaults to “”.
• justify (str, optional) – Justify method: “left”, “center”, “full”, “right”. Defaults to
None.
• overflow (str, optional) – Overflow method: “crop”, “fold”, “ellipsis”. Defaults to
None.
• end (str, optional) – Character to end text with. Defaults to “\n”.
• tab_size (int) – Number of spaces per tab, or None to use console.tab_size. De-
faults to None.
• meta (Dict[str, Any], optional) –
Return type
None
extend_style(spaces)
Extend the Text given number of spaces where the spaces have the same style as the last character.
Parameters
spaces (int) – Number of spaces to add to the Text.
Return type
None
fit(width)
Fit the text in to given width by chopping in to lines.
Parameters
width (int) – Maximum characters in a line.
Returns
Lines container.
Return type
Lines
classmethod from_ansi(text, *, style='', justify=None, overflow=None, no_wrap=None, end='\n',
tab_size=8)
Create a Text object from a string containing ANSI escape codes.
Parameters
• text (str) – A string containing escape codes.
• style (Union[str, Style], optional) – Base style for text. Defaults to “”.
• justify (str, optional) – Justify method: “left”, “center”, “full”, “right”. Defaults to
None.
• overflow (str, optional) – Overflow method: “crop”, “fold”, “ellipsis”. Defaults to
None.
• no_wrap (bool, optional) – Disable text wrapping, or None for default. Defaults to
None.
• end (str, optional) – Character to end text with. Defaults to “\n”.
• tab_size (int) – Number of spaces per tab, or None to use console.tab_size. De-
faults to None.
Return type
Text
classmethod from_markup(text, *, style='', emoji=True, emoji_variant=None, justify=None,
overflow=None, end='\n')
Create Text instance from markup.
Parameters
• text (str) – A string containing console markup.
• emoji (bool, optional) – Also render emoji code. Defaults to True.
• justify (str, optional) – Justify method: “left”, “center”, “full”, “right”. Defaults to
None.
join(lines)
Join text together with this instance as the separator.
Parameters
lines (Iterable[Text]) – An iterable of Text instances to join.
Returns
A new text instance containing join text.
Return type
Text
property markup: str
Get console markup to render this Text.
Returns
A string potentially creating markup tags.
Return type
str
on(meta=None, **handlers)
Apply event handlers (used by Textual project).
Example
Parameters
• meta (Dict[str, Any]) – Mapping of meta information.
• **handlers – Keyword args are prefixed with “@” to defined handlers.
Returns
Self is returned to method may be chained.
Return type
Text
Return type
None
set_length(new_length)
Set new length of the text, clipping or padding is required.
Parameters
new_length (int) –
Return type
None
property spans: List[Span]
Get a reference to the internal list of spans.
split(separator='\n', *, include_separator=False, allow_blank=False)
Split rich text in to lines, preserving styles.
Parameters
• separator (str, optional) – String to split on. Defaults to “\n”.
• include_separator (bool, optional) – Include the separator in the lines. Defaults
to False.
• allow_blank (bool, optional) – Return a blank line if the text ends with a separator.
Defaults to False.
Returns
A list of rich text, one per line of the original.
Return type
List[RichText]
classmethod styled(text, style='', *, justify=None, overflow=None)
Construct a Text instance with a pre-applied styled. A style applied in this way won’t be used to pad the
text when it is justified.
Parameters
• text (str) – A string containing console markup.
• style (Union[str, Style]) – Style to apply to the text. Defaults to “”.
• justify (str, optional) – Justify method: “left”, “center”, “full”, “right”. Defaults to
None.
• overflow (str, optional) – Overflow method: “crop”, “fold”, “ellipsis”. Defaults to
None.
Returns
A text instance with a style applied to the entire string.
Return type
Text
stylize(style, start=0, end=None)
Apply a style to the text, or a portion of the text.
Parameters
• style (Union[str, Style]) – Style instance or style definition to apply.
• start (int) – Start offset (negative indexing is supported). Defaults to 0.
• justify (str, optional) – Justify method: “default”, “left”, “center”, “full”, “right”.
Defaults to “default”.
• overflow (str, optional) – Overflow method: “crop”, “fold”, or “ellipsis”. Defaults
to None.
• tab_size (int, optional) – Default tab size. Defaults to 8.
• no_wrap (bool, optional) – Disable wrapping, Defaults to False.
Returns
Number of lines.
Return type
Lines
23.32 rich.theme
Return type
Theme
23.33 rich.traceback
Returns
A Traceback instance that may be printed.
Return type
Traceback
rich.traceback.install(*, console=None, width=100, extra_lines=3, theme=None, word_wrap=False,
show_locals=False, locals_max_length=10, locals_max_string=80,
locals_hide_dunder=True, locals_hide_sunder=None, indent_guides=True,
suppress=(), max_frames=100)
Install a rich traceback handler.
Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.
Parameters
• console (Optional[Console], optional) – Console to write exception to. Default uses
internal Console instance.
• width (Optional[int], optional) – Width (in characters) of traceback. Defaults to
100.
• extra_lines (int, optional) – Extra lines of code. Defaults to 3.
• theme (Optional[str], optional) – Pygments theme to use in traceback. Defaults to
None which will pick a theme appropriate for the platform.
• word_wrap (bool, optional) – Enable word wrapping of long lines. Defaults to False.
• show_locals (bool, optional) – Enable display of local variables. Defaults to False.
• locals_max_length (int, optional) – Maximum length of containers before abbrevi-
ating, or None for no abbreviation. Defaults to 10.
• locals_max_string (int, optional) – Maximum length of string before truncating, or
None to disable. Defaults to 80.
• locals_hide_dunder (bool, optional) – Hide locals prefixed with double underscore.
Defaults to True.
• locals_hide_sunder (bool, optional) – Hide locals prefixed with single underscore.
Defaults to False.
• indent_guides (bool, optional) – Enable indent guides in code and locals. Defaults
to True.
• suppress (Sequence[Union[str, ModuleType]]) – Optional sequence of modules or
paths to exclude from traceback.
• max_frames (int) –
Returns
The previous exception handler that was replaced.
Return type
Callable
23.34 rich.tree
23.35 rich.abc
class rich.abc.RichRenderable
An abstract base class for Rich renderables.
Note that there is no need to extend this class, the intended use is to check if an object supports the Rich renderable
protocol. For example:
if isinstance(my_object, RichRenderable):
console.print(my_object)
TWENTYFOUR
APPENDIX
24.1 Box
Rich has a number of constants that set the box characters used to draw tables and panels. To select a box style import
one of the constants below from rich.box. For example:
Note: Some of the box drawing characters will not display correctly on Windows legacy terminal (cmd.exe) with
raster fonts, and are disabled by default. If you want the full range of box options on Windows legacy terminal, use a
truetype font and set the safe_box parameter on the Table class to False.
python -m rich.box
185
Rich, Release 13.6.0
TWENTYFIVE
• genindex
• modindex
• search
187
Rich, Release 13.6.0
r
rich, 103
rich.abc, 183
rich.align, 75
rich.bar, 77
rich.color, 77
rich.columns, 80
rich.console, 80
rich.emoji, 101
rich.highlighter, 101
rich.json, 105
rich.layout, 106
rich.live, 109
rich.logging, 111
rich.markdown, 113
rich.markup, 120
rich.measure, 121
rich.padding, 122
rich.panel, 123
rich.pretty, 124
rich.progress, 129
rich.progress_bar, 128
rich.prompt, 144
rich.protocol, 148
rich.rule, 148
rich.segment, 148
rich.spinner, 154
rich.status, 155
rich.style, 156
rich.styled, 161
rich.syntax, 161
rich.table, 163
rich.text, 170
rich.theme, 179
rich.traceback, 180
rich.tree, 183
189
Rich, Release 13.6.0
Symbols C
__call__() (rich.highlighter.Highlighter method), 101 Capture (class in rich.console), 80
capture() (rich.console.Console method), 82
A CaptureError, 80
add() (rich.tree.Tree method), 183 cell_len (rich.text.Text property), 172
add_column() (rich.table.Table method), 168 cell_length (rich.segment.Segment attribute), 148
add_renderable() (rich.columns.Columns method), 80 cell_length (rich.segment.Segment property), 151
add_row() (rich.table.Table method), 168 cells (rich.table.Column property), 165
add_section() (rich.table.Table method), 169 center() (rich.align.Align class method), 75
add_split() (rich.layout.Layout method), 106 chain() (rich.style.Style class method), 157
add_task() (rich.progress.Progress method), 131 check_choice() (rich.prompt.PromptBase method),
adjust_line_length() (rich.segment.Segment class 146
method), 149 check_length() (rich.pretty.Node method), 125
advance() (rich.progress.Progress method), 131 children (rich.layout.Layout property), 106
Align (class in rich.align), 75 clamp() (rich.measure.Measurement method), 121
align() (rich.text.Text method), 170 clear() (rich.console.Console method), 82
align_bottom() (rich.segment.Segment class method), clear_live() (rich.console.Console method), 82
149 clear_meta_and_links() (rich.style.Style method),
align_middle() (rich.segment.Segment class method), 157
149 CodeBlock (class in rich.markdown), 113
align_top() (rich.segment.Segment class method), 150 Color (class in rich.color), 77
append() (rich.text.Text method), 170 color (rich.style.Style property), 157
append_text() (rich.text.Text method), 170 color_system (rich.console.Console property), 83
append_tokens() (rich.text.Text method), 171 ColorParseError, 79
apply_meta() (rich.text.Text method), 171 ColorSystem (class in rich.color), 79
apply_style() (rich.segment.Segment class method), ColorType (class in rich.color), 79
150 Column (class in rich.table), 163
ascii_only (rich.console.ConsoleOptions property), 97 Columns (class in rich.columns), 80
ask() (rich.prompt.PromptBase class method), 145 ColumnSplitter (class in rich.layout), 106
assemble() (rich.text.Text class method), 171 combine() (rich.style.Style class method), 157
completed (rich.progress.ProgressSample property),
B 135
background_style (rich.style.Style property), 156 completed (rich.progress.Task attribute), 137
Bar (class in rich.bar), 77 config (rich.theme.Theme property), 179
BarColumn (class in rich.progress), 129 Confirm (class in rich.prompt), 144
begin_capture() (rich.console.Console method), 82 Console (class in rich.console), 80
bell() (rich.console.Console method), 82 console (rich.status.Status property), 155
bgcolor (rich.style.Style property), 156 ConsoleDimensions (class in rich.console), 96
blank_copy() (rich.text.Text method), 172 ConsoleOptions (class in rich.console), 96
blend_rgb() (in module rich.color), 79 ConsoleRenderable (class in rich.console), 99
BlockQuote (class in rich.markdown), 113 ConsoleThreadLocals (class in rich.console), 99
control (rich.segment.Segment property), 151
191
Rich, Release 13.6.0
192 Index
Rich, Release 13.6.0
Index 193
Rich, Release 13.6.0
194 Index
Rich, Release 13.6.0
Index 195
Rich, Release 13.6.0
rich.color rich.text
module, 77 module, 170
rich.columns rich.theme
module, 80 module, 179
rich.console rich.traceback
module, 80 module, 180
rich.emoji rich.tree
module, 101 module, 183
rich.highlighter rich_cast() (in module rich.protocol), 148
module, 101 RichCast (class in rich.console), 100
rich.json RichHandler (class in rich.logging), 111
module, 105 RichRenderable (class in rich.abc), 183
rich.layout right() (rich.align.Align class method), 76
module, 106 right_crop() (rich.text.Text method), 176
rich.live Row (class in rich.table), 166
module, 109 row_count (rich.table.Table property), 170
rich.logging RowSplitter (class in rich.layout), 108
module, 111 rstrip() (rich.text.Text method), 176
rich.markdown rstrip_end() (rich.text.Text method), 176
module, 113 Rule (class in rich.rule), 148
rich.markup rule() (rich.console.Console method), 91
module, 120
rich.measure S
module, 121 save_html() (rich.console.Console method), 92
rich.padding save_svg() (rich.console.Console method), 92
module, 122 save_text() (rich.console.Console method), 93
rich.panel screen() (rich.console.Console method), 93
module, 123 ScreenContext (class in rich.console), 100
rich.pretty ScreenUpdate (class in rich.console), 100
module, 124 Segment (class in rich.segment), 148
rich.progress Segments (class in rich.segment), 154
module, 129 set_alt_screen() (rich.console.Console method), 93
rich.progress_bar set_length() (rich.text.Text method), 177
module, 128 set_live() (rich.console.Console method), 94
rich.prompt set_shape() (rich.segment.Segment class method), 152
module, 144 set_spinner() (rich.progress.SpinnerColumn method),
rich.protocol 136
module, 148 set_window_title() (rich.console.Console method),
rich.rule 94
module, 148 show_cursor() (rich.console.Console method), 94
rich.segment simplify() (rich.segment.Segment class method), 152
module, 148 size (rich.console.Console property), 94
rich.spinner size (rich.console.ConsoleOptions attribute), 98
module, 154 span (rich.measure.Measurement property), 121
rich.status spans (rich.text.Text property), 177
module, 155 speed (rich.progress.Task property), 138
rich.style Spinner (class in rich.spinner), 154
module, 156 SpinnerColumn (class in rich.progress), 136
rich.styled split() (rich.layout.Layout method), 107
module, 161 split() (rich.text.Text method), 177
rich.syntax split_and_crop_lines() (rich.segment.Segment class
module, 161 method), 153
rich.table split_cells() (rich.segment.Segment method), 153
module, 163 split_column() (rich.layout.Layout method), 107
196 Index
Rich, Release 13.6.0
Index 197
Rich, Release 13.6.0
198 Index