0
# Rich
1
2
Rich is a comprehensive Python terminal formatting library that enables developers to create beautiful, interactive command-line interfaces with advanced text styling, color support, and rich output components. It provides a powerful API for rendering styled text with support for RGB/HEX colors, markup-style formatting, and automatic terminal capability detection.
3
4
## Package Information
5
6
- **Package Name**: rich
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install rich`
10
- **Minimum Python**: 3.8+
11
- **Dependencies**: pygments, markdown-it-py
12
13
## Core Imports
14
15
```python
16
import rich
17
from rich.console import Console
18
from rich.text import Text
19
from rich import print
20
```
21
22
Common imports for specific functionality:
23
24
```python
25
from rich.table import Table
26
from rich.progress import Progress
27
from rich.panel import Panel
28
from rich.syntax import Syntax
29
from rich.markdown import Markdown
30
from rich.prompt import Prompt
31
from rich.live import Live
32
from rich.layout import Layout
33
```
34
35
## Basic Usage
36
37
```python
38
from rich.console import Console
39
from rich.text import Text
40
from rich import print
41
42
# Enhanced print function with markup support
43
print("Hello [bold magenta]World[/bold magenta]!")
44
print("[bold red]Alert![/bold red] This is [italic]important[/italic].")
45
46
# Console for advanced features
47
console = Console()
48
console.print("Hello", "World!", style="bold blue")
49
50
# Rich text objects
51
text = Text("Hello World!")
52
text.stylize("bold magenta", 0, 6)
53
console.print(text)
54
55
# Simple table
56
from rich.table import Table
57
table = Table()
58
table.add_column("Name")
59
table.add_column("Score")
60
table.add_row("Alice", "95")
61
table.add_row("Bob", "87")
62
console.print(table)
63
```
64
65
## Architecture
66
67
Rich is built around several key components:
68
69
- **Console**: Central output manager handling terminal detection, rendering, and export
70
- **Text Objects**: Styled text with spans for precise formatting control
71
- **Renderables**: Protocol for objects that can be rendered to the terminal
72
- **Styles**: Comprehensive styling system with color, typography, and effects
73
- **Layout System**: Advanced positioning and sizing for complex UIs
74
- **Live Display**: Real-time updating content for progress bars and dynamic interfaces
75
76
## Capabilities
77
78
### Console Output and Styling
79
80
Core console functionality for printing styled text, handling terminal capabilities, and managing output formatting.
81
82
```python { .api }
83
class Console:
84
def __init__(
85
self,
86
color_system: Optional[str] = "auto",
87
force_terminal: Optional[bool] = None,
88
force_jupyter: Optional[bool] = None,
89
force_interactive: Optional[bool] = None,
90
soft_wrap: bool = False,
91
theme: Optional[Theme] = None,
92
stderr: bool = False,
93
file: Optional[TextIO] = None,
94
quiet: bool = False,
95
width: Optional[int] = None,
96
height: Optional[int] = None,
97
style: Optional[StyleType] = None,
98
no_color: Optional[bool] = None,
99
tab_size: int = 8,
100
record: bool = False,
101
markup: bool = True,
102
emoji: bool = True,
103
emoji_variant: Optional[EmojiVariant] = None,
104
highlight: bool = True,
105
log_time: bool = True,
106
log_path: bool = True,
107
log_time_format: Union[str, FormatTimeCallable] = "[%X]",
108
highlighter: Optional[HighlighterType] = ReprHighlighter(),
109
legacy_windows: Optional[bool] = None,
110
safe_box: bool = True,
111
get_datetime: Optional[Callable[[], datetime]] = None,
112
get_time: Optional[Callable[[], float]] = None,
113
_environ: Optional[Mapping[str, str]] = None,
114
): ...
115
116
def print(
117
self,
118
*objects: Any,
119
sep: str = " ",
120
end: str = "\n",
121
style: Optional[StyleType] = None,
122
justify: Optional[JustifyMethod] = None,
123
overflow: Optional[OverflowMethod] = None,
124
no_wrap: Optional[bool] = None,
125
emoji: Optional[bool] = None,
126
markup: Optional[bool] = None,
127
highlight: Optional[bool] = None,
128
width: Optional[int] = None,
129
height: Optional[int] = None,
130
crop: bool = True,
131
soft_wrap: Optional[bool] = None,
132
new_line_start: bool = False,
133
) -> None: ...
134
135
def print(
136
*objects: Any,
137
sep: str = " ",
138
end: str = "\n",
139
file: Optional[IO[str]] = None,
140
flush: bool = False,
141
) -> None: ...
142
143
def print_json(
144
json: Optional[str] = None,
145
*,
146
data: Any = None,
147
indent: Union[None, int, str] = 2,
148
highlight: bool = True,
149
skip_keys: bool = False,
150
ensure_ascii: bool = False,
151
check_circular: bool = True,
152
allow_nan: bool = True,
153
default: Optional[Callable[[Any], Any]] = None,
154
sort_keys: bool = False,
155
) -> None: ...
156
```
157
158
[Console and Output](./console.md)
159
160
### Rich Text and Styling
161
162
Advanced text objects with precise styling control, markup support, and comprehensive formatting options.
163
164
```python { .api }
165
class Text:
166
def __init__(
167
self,
168
text: str = "",
169
style: StyleType = "",
170
*,
171
justify: Optional[JustifyMethod] = None,
172
overflow: OverflowMethod = "fold",
173
no_wrap: Optional[bool] = None,
174
end: str = "\n",
175
tab_size: Optional[int] = 8,
176
spans: Optional[List[Span]] = None,
177
): ...
178
179
def stylize(
180
self,
181
style: StyleType,
182
start: int = 0,
183
end: Optional[int] = None,
184
) -> None: ...
185
186
@classmethod
187
def from_markup(
188
cls,
189
text: str,
190
*,
191
style: StyleType = "",
192
emoji: bool = True,
193
emoji_variant: Optional[EmojiVariant] = None,
194
) -> "Text": ...
195
196
class Style:
197
def __init__(
198
self,
199
*,
200
color: Optional[ColorType] = None,
201
bgcolor: Optional[ColorType] = None,
202
bold: Optional[bool] = None,
203
dim: Optional[bool] = None,
204
italic: Optional[bool] = None,
205
underline: Optional[bool] = None,
206
blink: Optional[bool] = None,
207
blink2: Optional[bool] = None,
208
reverse: Optional[bool] = None,
209
conceal: Optional[bool] = None,
210
strike: Optional[bool] = None,
211
underline2: Optional[bool] = None,
212
frame: Optional[bool] = None,
213
encircle: Optional[bool] = None,
214
overline: Optional[bool] = None,
215
link: Optional[str] = None,
216
meta: Optional[Dict[str, Any]] = None,
217
): ...
218
```
219
220
[Text and Styling](./text-styling.md)
221
222
### Tables and Data Display
223
224
Comprehensive table system with flexible columns, styling, borders, and automatic sizing.
225
226
```python { .api }
227
class Table:
228
def __init__(
229
self,
230
*columns: Union[Column, str],
231
title: Optional[TextType] = None,
232
caption: Optional[TextType] = None,
233
width: Optional[int] = None,
234
min_width: Optional[int] = None,
235
box: Optional[Box] = box.HEAVY_HEAD,
236
safe_box: Optional[bool] = None,
237
padding: PaddingDimensions = (0, 1),
238
collapse_padding: bool = False,
239
pad_edge: bool = True,
240
expand: bool = False,
241
show_header: bool = True,
242
show_footer: bool = False,
243
show_edge: bool = True,
244
show_lines: bool = False,
245
leading: int = 0,
246
style: StyleType = "",
247
row_styles: Optional[Iterable[StyleType]] = None,
248
header_style: Optional[StyleType] = None,
249
footer_style: Optional[StyleType] = None,
250
border_style: Optional[StyleType] = None,
251
title_style: Optional[StyleType] = None,
252
caption_style: Optional[StyleType] = None,
253
title_justify: JustifyMethod = "center",
254
caption_justify: JustifyMethod = "center",
255
highlight: bool = False,
256
): ...
257
258
def add_column(
259
self,
260
header: RenderableType = "",
261
*,
262
footer: RenderableType = "",
263
header_style: Optional[StyleType] = None,
264
footer_style: Optional[StyleType] = None,
265
style: Optional[StyleType] = None,
266
justify: JustifyMethod = "left",
267
vertical: VerticalAlignMethod = "top",
268
overflow: OverflowMethod = "ellipsis",
269
width: Optional[int] = None,
270
min_width: Optional[int] = None,
271
max_width: Optional[int] = None,
272
ratio: Optional[int] = None,
273
no_wrap: bool = False,
274
) -> None: ...
275
276
def add_row(
277
self,
278
*renderables: Optional[RenderableType],
279
style: Optional[StyleType] = None,
280
end_section: bool = False,
281
) -> None: ...
282
```
283
284
[Tables](./tables.md)
285
286
### Progress Tracking
287
288
Advanced progress bar system with customizable columns, multiple tasks, and real-time updates.
289
290
```python { .api }
291
class Progress:
292
def __init__(
293
self,
294
*columns: Union[str, ProgressColumn],
295
console: Optional[Console] = None,
296
auto_refresh: bool = True,
297
refresh_per_second: float = 10,
298
speed_estimate_period: float = 30.0,
299
transient: bool = False,
300
redirect_stdout: bool = True,
301
redirect_stderr: bool = True,
302
get_time: Optional[GetTimeCallable] = None,
303
disable: bool = False,
304
expand: bool = False,
305
): ...
306
307
def add_task(
308
self,
309
description: str,
310
start: bool = True,
311
total: Optional[float] = 100.0,
312
completed: float = 0,
313
visible: bool = True,
314
**fields: Any,
315
) -> TaskID: ...
316
317
def update(
318
self,
319
task_id: TaskID,
320
*,
321
total: Optional[float] = None,
322
completed: Optional[float] = None,
323
advance: Optional[float] = None,
324
description: Optional[str] = None,
325
visible: Optional[bool] = None,
326
refresh: bool = False,
327
**fields: Any,
328
) -> None: ...
329
330
def track(
331
self,
332
sequence: Iterable[ProgressType],
333
task_id: Optional[TaskID] = None,
334
description: str = "Working...",
335
total: Optional[float] = None,
336
auto_refresh: bool = True,
337
console: Optional[Console] = None,
338
transient: bool = False,
339
get_time: Optional[GetTimeCallable] = None,
340
refresh_per_second: float = 10,
341
style: StyleType = "bar.back",
342
complete_style: StyleType = "bar.complete",
343
finished_style: StyleType = "bar.finished",
344
pulse_style: StyleType = "bar.pulse",
345
update_period: float = 0.1,
346
disable: bool = False,
347
show_speed: bool = True,
348
) -> Iterable[ProgressType]: ...
349
```
350
351
[Progress Tracking](./progress.md)
352
353
### Syntax Highlighting
354
355
Code syntax highlighting with theme support and extensive language coverage via Pygments.
356
357
```python { .api }
358
class Syntax:
359
def __init__(
360
self,
361
code: str,
362
lexer: Optional[Union[Lexer, str]] = None,
363
*,
364
theme: Union[str, SyntaxTheme] = "monokai",
365
dedent: bool = False,
366
line_numbers: bool = False,
367
start_line: int = 1,
368
line_range: Optional[Tuple[int, int]] = None,
369
highlight_lines: Optional[Set[int]] = None,
370
code_width: Optional[int] = None,
371
tab_size: int = 4,
372
word_wrap: bool = False,
373
background_color: Optional[str] = None,
374
indent_guides: bool = False,
375
padding: PaddingDimensions = 0,
376
): ...
377
378
@classmethod
379
def from_path(
380
cls,
381
path: Union[str, PathLike[str]],
382
encoding: str = "utf-8",
383
lexer: Optional[Union[Lexer, str]] = None,
384
theme: Union[str, SyntaxTheme] = "monokai",
385
dedent: bool = False,
386
line_numbers: bool = False,
387
line_range: Optional[Tuple[int, int]] = None,
388
start_line: int = 1,
389
highlight_lines: Optional[Set[int]] = None,
390
code_width: Optional[int] = None,
391
tab_size: int = 4,
392
word_wrap: bool = False,
393
background_color: Optional[str] = None,
394
indent_guides: bool = False,
395
padding: PaddingDimensions = 0,
396
) -> "Syntax": ...
397
```
398
399
[Syntax Highlighting](./syntax.md)
400
401
### Interactive Components
402
403
Live updating displays, user input prompts, and real-time interface components.
404
405
```python { .api }
406
class Live:
407
def __init__(
408
self,
409
renderable: Optional[RenderableType] = None,
410
*,
411
console: Optional[Console] = None,
412
screen: bool = False,
413
auto_refresh: bool = True,
414
refresh_per_second: float = 4,
415
transient: bool = False,
416
redirect_stdout: bool = True,
417
redirect_stderr: bool = True,
418
vertical_overflow: OverflowMethod = "ellipsis",
419
get_renderable: Optional[Callable[[], RenderableType]] = None,
420
): ...
421
422
class Prompt:
423
@classmethod
424
def ask(
425
cls,
426
prompt: TextType = "",
427
*,
428
console: Optional[Console] = None,
429
password: bool = False,
430
choices: Optional[List[str]] = None,
431
show_default: bool = True,
432
show_choices: bool = True,
433
default: Any = ...,
434
stream: Optional[TextIO] = None,
435
) -> Any: ...
436
```
437
438
[Interactive Components](./interactive.md)
439
440
### Layout and Positioning
441
442
Advanced layout system for complex terminal UIs with flexible positioning and sizing.
443
444
```python { .api }
445
class Layout:
446
def __init__(
447
self,
448
renderable: Optional[RenderableType] = None,
449
*,
450
name: str = "root",
451
size: Optional[int] = None,
452
minimum_size: int = 1,
453
ratio: int = 1,
454
visible: bool = True,
455
): ...
456
457
def split(
458
self,
459
*layouts: Union["Layout", RenderableType],
460
splitter: Splitter = "column",
461
) -> None: ...
462
463
def split_column(self, *layouts: Union["Layout", RenderableType]) -> None: ...
464
def split_row(self, *layouts: Union["Layout", RenderableType]) -> None: ...
465
```
466
467
[Layout System](./layout.md)
468
469
### Markdown Rendering
470
471
CommonMark-compliant markdown rendering with syntax highlighting and Rich formatting.
472
473
```python { .api }
474
class Markdown:
475
def __init__(
476
self,
477
markup: str,
478
*,
479
code_theme: Union[str, SyntaxTheme] = "monokai",
480
justify: Optional[JustifyMethod] = None,
481
style: StyleType = "none",
482
hyperlinks: bool = True,
483
inline_code_lexer: Optional[str] = None,
484
inline_code_theme: Optional[Union[str, SyntaxTheme]] = None,
485
): ...
486
```
487
488
[Markdown](./markdown.md)
489
490
### Panel and Container Components
491
492
Panels, rules, columns, and other container components for organizing content.
493
494
```python { .api }
495
class Panel:
496
def __init__(
497
self,
498
renderable: RenderableType,
499
box: Box = box.ROUNDED,
500
*,
501
safe_box: Optional[bool] = None,
502
expand: bool = True,
503
style: StyleType = "none",
504
border_style: StyleType = "none",
505
width: Optional[int] = None,
506
height: Optional[int] = None,
507
padding: PaddingDimensions = (0, 1),
508
highlight: bool = False,
509
title: Optional[TextType] = None,
510
title_align: AlignMethod = "center",
511
subtitle: Optional[TextType] = None,
512
subtitle_align: AlignMethod = "center",
513
): ...
514
515
class Rule:
516
def __init__(
517
self,
518
title: TextType = "",
519
*,
520
characters: str = "─",
521
style: StyleType = "rule.line",
522
end: str = "\n",
523
align: AlignMethod = "center",
524
): ...
525
```
526
527
[Panels and Containers](./containers.md)
528
529
### Utilities and Helpers
530
531
Color handling, measurement, error types, and other utility functions.
532
533
```python { .api }
534
class Color:
535
@classmethod
536
def parse(cls, color: ColorType) -> "Color": ...
537
538
def blend(self, destination: "Color", factor: float) -> "Color": ...
539
540
def inspect(
541
obj: Any,
542
*,
543
console: Optional[Console] = None,
544
title: Optional[str] = None,
545
help: bool = False,
546
methods: bool = False,
547
docs: bool = True,
548
private: bool = False,
549
dunder: bool = False,
550
sort: bool = True,
551
all: bool = False,
552
value: bool = True,
553
) -> None: ...
554
```
555
556
[Utilities](./utilities.md)
557
558
## Types
559
560
```python { .api }
561
from typing import Union, Optional, IO, Any, Callable, List, Dict, Tuple, Iterable
562
563
# Core types
564
TextType = Union[str, Text]
565
StyleType = Union[str, Style]
566
RenderableType = Union[ConsoleRenderable, RichRenderable, str]
567
ColorType = Union[int, str, Tuple[int, int, int], Color]
568
569
# Method types
570
JustifyMethod = Literal["default", "left", "center", "right", "full"]
571
OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"]
572
AlignMethod = Literal["left", "center", "right"]
573
VerticalAlignMethod = Literal["top", "middle", "bottom"]
574
575
# Progress types
576
TaskID = NewType("TaskID", int)
577
GetTimeCallable = Callable[[], float]
578
579
# Console types
580
HighlighterType = Callable[[Union[str, Text]], Text]
581
FormatTimeCallable = Callable[[datetime], Text]
582
583
# Padding type
584
PaddingDimensions = Union[
585
int,
586
Tuple[int],
587
Tuple[int, int],
588
Tuple[int, int, int],
589
Tuple[int, int, int, int],
590
]
591
```