0
# Console and Output
1
2
Core console functionality for printing styled text, handling terminal capabilities, and managing output formatting. The Console class is the central component of Rich, providing comprehensive terminal output management with automatic capability detection.
3
4
## Capabilities
5
6
### Console Class
7
8
The main Console class handles all terminal output with support for styling, color, markup, and advanced formatting features.
9
10
```python { .api }
11
class Console:
12
"""
13
A high level console interface for Rich.
14
15
Args:
16
color_system: The color system to use ("auto", "standard", "256", "truecolor", "windows", None)
17
force_terminal: Force terminal detection
18
force_jupyter: Force Jupyter mode detection
19
force_interactive: Force interactive mode
20
soft_wrap: Enable soft wrapping of long lines
21
theme: Default theme or None for builtin theme
22
stderr: Write to stderr instead of stdout
23
file: File object to write to or None for stdout
24
quiet: Suppress all output if True
25
width: Width of output or None to auto-detect
26
height: Height of output or None to auto-detect
27
style: Default style for console output
28
no_color: Disable color output
29
tab_size: Size of tabs in characters
30
record: Record all output for later playback
31
markup: Enable Rich markup processing
32
emoji: Enable emoji code rendering
33
emoji_variant: Emoji variant preference
34
highlight: Enable highlighting of output
35
log_time: Include timestamp in log output
36
log_path: Include path in log output
37
log_time_format: Format for log timestamps
38
highlighter: Default highlighter for output
39
legacy_windows: Enable legacy Windows terminal support
40
safe_box: Disable box characters incompatible with legacy terminals
41
get_datetime: Callable to get current datetime
42
get_time: Callable to get current time
43
"""
44
def __init__(
45
self,
46
color_system: Optional[str] = "auto",
47
force_terminal: Optional[bool] = None,
48
force_jupyter: Optional[bool] = None,
49
force_interactive: Optional[bool] = None,
50
soft_wrap: bool = False,
51
theme: Optional[Theme] = None,
52
stderr: bool = False,
53
file: Optional[TextIO] = None,
54
quiet: bool = False,
55
width: Optional[int] = None,
56
height: Optional[int] = None,
57
style: Optional[StyleType] = None,
58
no_color: Optional[bool] = None,
59
tab_size: int = 8,
60
record: bool = False,
61
markup: bool = True,
62
emoji: bool = True,
63
emoji_variant: Optional[EmojiVariant] = None,
64
highlight: bool = True,
65
log_time: bool = True,
66
log_path: bool = True,
67
log_time_format: Union[str, FormatTimeCallable] = "[%X]",
68
highlighter: Optional[HighlighterType] = ReprHighlighter(),
69
legacy_windows: Optional[bool] = None,
70
safe_box: bool = True,
71
get_datetime: Optional[Callable[[], datetime]] = None,
72
get_time: Optional[Callable[[], float]] = None,
73
_environ: Optional[Mapping[str, str]] = None,
74
): ...
75
76
def print(
77
self,
78
*objects: Any,
79
sep: str = " ",
80
end: str = "\n",
81
style: Optional[StyleType] = None,
82
justify: Optional[JustifyMethod] = None,
83
overflow: Optional[OverflowMethod] = None,
84
no_wrap: Optional[bool] = None,
85
emoji: Optional[bool] = None,
86
markup: Optional[bool] = None,
87
highlight: Optional[bool] = None,
88
width: Optional[int] = None,
89
height: Optional[int] = None,
90
crop: bool = True,
91
soft_wrap: Optional[bool] = None,
92
new_line_start: bool = False,
93
) -> None:
94
"""
95
Print to the console with rich formatting.
96
97
Args:
98
*objects: Objects to print
99
sep: Separator between objects
100
end: String to print at end
101
style: Style to apply to output
102
justify: Text justification method
103
overflow: Overflow handling method
104
no_wrap: Disable text wrapping
105
emoji: Enable emoji rendering
106
markup: Enable markup processing
107
highlight: Enable highlighting
108
width: Maximum width of output
109
height: Maximum height of output
110
crop: Crop output to fit console
111
soft_wrap: Enable soft wrapping
112
new_line_start: Start on new line
113
"""
114
115
def log(
116
self,
117
*objects: Any,
118
sep: str = " ",
119
end: str = "\n",
120
style: Optional[StyleType] = None,
121
justify: Optional[JustifyMethod] = None,
122
emoji: Optional[bool] = None,
123
markup: Optional[bool] = None,
124
highlight: Optional[bool] = None,
125
log_locals: bool = False,
126
_stack_offset: int = 1,
127
) -> None:
128
"""
129
Print with timestamp and caller information.
130
131
Args:
132
*objects: Objects to log
133
sep: Separator between objects
134
end: String to print at end
135
style: Style to apply to output
136
justify: Text justification method
137
emoji: Enable emoji rendering
138
markup: Enable markup processing
139
highlight: Enable highlighting
140
log_locals: Include local variables in output
141
"""
142
143
def clear(self, home: bool = True) -> None:
144
"""
145
Clear the console.
146
147
Args:
148
home: Move cursor to home position
149
"""
150
151
def rule(
152
self,
153
title: TextType = "",
154
*,
155
characters: str = "─",
156
style: StyleType = "rule.line",
157
end: str = "\n",
158
align: AlignMethod = "center",
159
) -> None:
160
"""
161
Print a horizontal rule with optional title.
162
163
Args:
164
title: Title text for the rule
165
characters: Characters to use for the rule
166
style: Style for the rule
167
end: String to print at end
168
align: Alignment of title
169
"""
170
171
def status(
172
self,
173
status: RenderableType,
174
*,
175
spinner: str = "dots",
176
spinner_style: StyleType = "status.spinner",
177
speed: float = 1.0,
178
) -> "Status":
179
"""
180
Create a status context manager with spinner.
181
182
Args:
183
status: Status text or renderable
184
spinner: Spinner style name
185
spinner_style: Style for spinner
186
speed: Spinner animation speed
187
188
Returns:
189
Status context manager
190
"""
191
192
def capture(self) -> "Capture":
193
"""
194
Create a capture context to record console output.
195
196
Returns:
197
Capture context manager
198
"""
199
200
def pager(
201
self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False
202
) -> "PagerContext":
203
"""
204
Create a pager context for scrollable output.
205
206
Args:
207
pager: Pager instance or None for system pager
208
styles: Include styles in paged output
209
links: Include links in paged output
210
211
Returns:
212
Pager context manager
213
"""
214
215
def screen(
216
self, *, hide_cursor: bool = True, alt_screen: bool = True
217
) -> "ScreenContext":
218
"""
219
Create a screen context for full-screen applications.
220
221
Args:
222
hide_cursor: Hide the cursor
223
alt_screen: Use alternate screen buffer
224
225
Returns:
226
Screen context manager
227
"""
228
229
def measure(self, renderable: RenderableType) -> Measurement:
230
"""
231
Measure the dimensions of a renderable.
232
233
Args:
234
renderable: Object to measure
235
236
Returns:
237
Measurement with minimum and maximum dimensions
238
"""
239
240
def render(
241
self, renderable: RenderableType, options: Optional[ConsoleOptions] = None
242
) -> Iterable[Segment]:
243
"""
244
Render a renderable to segments.
245
246
Args:
247
renderable: Object to render
248
options: Console options or None for default
249
250
Returns:
251
Iterator of segments
252
"""
253
254
def export_html(
255
self,
256
*,
257
theme: Optional[TerminalTheme] = None,
258
clear: bool = True,
259
code_format: Optional[str] = None,
260
inline_styles: bool = False,
261
) -> str:
262
"""
263
Export console content as HTML.
264
265
Args:
266
theme: Terminal theme or None for default
267
clear: Clear console after export
268
code_format: Code format template
269
inline_styles: Use inline CSS styles
270
271
Returns:
272
HTML string
273
"""
274
275
def export_svg(
276
self,
277
*,
278
title: str = "Rich",
279
theme: Optional[TerminalTheme] = None,
280
clear: bool = True,
281
code_format: str = CONSOLE_SVG_FORMAT,
282
font_size: float = 14,
283
unique_id: Optional[str] = None,
284
) -> str:
285
"""
286
Export console content as SVG.
287
288
Args:
289
title: SVG title
290
theme: Terminal theme or None for default
291
clear: Clear console after export
292
code_format: SVG format template
293
font_size: Font size in pixels
294
unique_id: Unique identifier for SVG elements
295
296
Returns:
297
SVG string
298
"""
299
300
def export_text(self, *, clear: bool = True, styles: bool = False) -> str:
301
"""
302
Export console content as plain text.
303
304
Args:
305
clear: Clear console after export
306
styles: Include ANSI styles in output
307
308
Returns:
309
Plain text string
310
"""
311
312
# Properties
313
@property
314
def size(self) -> ConsoleDimensions:
315
"""Get console dimensions (width, height)."""
316
317
@property
318
def width(self) -> int:
319
"""Get console width in characters."""
320
321
@property
322
def height(self) -> int:
323
"""Get console height in lines."""
324
325
@property
326
def is_terminal(self) -> bool:
327
"""Check if output is a terminal."""
328
329
@property
330
def is_dumb_terminal(self) -> bool:
331
"""Check if terminal has limited capabilities."""
332
333
@property
334
def is_interactive(self) -> bool:
335
"""Check if console is interactive."""
336
337
@property
338
def color_system(self) -> Optional[str]:
339
"""Get the active color system."""
340
341
@property
342
def encoding(self) -> str:
343
"""Get the output encoding."""
344
345
@property
346
def is_jupyter(self) -> bool:
347
"""Check if running in Jupyter."""
348
349
@property
350
def options(self) -> ConsoleOptions:
351
"""Get default console options."""
352
```
353
354
### Global Functions
355
356
Module-level convenience functions for common operations.
357
358
```python { .api }
359
def get_console() -> Console:
360
"""
361
Get a global Console instance.
362
363
Returns:
364
Global console instance
365
"""
366
367
def reconfigure(*args: Any, **kwargs: Any) -> None:
368
"""
369
Reconfigure the global console.
370
371
Args:
372
*args: Positional arguments for Console constructor
373
**kwargs: Keyword arguments for Console constructor
374
"""
375
376
def print(
377
*objects: Any,
378
sep: str = " ",
379
end: str = "\n",
380
file: Optional[IO[str]] = None,
381
flush: bool = False,
382
) -> None:
383
"""
384
Rich-enhanced print function with markup support.
385
386
Args:
387
*objects: Objects to print
388
sep: Separator between objects
389
end: String to print at end
390
file: File to write to or None for stdout
391
flush: Force flush output (ignored, Rich always flushes)
392
"""
393
394
def print_json(
395
json: Optional[str] = None,
396
*,
397
data: Any = None,
398
indent: Union[None, int, str] = 2,
399
highlight: bool = True,
400
skip_keys: bool = False,
401
ensure_ascii: bool = False,
402
check_circular: bool = True,
403
allow_nan: bool = True,
404
default: Optional[Callable[[Any], Any]] = None,
405
sort_keys: bool = False,
406
) -> None:
407
"""
408
Pretty print JSON with syntax highlighting.
409
410
Args:
411
json: JSON string to print
412
data: Python data to encode as JSON
413
indent: Number of spaces to indent
414
highlight: Enable syntax highlighting
415
skip_keys: Skip keys that are not basic types
416
ensure_ascii: Escape non-ASCII characters
417
check_circular: Check for circular references
418
allow_nan: Allow NaN and Infinity values
419
default: Function to handle non-serializable objects
420
sort_keys: Sort object keys
421
"""
422
423
def inspect(
424
obj: Any,
425
*,
426
console: Optional[Console] = None,
427
title: Optional[str] = None,
428
help: bool = False,
429
methods: bool = False,
430
docs: bool = True,
431
private: bool = False,
432
dunder: bool = False,
433
sort: bool = True,
434
all: bool = False,
435
value: bool = True,
436
) -> None:
437
"""
438
Inspect any Python object with rich formatting.
439
440
Args:
441
obj: Object to inspect
442
console: Console instance or None for global console
443
title: Title for the inspection or None to use object type
444
help: Show full help text instead of summary
445
methods: Include callable methods
446
docs: Show docstrings
447
private: Show private attributes (starting with _)
448
dunder: Show dunder attributes (starting with __)
449
sort: Sort attributes alphabetically
450
all: Show all attributes (equivalent to private=True, dunder=True)
451
value: Show attribute values
452
"""
453
```
454
455
**Usage Examples:**
456
457
```python
458
from rich.console import Console
459
from rich import print
460
461
# Basic console usage
462
console = Console()
463
console.print("Hello, World!", style="bold red")
464
465
# Enhanced print with markup
466
print("[bold blue]Information:[/bold blue] Process completed successfully")
467
print("[red]Error:[/red] Unable to connect to server")
468
469
# Logging with timestamps
470
console.log("Application started")
471
console.log("Processing data...", style="yellow")
472
473
# Status spinner
474
with console.status("Loading data...") as status:
475
time.sleep(2)
476
status.update("Processing...")
477
time.sleep(2)
478
479
# Measuring content
480
from rich.text import Text
481
text = Text("Hello World", style="bold")
482
measurement = console.measure(text)
483
print(f"Text width: {measurement.minimum}-{measurement.maximum}")
484
485
# Exporting output
486
console.print("This will be exported", style="green")
487
html_output = console.export_html()
488
svg_output = console.export_svg()
489
490
# Object inspection
491
inspect([1, 2, 3, 4, 5])
492
inspect(console, methods=True)
493
```