rich.console

class rich.console.Capture(console: rich.console.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() → str[source]

Get the result of the capture.

exception rich.console.CaptureError[source]

An error in the Capture context manager.

class rich.console.Console(*, color_system: Optional[typing_extensions.Literal[auto, standard, 256, truecolor, windows]] = 'auto', force_terminal: bool = None, force_jupyter: bool = None, theme: rich.theme.Theme = None, file: IO[str] = None, width: int = None, height: int = None, tab_size: int = 8, record: bool = False, markup: bool = True, emoji: bool = True, highlight: bool = True, log_time: bool = True, log_path: bool = True, log_time_format: str = '[%X]', highlighter: Optional[HighlighterType] = <rich.highlighter.ReprHighlighter object>, legacy_windows: bool = None, safe_box: bool = True, _environ: Dict[str, str] = 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.

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

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

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

  • record (bool, optional) – Boolean to enable recording of terminal output, required to call export_html() 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.

  • 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 (str, optional) – Log time format if log_time is enabled. 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.

begin_capture() → None[source]

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

bell() → None[source]

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

capture()rich.console.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: bool = True) → None[source]

Clear the screen.

Parameters

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

property color_system

Get color system string.

Returns

“standard”, “256” or “truecolor”.

Return type

Optional[str]

control(control_codes: Union[Control, str]) → None[source]

Insert non-printing control codes.

Parameters

control_codes (str) – Control codes, such as those that may move the cursor.

property encoding

Get the encoding of the console file, e.g. "utf-8".

Returns

A standard encoding string.

Return type

str

end_capture() → str[source]

End capture mode and return captured string.

Returns

Console output.

Return type

str

export_html(*, theme: rich.terminal_theme.TerminalTheme = None, clear: bool = True, code_format: str = None, inline_styles: bool = False) → str[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, should contain {foreground} {background} and {code}.

  • 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_text(*, clear: bool = True, styles: bool = False) → str[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

get_style(name: Union[str, rich.style.Style], *, default: Union[rich.style.Style, str] = None)rich.style.Style[source]

Get a Style instance by it’s theme name or parse a definition.

Parameters

name (str) – The name of a style or a style definition.

Returns

A Style object.

Return type

Style

Raises

MissingStyle – If no style could be parsed from name.

input(prompt: Union[str, Text] = '', *, markup: bool = True, emoji: bool = True, password: bool = False, stream: TextIO = None) → str[source]

Displays a prompt and waits for input from the user. The prompt may contain color / style.

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, optional): Hide typed text. Defaults to False.

  • stream – (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.

Returns

Text read from stdin.

Return type

str

property is_dumb_terminal

Detect dumb terminal.

Returns

True if writing to a dumb terminal, otherwise False.

Return type

bool

property is_terminal

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: int = 1) → None[source]

Write new line(s).

Parameters

count (int, optional) – Number of new lines. Defaults to 1.

log(*objects: Any, sep=' ', end='\n', justify: typing_extensions.Literal[default, left, center, right, full] = None, emoji: bool = None, markup: bool = None, highlight: bool = None, log_locals: bool = False, _stack_offset=1) → None[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”.

  • justify (str, optional) – One of “left”, “right”, “center”, or “full”. Defaults to None.

  • overflow (str, optional) – Overflow method: “crop”, “fold”, or “ellipsis”. 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.

property options

Get default console options.

out(*objects: Any, sep=' ', end='\n', style: Union[str, rich.style.Style] = None, highlight: bool = True) → None[source]

Output to the terminal. This is a low-level way of writing to the terminal which unlike print() doesn’t pretty print, wrap text, nor markup, but will highlighting and apply 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.

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

A context manager to display anything printed within a “pager”. The pager used is defined by the system and will typically support at less pressing a key to scroll.

Parameters
  • pager (Pager, optional) – A pager object, or None to use :class:~rich.pager.SystemPager`. Defaults to None.

  • styles (bool, optional) – Show styles in pager. Defaults to False.

  • links (bool, optional) – Show links in pager. Defaults to False.

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

pop_render_hook() → None[source]

Pop the last renderhook from the stack.

pop_theme() → None[source]

Remove theme from top of stack, restoring previous theme.

print(*objects: Any, sep=' ', end='\n', style: Union[str, rich.style.Style] = None, justify: typing_extensions.Literal[default, left, center, right, full] = None, overflow: typing_extensions.Literal[fold, crop, ellipsis, ignore] = None, no_wrap: bool = None, emoji: bool = None, markup: bool = None, highlight: bool = None, width: int = None, crop: bool = True, soft_wrap: bool = False) → None[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. Defaults to False.

print_exception(*, width: Optional[int] = 100, extra_lines: int = 3, theme: Optional[str] = None, word_wrap: bool = False, show_locals: bool = False) → None[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 88.

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

push_render_hook(hook: rich.console.RenderHook) → None[source]

Add a new render hook to the stack.

Parameters

hook (RenderHook) – Render hook instance.

push_theme(theme: rich.theme.Theme, *, inherit: bool = True) → None[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.

render(renderable: Union[rich.console.ConsoleRenderable, rich.console.RichCast, str], options: rich.console.ConsoleOptions = None) → Iterable[rich.segment.Segment][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: Union[rich.console.ConsoleRenderable, rich.console.RichCast, str], options: Optional[rich.console.ConsoleOptions] = None, *, style: Optional[rich.style.Style] = None, pad: bool = True) → List[List[rich.segment.Segment]][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.

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

Returns

A list of lines, where a line is a list of Segment objects.

Return type

List[List[Segment]]

render_str(text: str, *, style: Union[str, rich.style.Style] = '', justify: typing_extensions.Literal[default, left, center, right, full] = None, overflow: typing_extensions.Literal[fold, crop, ellipsis, ignore] = None, emoji: bool = None, markup: bool = None, highlighter: Callable[[Union[str, Text]], Text] = None)rich.text.Text[source]

Convert a string to a Text instance. This is 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.

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

Returns

Renderable object.

Return type

ConsoleRenderable

rule(title: Union[str, Text] = '', *, characters: str = '─', style: Union[str, rich.style.Style] = 'rule.line') → None[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 “─”.

save_html(path: str, *, theme: rich.terminal_theme.TerminalTheme = None, clear: bool = True, code_format='<!DOCTYPE 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<html>\n<body>\n <code>\n <pre style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace">{code}</pre>\n </code>\n</body>\n</html>\n', inline_styles: bool = False) → None[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, should contain {foreground} {background} and {code}.

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

save_text(path: str, *, clear: bool = True, styles: bool = False) → None[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.

show_cursor(show: bool = True) → None[source]

Show or hide the cursor.

Parameters

show (bool, optional) – Set visibility of the cursor.

property size

Get the size of the console.

Returns

A named tuple containing the dimensions.

Return type

ConsoleDimensions

use_theme(theme: rich.theme.Theme, *, inherit: bool = True)rich.console.ThemeContext[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

Get the width of the console.

Returns

The width (in characters) of the console.

Return type

int

class rich.console.ConsoleDimensions(width: int, height: int)[source]

Size of the terminal.

property height

The height of the console in lines.

property width

The width of the console in ‘cells’.

class rich.console.ConsoleOptions(legacy_windows: bool, min_width: int, max_width: int, is_terminal: bool, encoding: str, justify: Optional[typing_extensions.Literal[default, left, center, right, full]] = None, overflow: Optional[typing_extensions.Literal[fold, crop, ellipsis, ignore]] = None, no_wrap: Optional[bool] = False)[source]

Options for __rich_console__ method.

property ascii_only

Check if renderables should use ascii only.

encoding: str

Encoding of terminal.

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

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.

update(width: int = None, min_width: int = None, max_width: int = None, justify: typing_extensions.Literal[default, left, center, right, full] = None, overflow: typing_extensions.Literal[fold, crop, ellipsis, ignore] = None, no_wrap: bool = None)rich.console.ConsoleOptions[source]

Update values, return a copy.

class rich.console.ConsoleRenderable(*args, **kwds)[source]

An object that supports the console protocol.

class rich.console.ConsoleThreadLocals(theme_stack: rich.theme.ThemeStack, buffer: List[rich.segment.Segment] = <factory>, buffer_index: int = 0)[source]

Thread local values for Console context.

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

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

class rich.console.RenderGroup(*renderables: Union[rich.console.ConsoleRenderable, rich.console.RichCast, str], fit: bool = 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.RenderHook[source]

Provides hooks in to the render process.

abstract process_renderables(renderables: List[rich.console.ConsoleRenderable]) → List[rich.console.ConsoleRenderable][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.RenderResult

The result of calling a __rich_console__ method.

alias of Iterable[Union[rich.console.ConsoleRenderable, rich.console.RichCast, str, rich.segment.Segment]]

rich.console.RenderableType

A type that may be rendered by Console.

alias of Union[rich.console.ConsoleRenderable, rich.console.RichCast, str]

class rich.console.RichCast(*args, **kwds)[source]

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

class rich.console.ThemeContext(console: rich.console.Console, theme: rich.theme.Theme, inherit: bool = True)[source]

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

rich.console.detect_legacy_windows() → bool[source]

Detect legacy Windows.

rich.console.render_group(fit: bool = True) → Callable[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.