rich.console

class rich.console.Capture(console)[source]

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()[source]

Get the result of the capture.

Return type

str

exception rich.console.CaptureError[source]

An error in the Capture context manager.

class rich.console.Console(*, color_system='auto', force_terminal=None, force_jupyter=None, force_interactive=None, soft_wrap=False, theme=None, stderr=False, file=None, quiet=False, width=None, height=None, style=None, no_color=None, tab_size=8, record=False, markup=True, emoji=True, emoji_variant=None, highlight=True, log_time=True, log_path=True, log_time_format='[%X]', highlighter=<rich.highlighter.ReprHighlighter object>, legacy_windows=None, safe_box=True, get_datetime=None, get_time=None, _environ=None)[source]

A high level console interface.

Parameters
  • color_system (str, optional) – The color system supported by your terminal, either "standard", "256" or "truecolor". Leave as "auto" to autodetect.

  • force_terminal (Optional[bool], optional) – Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.

  • force_jupyter (Optional[bool], optional) – Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.

  • force_interactive (Optional[bool], optional) – Enable/disable interactive mode, or None to auto detect. Defaults to None.

  • soft_wrap (Optional[bool], optional) – Set soft wrap default on print method. Defaults to False.

  • theme (Theme, optional) – An optional style theme object, or None for default theme.

  • stderr (bool, optional) – Use stderr rather than stdout if file is not specified. Defaults to False.

  • file (IO, optional) – A file object where the console should write to. Defaults to stdout.

  • quiet (bool, Optional) – Boolean to suppress all output. Defaults to False.

  • width (int, optional) – The width of the terminal. Leave as default to auto-detect width.

  • height (int, optional) – The height of the terminal. Leave as default to auto-detect height.

  • style (StyleType, optional) – Style to apply to all output, or None for no style. Defaults to None.

  • no_color (Optional[bool], optional) – Enabled no color mode, or None to auto detect. Defaults to None.

  • tab_size (int, optional) – Number of spaces used to replace a tab character. Defaults to 8.

  • record (bool, optional) – Boolean to enable recording of terminal output, required to call export_html(), export_svg(), and export_text(). Defaults to False.

  • markup (bool, optional) – Boolean to enable Console Markup. Defaults to True.

  • emoji (bool, optional) – Enable emoji code. Defaults to True.

  • emoji_variant (str, optional) – Optional emoji variant, either “text” or “emoji”. Defaults to None.

  • highlight (bool, optional) – Enable automatic highlighting. Defaults to True.

  • log_time (bool, optional) – Boolean to enable logging of time by log() methods. Defaults to True.

  • log_path (bool, optional) – Boolean to enable the logging of the caller by log(). Defaults 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()[source]

Begin capturing console output. Call end_capture() to exit capture mode and return output.

Return type

None

bell()[source]

Play a ‘bell’ sound (if supported by the terminal).

Return type

None

capture()[source]

A context manager to capture the result of print() or log() in a string, rather than writing it to the console.

Example

>>> from rich.console import Console
>>> console = Console()
>>> with console.capture() as capture:
...     console.print("[bold magenta]Hello World[/]")
>>> print(capture.get())
Returns

Context manager with disables writing to the terminal.

Return type

Capture

clear(home=True)[source]

Clear the screen.

Parameters

home (bool, optional) – Also move the cursor to ‘home’ position. Defaults to True.

Return type

None

clear_live()[source]

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)[source]

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()[source]

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)[source]

Generate HTML from console contents (requires record=True argument in constructor).

Parameters
  • theme (TerminalTheme, optional) – TerminalTheme object containing console colors.

  • clear (bool, optional) – Clear record buffer after exporting. Defaults to True.

  • code_format (str, optional) – Format string to render HTML. In addition to ‘{foreground}’, ‘{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.

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)[source]

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)[source]

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)[source]

Get a Style instance by its theme name or parse a definition.

Parameters
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)[source]

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.

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)[source]

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)[source]

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 default. Defaults to None.

  • markup (Optional[bool], optional) – Enable markup, or None to use console default. 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)[source]

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 measuring, 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)[source]

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)[source]

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

Example

>>> from rich.console import Console
>>> from rich.__main__ import make_test_card
>>> console = Console()
>>> with console.pager():
        console.print(make_test_card())
Returns

A context manager.

Return type

PagerContext

Parameters
pop_render_hook()[source]

Pop the last renderhook from the stack.

