This page is a complete API reference for the Console class defined in rich/console.py It covers the constructor, all public properties, methods, and the associated context manager and helper classes (Capture, PagerContext, ScreenContext, ThemeContext).
For a conceptual overview of how Console fits into the rendering pipeline, see Architecture Overview and Rendering Pipeline. For information about Style and Color types referenced here, see Styles and Colors. For export functionality (HTML, SVG, text), see Export and Capture.
File: rich/console.py587-622
Console is the central class in Rich. All rendering, styling, and output goes through an instance of this class. It manages:
Type aliases defined in the module:
| Alias | Definition |
|---|---|
RenderableType | Union[ConsoleRenderable, RichCast, str] |
RenderResult | Iterable[Union[RenderableType, Segment]] |
JustifyMethod | Literal["default", "left", "center", "right", "full"] |
OverflowMethod | Literal["fold", "crop", "ellipsis", "ignore"] |
HighlighterType | Callable[[Union[str, Text]], Text] |
Sources: rich/console.py74-77
All parameters are keyword-only.
| Parameter | Type | Default | Description |
|---|---|---|---|
file | IO[str] | None | File object to write to. Falls back to sys.stderr if stderr=True, else sys.stdout. |
stderr | bool | False | Write to sys.stderr instead of sys.stdout when file is not set. |
quiet | bool | False | Suppress all output. |
| Parameter | Type | Default | Description |
|---|---|---|---|
color_system | str | None | "auto" | One of "auto", "standard", "256", "truecolor", "windows", or None to disable color. |
force_terminal | bool | None | None | Override terminal detection. True enables ANSI codes even to non-terminals. |
force_jupyter | bool | None | None | Override Jupyter environment detection. |
force_interactive | bool | None | None | Override interactive mode detection (affects animations). |
no_color | bool | None | None | Disable color output. Falls back to the NO_COLOR environment variable. |
legacy_windows | bool | None | None | Enable legacy Windows terminal mode. Auto-detected if None. |
safe_box | bool | True | Restrict box characters to those renderable on legacy Windows. |
width | int | None | None | Fixed console width in characters. Auto-detected if None. |
height | int | None | None | Fixed console height in lines. Auto-detected if None. |
| Parameter | Type | Default | Description |
|---|---|---|---|
markup | bool | True | Enable Rich markup parsing globally. |
emoji | bool | True | Enable emoji code replacement globally. |
emoji_variant | str | None | None | Emoji variant: "text" or "emoji". |
highlight | bool | True | Enable automatic syntax highlighting on output. |
highlighter | HighlighterType | ReprHighlighter() | Default highlighter applied to strings. |
soft_wrap | bool | False | Disable word-wrapping and cropping by default in print(). |
tab_size | int | 8 | Number of spaces used to replace tab characters. |
style | StyleType | None | None | Style applied to all output. |
theme | Theme | None | None | Custom Theme instance. Uses built-in default if None. |
| Parameter | Type | Default | Description |
|---|---|---|---|
log_time | bool | True | Show timestamp column in log() output. |
log_path | bool | True | Show caller file/line column in log() output. |
log_time_format | str | Callable | "[%X]" | strftime format string or callable returning a Text object. |
get_datetime | Callable[[], datetime] | None | Override datetime source for log(). Defaults to datetime.now. |
get_time | Callable[[], float] | None | Override time source. Defaults to time.monotonic. |
| Parameter | Type | Default | Description |
|---|---|---|---|
record | bool | False | Enable recording of all output. Required before calling export_text(), export_html(), export_svg(). |
Sources: rich/console.py625-758
Console reads several environment variables during initialization and property evaluation.
| Variable | Effect |
|---|---|
NO_COLOR | Disables all color output when set to any non-empty value. |
FORCE_COLOR | Forces is_terminal to True when set and non-empty, enabling color. |
TERM | Set to "dumb" or "unknown" to disable color and cursor movement. |
COLORTERM | Set to "truecolor" or "24bit" to select the truecolor system. |
COLUMNS | Default console width if width constructor arg is not set. |
LINES | Default console height if height constructor arg is not set. |
JUPYTER_COLUMNS | Console width in Jupyter environments. |
JUPYTER_LINES | Console height in Jupyter environments. |
TTY_COMPATIBLE | "1" forces is_terminal=True; "0" forces is_terminal=False. |
TTY_INTERACTIVE | "1" forces is_interactive=True; "0" forces is_interactive=False. |
Sources: rich/console.py795-818 docs/source/console.rst416-438
| Property | Type | Description |
|---|---|---|
is_terminal | bool | True if writing to a TTY-capable device. Respects force_terminal, FORCE_COLOR, TTY_COMPATIBLE. |
is_dumb_terminal | bool | True if TERM is "dumb" or "unknown". |
is_jupyter | bool | True if running inside a Jupyter notebook or Colab. |
is_interactive | bool | True if running in interactive mode (enables animations). |
is_alt_screen | bool | True if the alternate screen is currently active. |
color_system | str | None | Active color system name: "standard", "256", "truecolor", "windows", or None. |
encoding | str | Encoding of the output file, e.g. "utf-8". |
legacy_windows | bool | True if legacy Windows console mode is active. |
Sources: rich/console.py914-994
| Property | Type | Settable | Description |
|---|---|---|---|
size | ConsoleDimensions | Yes (tuple) | Named tuple (width, height). Auto-detected from terminal or env vars. |
width | int | Yes | Width in character cells. |
height | int | Yes | Height in lines. |
ConsoleDimensions is a NamedTuple with fields width: int and height: int.
Sources: rich/console.py109-115 rich/console.py1010-1096
| Attribute | Type | Description |
|---|---|---|
file | IO[str] | The output file (property, also settable). |
options | ConsoleOptions | Default ConsoleOptions derived from the current terminal state. |
highlighter | HighlighterType | Active default highlighter instance. |
style | StyleType | None | Global style applied to all output. |
soft_wrap | bool | Global soft-wrap default for print(). |
tab_size | int | Tab character expansion width. |
record | bool | Whether output recording is active. |
quiet | bool | Suppress all output when True. |
no_color | bool | Whether color is disabled. |
Sources: rich/console.py678-757
print()Console.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)
The primary output method. Renders any number of objects to the console.
| Parameter | Type | Default | Description |
|---|---|---|---|
*objects | Any | — | Objects to render. Strings are parsed for markup/emoji. |
sep | str | " " | Separator between objects. |
end | str | "\n" | String appended after all objects. |
style | StyleType | None | Style applied to all output. |
justify | JustifyMethod | None | Text justification: "default", "left", "center", "right", "full". |
overflow | OverflowMethod | None | Overflow handling: "fold", "crop", "ellipsis", "ignore". |
no_wrap | bool | None | Disable word wrap. |
emoji | bool | None | Override emoji setting for this call. |
markup | bool | None | Override markup setting for this call. |
highlight | bool | None | Override highlight setting for this call. |
width | int | None | Override render width. |
height | int | None | Override render height. |
crop | bool | True | Crop output to terminal width. |
soft_wrap | bool | None | Soft-wrap mode (disables no_wrap, overflow, crop). |
new_line_start | bool | False | Prepend a newline if output is multi-line. |
log()rich/console.py1762-1830 (approx.)
Console.log(*objects, sep=" ", end="\n", style=None, justify=None,
emoji=None, markup=None, highlight=None, log_locals=False,
_stack_offset=1)
Same as print(), but prepends a timestamp and appends caller file/line information (controlled by log_time and log_path constructor args).
| Extra Parameter | Type | Default | Description |
|---|---|---|---|
log_locals | bool | False | Display a table of local variables at the call site. |
_stack_offset | int | 1 | Frames to look back for caller info. Internal use. |
out()Console.out(*objects, sep=" ", end="\n", style=None, highlight=None)
Low-level output. Joins objects with str(), does not apply markup, emoji, or word-wrap. Passes output through print() with markup=False, emoji=False, no_wrap=True, overflow="ignore", crop=False.
print_json()rich/console.py1831-1870 (approx.)
Console.print_json(json=None, *, data=None, indent=2, highlight=True,
skip_keys=False, ensure_ascii=False,
check_circular=True, allow_nan=True,
default=None, sort_keys=False)
Pretty-prints JSON. Pass either a JSON string via json, or a Python object via data (which will be serialized).
rule()Console.rule(title="", *, characters="─", style="rule.line", align="center")
Draws a horizontal line across the terminal with an optional centered title.
| Parameter | Type | Default | Description |
|---|---|---|---|
title | TextType | "" | Text displayed over the rule. |
characters | str | "─" | Character(s) forming the line. |
style | StyleType | "rule.line" | Style of the line. |
align | AlignMethod | "center" | Title alignment: "left", "center", "right". |
input()rich/console.py1872-1910 (approx.)
Console.input(prompt="", *, markup=False, emoji=False, password=False,
stream=None)
Display a prompt and read user input. Uses getpass if password=True. Renders the prompt via print().
line()Console.line(count=1)
Write one or more blank lines.
bell()Console.bell()
Emit a terminal bell character (\x07), if the terminal supports it.
clear()Console.clear(home=True)
Clear the terminal screen. If home=True (default), also move the cursor to the top-left.
Sources: rich/console.py1098-1161 rich/console.py1585-1870
render()Console.render(renderable, options=None) -> Iterable[Segment]
Low-level method that converts any renderable to an iterable of Segment objects. Resolves __rich__ and __rich_console__ protocols. Used internally by print() and log().
render_lines()Console.render_lines(renderable, options=None, *, style=None,
pad=True, new_lines=False) -> List[List[Segment]]
Render a renderable and return a list of lines, where each line is a list of Segment objects. Used by Panel, Table, and other container renderables.
| Parameter | Type | Default | Description |
|---|---|---|---|
style | Style | None | Optional style applied to all segments. |
pad | bool | True | Pad lines shorter than render width with spaces. |
new_lines | bool | False | Include "\n" segments at end of each line. |
render_str()Console.render_str(text, *, style="", justify=None, overflow=None,
emoji=None, markup=None, highlight=None,
highlighter=None) -> Text
Convert a raw string to a Text instance, applying markup, emoji, and highlighting as configured. Called internally whenever a string is passed to print().
measure()Console.measure(renderable, *, options=None) -> Measurement
Return a Measurement named tuple (minimum, maximum) describing how many characters wide the renderable needs to be. See Measurement and Layout.
control()Console.control(*control)
Write non-printing Control objects directly to the output buffer (cursor movement, screen control, etc.). Ignored on dumb terminals.
get_style()Console.get_style(name, *, default=None) -> Style
Resolve a style by name from the theme stack, or parse a style definition string. Raises MissingStyle if the name cannot be resolved and no default is provided.
Sources: rich/console.py1283-1504
capture()Returns a Capture context manager. While active, all output is buffered instead of written to the terminal. Call capture.get() after the with block to retrieve the captured string. Raises CaptureError if get() is called before the context exits.
pager()Returns a PagerContext. Content printed within the block is passed to the system pager (e.g., less). The pager command is sourced from MANPAGER then PAGER environment variables.
| Parameter | Type | Default | Description |
|---|---|---|---|
pager | Pager | None | Custom Pager instance. Defaults to SystemPager. |
styles | bool | False | Preserve ANSI styles when sending to pager. |
links | bool | False | Preserve hyperlinks when sending to pager. |
screen()Returns a ScreenContext that enables the terminal alternate screen on entry and restores the normal screen on exit. The screen.update(*renderables, style=None) method replaces the displayed content.
| Parameter | Type | Default | Description |
|---|---|---|---|
hide_cursor | bool | True | Hide the cursor while in alternate screen. |
style | StyleType | None | Background style for the screen. |
status()Returns a Status context manager that renders a spinner animation and status message. Does not block other output.
| Parameter | Type | Default | Description |
|---|---|---|---|
status | RenderableType | — | Status message. |
spinner | str | "dots" | Spinner animation name. See python -m rich.spinner. |
spinner_style | StyleType | "status.spinner" | Style of the spinner. |
speed | float | 1.0 | Spinner speed multiplier. |
refresh_per_second | float | 12.5 | Refresh rate. |
use_theme()Returns a ThemeContext that pushes a Theme onto the style stack for the duration of the block, then restores the previous theme on exit.
Sources: rich/console.py1102-1194 rich/console.py902-912 rich/console.py349-367
These methods require record=True on the constructor.
| Method | Description |
|---|---|
export_text(clear=True) | Return all recorded output as plain text (ANSI stripped). |
export_html(theme=None, clear=True, code_format=..., inline_styles=False) | Return recorded output as an HTML document string. |
export_svg(title="Rich", theme=None, unique_id=None, clear=True) | Return recorded output as an SVG document string. |
save_text(path, clear=True) | Write export_text() result to a file. |
save_html(path, theme=None, clear=True, inline_styles=False) | Write export_html() result to a file. |
save_svg(path, title="Rich", theme=None, unique_id=None, clear=True) | Write export_svg() result to a file. |
The clear parameter (default True) discards the recording buffer after export.
Sources: rich/console.py1920-2050 (approx.), docs/source/console.rst249-284
| Method | Description |
|---|---|
push_theme(theme, *, inherit=True) | Push a Theme onto the thread-local theme stack. |
pop_theme() | Pop the top Theme from the stack. |
push_render_hook(hook) | Register a RenderHook that receives renderables before output. |
pop_render_hook() | Remove the most-recently-added RenderHook. |
RenderHook is an abstract class. Subclasses must implement process_renderables(renderables) -> List[ConsoleRenderable].
Sources: rich/console.py550-566 rich/console.py887-912 rich/console.py849-861
| Method | Returns | Description |
|---|---|---|
show_cursor(show=True) | bool | Show or hide the cursor. Returns True if control code was emitted. |
set_alt_screen(enable=True) | bool | Enable or disable alternate screen mode directly. |
set_window_title(title) | bool | Set the terminal window title. Returns True if code was emitted. |
update_screen(renderable, *, region=None, options=None) | None | Render content to the alternate screen (raises NoAltScreen if not active). |
update_screen_lines(lines, *, region=None) | None | Write pre-rendered lines to the alternate screen. |
begin_capture() | None | Begin capturing mode (lower-level alternative to capture()). |
end_capture() | str | End capturing mode and return captured string. |
Sources: rich/console.py1196-1267 rich/console.py872-885
The following diagram shows how a call to Console.print() flows through the rendering system.
Console.print() Data Flow
Sources: rich/console.py1648-1760 rich/console.py1506-1583 rich/console.py1300-1349
Console-related types in rich/console.py
Sources: rich/console.py109-270 rich/console.py316-453 rich/console.py550-566
ConsoleOptions ReferenceConsoleOptions is a @dataclass passed to every __rich_console__ method. It describes the space available for rendering.
| Field | Type | Description |
|---|---|---|
size | ConsoleDimensions | Full terminal dimensions. |
min_width | int | Minimum width the renderable may use. |
max_width | int | Maximum width the renderable may use. |
max_height | int | Maximum height in lines. |
height | int | None | Explicit height constraint, or None for unconstrained. |
is_terminal | bool | Whether the target is a terminal. |
legacy_windows | bool | Legacy Windows mode flag. |
encoding | str | Output encoding string. |
justify | JustifyMethod | None | Justify override. |
overflow | OverflowMethod | None | Overflow override. |
no_wrap | bool | None | Disable wrap override. |
highlight | bool | None | Highlight override. |
markup | bool | None | Markup override. |
Mutation methods (all return a copy, never modify in place):
| Method | Description |
|---|---|
copy() | Return a shallow copy. |
update(**kwargs) | Return a copy with specified fields changed. |
update_width(width) | Set both min_width and max_width. |
update_height(height) | Set both height and max_height. |
reset_height() | Return a copy with height=None. |
update_dimensions(width, height) | Set both width and height fields. |
Computed property:
ascii_only -> bool: True if encoding does not start with "utf".Sources: rich/console.py118-249
Group and group DecoratorGroup rich/console.py456-487 — A renderable container that wraps multiple renderables and yields them in sequence. When fit=True (default), measurement reflects the content width; when fit=False, it fills available space.
group decorator rich/console.py489-508 — Converts a generator function that yields renderables into a function that returns a Group.
Sources: rich/console.py456-508
Color system auto-detection logic (_detect_color_system)
Sources: rich/console.py795-818
Console uses a threading.RLock (self._lock) to protect output and recording operations. The buffer system is thread-local via ConsoleThreadLocals(threading.local), which holds a per-thread buffer, buffer_index, and theme_stack.
This means:
render_lines() acquires self._lock for its duration.rich/console.py541-547 rich/console.py1375-1376
render() and render_lines() process renderables end-to-end.Segment type produced by render().Style, Color, and ColorSystem types.Theme, ThemeStack, and default style names.export_html(), export_svg(), and recording.Live integrates with Console via set_live() / clear_live().Status object returned by console.status().Refresh this wiki
This wiki was recently refreshed. Please wait 2 days to refresh again.