Return type

None

pop_theme()[source]

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)[source]

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 default. Defaults to None.

  • markup (Optional[bool], optional) – Enable markup, or None to use console default. Defaults to None.

  • highlight (Optional[bool], optional) – Enable automatic highlighting, or None to use console default. Defaults to None.

  • width (Optional[int], optional) – Width of output, or None to auto-detect. Defaults to None.

  • crop (Optional[bool], optional) – Crop output to width of terminal. Defaults to True.

  • soft_wrap (bool, optional) – Enable soft wrap mode which disables word wrapping and cropping of text or None for Console default. Defaults to None.

  • new_line_start (bool, False) – Insert a new line at the start if the output contains more than one line. Defaults to False.

  • height (Optional[int]) –

Return type

None

print_exception(*, width=100, extra_lines=3, theme=None, word_wrap=False, show_locals=False, suppress=(), max_frames=100)[source]

Prints a rich render of the last exception and traceback.

Parameters
  • width (Optional[int], optional) – Number of characters used to render code. Defaults to 100.

  • extra_lines (int, optional) – Additional lines of code to render. Defaults to 3.

  • theme (str, optional) – Override pygments theme used in traceback

  • 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.

  • suppress (Iterable[Union[str, ModuleType]]) – Optional sequence of modules or paths to exclude from traceback.

  • max_frames (int) – Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.

Return type

None

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)[source]

Pretty prints JSON. Output will be valid JSON.

Parameters
  • json (Optional[str]) – A string containing JSON.

  • data (Any) – If json is not supplied, then encode this data.

  • indent (Union[None, int, str], optional) – Number of spaces to indent. Defaults to 2.

  • highlight (bool, optional) – Enable highlighting of output: Defaults to True.

  • skip_keys (bool, optional) – Skip keys not of a basic type. Defaults to False.

  • ensure_ascii (bool, optional) – Escape all non-ascii characters. Defaults to False.

  • check_circular (bool, optional) – Check for circular references. Defaults to True.

  • allow_nan (bool, optional) – Allow NaN and Infinity values. Defaults to True.

  • default (Callable, optional) – A callable that converts values that can not be encoded 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)[source]

Add a new render hook to the stack.

Parameters

hook (RenderHook) – Render hook instance.

Return type

None

push_theme(theme, *, inherit=True)[source]

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)[source]

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)[source]

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 (Optional[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 “

” characters at end of lines.

Returns:

List[List[Segment]]: A list of lines, where a line is a list of Segment objects.

Parameters
Return type

List[List[Segment]]

render_str(text, *, style='', justify=None, overflow=None, emoji=None, markup=None, highlight=None, highlighter=None)[source]

Convert a string to a Text instance. This is called automatically if you print or log a string.

Parameters
  • text (str) – Text to render.

  • style (Union[str, Style], optional) – Style to apply to rendered text.

  • justify (str, optional) – Justify method: “default”, “left”, “center”, “full”, or “right”. Defaults to None.

  • overflow (str, optional) – Overflow method: “crop”, “fold”, or “ellipsis”. Defaults to None.

  • emoji (Optional[bool], optional) – Enable emoji, or None to use Console default.

  • markup (Optional[bool], optional) – Enable markup, or None to use Console default.

  • highlight (Optional[bool], optional) – Enable highlighting, or None to use Console default.

  • highlighter (HighlighterType, optional) – Optional highlighter to apply.

Returns

Renderable object.

Return type

ConsoleRenderable

rule(title='', *, characters='─', style='rule.line', align='center')[source]

Draw a line with optional centered title.

Parameters
  • title (str, optional) – Text to render over the rule. Defaults to “”.

  • characters (str, optional) – Character(s) to form the line. Defaults to “─”.

  • style (str, optional) – Style of line. Defaults to “rule.line”.

  • align (str, optional) – How to align the title, one of “left”, “center”, or “right”. Defaults to “center”.

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)[source]

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 colors.

  • clear (bool, optional) – Clear record buffer after exporting. Defaults to True.

  • code_format (str, optional) – Format string to render HTML. In addition to ‘{foreground}’, ‘{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)[source]

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

  • 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

None

save_text(path, *, clear=True, styles=False)[source]

Generate text from console and save to a given location (requires record=True argument in constructor).

Parameters
  • path (str) – Path to write text files.

  • clear (bool, optional) – Clear record buffer after exporting. Defaults to True.

  • styles (bool, optional) – If True, ansi style codes will be included. False for plain text. Defaults to False.

Return type

None

screen(hide_cursor=True, style=None)[source]

Context manager to enable and disable ‘alternative screen’ mode.

Parameters
  • hide_cursor (bool, optional) – Also hide the cursor. Defaults to False.

  • style (Style, optional) – Optional style for screen. Defaults to None.

Returns

Context which enables alternate screen on enter, and disables it on exit.

Return type

~ScreenContext

set_alt_screen(enable=True)[source]

Enables alternative screen mode.

Note, if you enable this mode, you should ensure that is disabled before the application exits. See screen() for a context manager that handles this for you.

Parameters

enable (bool, optional) – Enable (True) or disable (False) alternate screen. Defaults to True.

Returns

True if the control codes were written.

Return type

bool

set_live(live)[source]

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)[source]

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 window title has actually changed, since the feature may be unsupported/disabled in some terminals.

Return type

bool

show_cursor(show=True)[source]

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

status(status, *, spinner='dots', spinner_style='status.spinner', speed=1.0, refresh_per_second=12.5)[source]

Display a status and spinner.

Parameters
  • status (RenderableType) – A status renderable (str or Text typically).

  • spinner (str, optional) – Name of spinner animation (see python -m rich.spinner). Defaults to “dots”.

  • spinner_style (StyleType, optional) – Style of spinner. Defaults to “status.spinner”.

  • speed (float, optional) – Speed factor for spinner animation. Defaults to 1.0.

  • refresh_per_second (float, optional) – Number of refreshes per second. Defaults to 12.5.

Returns

A Status object that may be used as a context manager.

Return type

Status

update_screen(renderable, *, region=None, options=None)[source]

Update the screen at a given offset.

Parameters
  • renderable (RenderableType) – A Rich renderable.

  • region (Region, optional) – Region of screen to update, or None for entire screen. Defaults to None.

  • x (int, optional) – x offset. Defaults to 0.

  • y (int, optional) – y offset. Defaults to 0.

  • options (Optional[ConsoleOptions]) –

Raises

errors.NoAltScreen – If the Console isn’t in alt screen mode.

Return type

None

update_screen_lines(lines, x=0, y=0)[source]

Update lines of the screen at a given offset.

Parameters
  • lines (List[List[Segment]]) – Rendered lines (as produced by render_lines()).

  • x (int, optional) – x offset (column no). Defaults to 0.

  • y (int, optional) – y offset (column no). Defaults to 0.

Raises

errors.NoAltScreen – If the Console isn’t in alt screen mode.

Return type

None

use_theme(theme, *, inherit=True)[source]

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)[source]

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)[source]

Options for __rich_console__ method.

Parameters
property ascii_only: bool

Check if renderables should use ascii only.

copy()[source]

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()[source]

Return a copy of the options with height set to None.

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>)[source]

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)[source]

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)[source]

Update the height, and return a copy.

Parameters

height (int) – New height

Returns

New Console options instance.

Return type

~ConsoleOptions

update_width(width)[source]

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)[source]

An object that supports the console protocol.

class rich.console.ConsoleThreadLocals(theme_stack, buffer=<factory>, buffer_index=0)[source]

Thread local values for Console context.

Parameters
  • theme_stack (ThemeStack) –

  • buffer (List[Segment]) –

  • buffer_index (int) –

class rich.console.Group(*renderables, fit=True)[source]

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. Defaults to True.

class rich.console.NewLine(count=1)[source]

A renderable to generate new line(s)

Parameters

count (int) –

class rich.console.PagerContext(console, pager=None, styles=False, links=False)[source]

A context manager that ‘pages’ content. See pager() for usage.

Parameters
class rich.console.RenderHook[source]

Provides hooks in to the render process.

abstract process_renderables(renderables)[source]

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)[source]

An object that may be ‘cast’ to a console renderable.

class rich.console.ScreenContext(console, hide_cursor, style='')[source]

A context manager that enables an alternative screen. See screen() for usage.

Parameters
update(*renderables, style=None)[source]

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)[source]

Render a list of lines at a given offset.

Parameters
class rich.console.ThemeContext(console, theme, inherit=True)[source]

A context manager to use a temporary theme. See use_theme() for usage.

Parameters
rich.console.detect_legacy_windows()[source]

Detect legacy Windows.

Return type

bool

rich.console.group(fit=True)[source]

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]]