import inspect import os import sys import threading import zlib from abc import ABC, abstractmethod from dataclasses import dataclass, field from datetime import datetime from functools import wraps from getpass import getpass from html import escape from inspect import isclass from itertools import islice from math import ceil from time import monotonic from types import FrameType, ModuleType, TracebackType from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
NamedTuple,
Optional,
TextIO,
Tuple,
Type,
Union,
cast,
)
from rich._null_file import NULL_FILE
if sys.version_info >= (3, 8): from typing import Literal, Protocol, runtime_checkable else: from typing_extensions import (
Literal,
Protocol,
runtime_checkable,
) # pragma: no cover
from . import errors, themes from ._emoji_replace import _emoji_replace from ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT from ._fileno import get_fileno from ._log_render import FormatTimeCallable, LogRender from .align import Align, AlignMethod from .color import ColorSystem, blend_rgb from .control import Control from .emoji import EmojiVariant from .highlighter import NullHighlighter, ReprHighlighter from .markup import render as render_markup from .measure import Measurement, measure_renderables from .pager import Pager, SystemPager from .pretty import Pretty, is_expandable from .protocol import rich_cast from .region import Region from .scope import render_scope from .screen import Screen from .segment import Segment from .style import Style, StyleType from .styled import Styled from .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme from .text import Text, TextType from .theme import Theme, ThemeStack
if TYPE_CHECKING: from ._windows import WindowsConsoleFeatures from .live import Live from .status import Status
class ConsoleDimensions(NamedTuple): """Size of the terminal."""
width: int """The width of the console in 'cells'."""
height: int """The height of the console in lines."""
@dataclass class ConsoleOptions: """Options for __rich_console__ method."""
size: ConsoleDimensions """Size of console."""
legacy_windows: bool """legacy_windows: flag for legacy windows."""
min_width: int """Minimum width of renderable."""
max_width: int """Maximum width of renderable."""
is_terminal: bool """True if the target is a terminal, otherwise False."""
encoding: str """Encoding of terminal."""
max_height: int """Height of container (starts as terminal)"""
justify: Optional[JustifyMethod] = None """Justify value override for renderable."""
overflow: Optional[OverflowMethod] = None """Overflow value override for renderable."""
no_wrap: Optional[bool] = False """Disable wrapping for text."""
highlight: Optional[bool] = None """Highlight override for render_str."""
markup: Optional[bool] = None """Enable markup when rendering strings."""
height: Optional[int] = None
@property def ascii_only(self) -> bool: """Check if renderables should use ascii only.""" returnnot self.encoding.startswith("utf")
def copy(self) -> "ConsoleOptions": """Return a copy of the options.
Returns:
ConsoleOptions: a copy of self. """
options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions)
options.__dict__ = self.__dict__.copy() return options
# A type that may be rendered by Console.
RenderableType = Union[ConsoleRenderable, RichCast, str] """A string or any object that may be rendered by Rich."""
# The result of calling a __rich_console__ method.
RenderResult = Iterable[Union[RenderableType, Segment]]
_null_highlighter = NullHighlighter()
class CaptureError(Exception): """An error in the Capture context manager."""
class NewLine: """A renderable to generate new line(s)"""
def get(self) -> str: """Get the result of the capture.""" if self._result isNone: raise CaptureError( "Capture result is not available until context manager exits."
) return self._result
class ThemeContext: """A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage."""
Args:
renderable (RenderableType, optional): Optional renderable to replace current renderable, orNonefor no change. Defaults to None.
style: (Style, optional): Replacement style, orNonefor no change. Defaults to None. """ if renderables:
self.screen.renderable = (
Group(*renderables) if len(renderables) > 1 else renderables[0]
) if style isnotNone:
self.screen.style = style
self.console.print(self.screen, end="")
def __enter__(self) -> "ScreenContext":
self._changed = self.console.set_alt_screen(True) if self._changed and self.hide_cursor:
self.console.show_cursor(False) return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None: if self._changed:
self.console.set_alt_screen(False) if self.hide_cursor:
self.console.show_cursor(True)
class Group: """Takes a group of renderables and returns a renderable object that renders the group.
Args:
renderables (Iterable[RenderableType]): An iterable of renderable objects.
fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True. """
def group(fit: bool = True) -> Callable[..., Callable[..., Group]]: """A decorator that turns an iterable of renderables in to a group.
Args:
fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True. """
def decorator(
method: Callable[..., Iterable[RenderableType]]
) -> Callable[..., Group]: """Convert a method that returns an iterable of renderables in to a Group."""
_COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()}
@dataclass class ConsoleThreadLocals(threading.local): """Thread local values for Console context."""
theme_stack: ThemeStack
buffer: List[Segment] = field(default_factory=list)
buffer_index: int = 0
class RenderHook(ABC): """Provides hooks in to the render process."""
@abstractmethod def process_renderables(
self, renderables: List[ConsoleRenderable]
) -> List[ConsoleRenderable]: """Called with a list of objects to render.
This method can return a new list of renderables, or modify andreturn the same list.
Args:
renderables (List[ConsoleRenderable]): A number of renderable objects.
Returns:
List[ConsoleRenderable]: A replacement list of renderables. """
def get_windows_console_features() -> "WindowsConsoleFeatures": # pragma: no cover global _windows_console_features if _windows_console_features isnotNone: return _windows_console_features from ._windows import get_windows_console_features
Args:
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, orNone to auto-detect terminal. Defaults to None.
force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, orNone to auto-detect Jupyter. Defaults to None.
force_interactive (Optional[bool], optional): Enable/disable interactive mode, orNone 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`` isnot 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, orNonefor no style. Defaults to None.
no_color (Optional[bool], optional): Enabled no color mode, orNone 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 :meth:`export_html`, :meth:`export_svg`, and :meth:`export_text`. Defaults to False.
markup (bool, optional): Boolean to enable :ref:`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 :meth:`log` methods. Defaults to True.
log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`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), orNonefor datetime.now.
get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic. """
@property def file(self) -> IO[str]: """Get the file object to write to."""
file = self._file or (sys.stderr if self.stderr else sys.stdout)
file = getattr(file, "rich_proxied_file", file) if file isNone:
file = NULL_FILE return file
@file.setter def file(self, new_file: IO[str]) -> None: """Set a new file object."""
self._file = new_file
@property def _buffer(self) -> List[Segment]: """Get a thread local buffer.""" return self._thread_locals.buffer
@property def _buffer_index(self) -> int: """Get a thread local buffer.""" return self._thread_locals.buffer_index
@_buffer_index.setter def _buffer_index(self, value: int) -> None:
self._thread_locals.buffer_index = value
@property def _theme_stack(self) -> ThemeStack: """Get the thread local theme stack.""" return self._thread_locals.theme_stack
def _detect_color_system(self) -> Optional[ColorSystem]: """Detect color system from env vars.""" if self.is_jupyter: return ColorSystem.TRUECOLOR ifnot self.is_terminal or self.is_dumb_terminal: returnNone if WINDOWS: # pragma: no cover if self.legacy_windows: # pragma: no cover return ColorSystem.WINDOWS
windows_console_features = get_windows_console_features() return (
ColorSystem.TRUECOLOR if windows_console_features.truecolor else ColorSystem.EIGHT_BIT
) else:
color_term = self._environ.get("COLORTERM", "").strip().lower() if color_term in ("truecolor", "24bit"): return ColorSystem.TRUECOLOR
term = self._environ.get("TERM", "").strip().lower()
_term_name, _hyphen, colors = term.rpartition("-")
color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD) return color_system
def _enter_buffer(self) -> None: """Enter in to a buffer context, and buffer all output."""
self._buffer_index += 1
def _exit_buffer(self) -> None: """Leave buffer context, and render content if required."""
self._buffer_index -= 1
self._check_buffer()
def set_live(self, live: "Live") -> None: """Set Live instance. Used by Live context manager.
Args:
live (Live): Live instance using this Console.
Raises:
errors.LiveError: If this Console has a Live context currently active. """ with self._lock: if self._live isnotNone: raise errors.LiveError("Only one live display may be active at once")
self._live = live
def clear_live(self) -> None: """Clear the Live instance.""" with self._lock:
self._live = None
def push_render_hook(self, hook: RenderHook) -> None: """Add a new render hook to the stack.
Args:
hook (RenderHook): Render hook instance. """ with self._lock:
self._render_hooks.append(hook)
def pop_render_hook(self) -> None: """Pop the last renderhook from the stack.""" with self._lock:
self._render_hooks.pop()
def __enter__(self) -> "Console": """Own context manager to enter buffer context."""
self._enter_buffer() return self
def push_theme(self, theme: Theme, *, inherit: bool = True) -> None: """Push a new theme on to the top of the stack, replacing the styles from the previous theme.
Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather
than calling this method directly.
Args:
theme (Theme): A theme instance.
inherit (bool, optional): Inherit existing styles. Defaults to True. """
self._theme_stack.push_theme(theme, inherit=inherit)
def pop_theme(self) -> None: """Remove theme from top of stack, restoring previous theme."""
self._theme_stack.pop_theme()
def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext: """Use a different theme for the duration of the context manager.
Args:
theme (Theme): Theme instance to user.
inherit (bool, optional): Inherit existing console styles. Defaults to True.
if self._color_system isnotNone: return _COLOR_SYSTEMS_NAMES[self._color_system] else: returnNone
@property def encoding(self) -> str: """Get the encoding of the console file, e.g. ``"utf-8"``.
Returns:
str: A standard encoding string. """ return (getattr(self.file, "encoding", "utf-8") or"utf-8").lower()
@property def is_terminal(self) -> bool: """Check if the console is writing to a terminal.
Returns:
bool: Trueif the console writing to a device capable of
understanding terminal codes, otherwise False. """ if self._force_terminal isnotNone: return self._force_terminal
if hasattr(sys.stdin, "__module__") and sys.stdin.__module__.startswith( "idlelib"
): # Return False for Idle which claims to be a tty but can't handle ansi codes returnFalse
if self.is_jupyter: # return False for Jupyter, which may have FORCE_COLOR set returnFalse
# If FORCE_COLOR env var has any value at all, we assume a terminal.
force_color = self._environ.get("FORCE_COLOR") if force_color isnotNone:
self._force_terminal = True returnTrue
isatty: Optional[Callable[[], bool]] = getattr(self.file, "isatty", None) try: returnFalseif isatty isNoneelse isatty() except ValueError: # in some situation (at the end of a pytest run for example) isatty() can raise # ValueError: I/O operation on closed file # return False because we aren't in a terminal anymore returnFalse
streams = _STD_STREAMS_OUTPUT if WINDOWS else _STD_STREAMS for file_descriptor in streams: try:
width, height = os.get_terminal_size(file_descriptor) except (AttributeError, ValueError, OSError): # Probably not a terminal pass else: break
columns = self._environ.get("COLUMNS") if columns isnotNoneand columns.isdigit():
width = int(columns)
lines = self._environ.get("LINES") if lines isnotNoneand lines.isdigit():
height = int(lines)
# get_terminal_size can report 0, 0 if run from pseudo-terminal
width = width or 80
height = height or 25 return ConsoleDimensions(
width - self.legacy_windows if self._width isNoneelse self._width,
height if self._height isNoneelse self._height,
)
@size.setter def size(self, new_size: Tuple[int, int]) -> None: """Set a new size for the terminal.
Args:
new_size (Tuple[int, int]): New width and height. """
width, height = new_size
self._width = width
self._height = height
@property def width(self) -> int: """Get the width of the console.
Returns:
int: The width (in characters) of the console. """ return self.size.width
Args:
height (int): new height. """
self._height = height
def bell(self) -> None: """Play a 'bell' sound (if supported by the terminal)."""
self.control(Control.bell())
def capture(self) -> Capture: """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:
Capture: Context manager with disables writing to the terminal. """
capture = Capture(self) return capture
def pager(
self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False
) -> PagerContext: """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.
Args:
pager (Pager, optional): A pager object, orNone 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())
Args:
home (bool, optional): Also move the cursor to 'home' position. Defaults to True. """ if home:
self.control(Control.clear(), Control.home()) else:
self.control(Control.clear())
def status(
self,
status: RenderableType,
*,
spinner: str = "dots",
spinner_style: StyleType = "status.spinner",
speed: float = 1.0,
refresh_per_second: float = 12.5,
) -> "Status": """Display a status and spinner.
Args:
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:
Status: A Status object that may be used as a context manager. """ from .status import Status
Note, if you enable this mode, you should ensure that is disabled before
the application exits. See :meth:`~rich.Console.screen` for a context manager
that handles this for you.
Args:
enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True.
Returns:
bool: Trueif the control codes were written.
@property def is_alt_screen(self) -> bool: """Check if the alt screen was enabled.
Returns:
bool: Trueif the alt screen was enabled, otherwise False. """ return self._is_alt_screen
def set_window_title(self, title: str) -> bool: """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.
Args:
title (str): The new title of the terminal window.
Returns:
bool: Trueif 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. """ if self.is_terminal:
self.control(Control.title(title)) returnTrue returnFalse
Args:
hide_cursor (bool, optional): Also hide the cursor. Defaults to False.
style (Style, optional): Optional style for screen. Defaults to None.
Returns:
~ScreenContext: Context which enables alternate screen on enter, and disables it on exit. """ return ScreenContext(self, hide_cursor=hide_cursor, style=style or"")
def measure(
self, renderable: RenderableType, *, options: Optional[ConsoleOptions] = None
) -> Measurement: """Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains
information regarding the number of characters required to print the renderable.
Args:
renderable (RenderableType): Any renderable or string.
options (Optional[ConsoleOptions], optional): Options to use when measuring, orNone
to use default options. Defaults to None.
Returns:
Measurement: A measurement of the renderable. """
measurement = Measurement.get(self, options or self.options, renderable) return measurement
def render(
self, renderable: RenderableType, options: Optional[ConsoleOptions] = None
) -> Iterable[Segment]: """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.
Args:
renderable (RenderableType): An object supporting the console protocol, or
an object that may be converted to a string.
options (ConsoleOptions, optional): An options object, orNone to use self.options. Defaults to None.
Returns:
Iterable[Segment]: An iterable of segments that may be rendered. """
_options = options or self.options if _options.max_width < 1: # No space to render anything. This prevents potential recursion errors. return
render_iterable: RenderResult
renderable = rich_cast(renderable) if hasattr(renderable, "__rich_console__") andnot isclass(renderable):
render_iterable = renderable.__rich_console__(self, _options) elif isinstance(renderable, str):
text_renderable = self.render_str(
renderable, highlight=_options.highlight, markup=_options.markup
)
render_iterable = text_renderable.__rich_console__(self, _options) else: raise errors.NotRenderableError(
f"Unable to render {renderable!r}; " "A str, Segment or object with __rich_console__ method is required"
)
try:
iter_render = iter(render_iterable) except TypeError: raise errors.NotRenderableError(
f"object {render_iterable!r} is not renderable"
)
_Segment = Segment
_options = _options.reset_height() for render_output in iter_render: if isinstance(render_output, _Segment): yield render_output else: yieldfrom self.render(render_output, _options)
def render_lines(
self,
renderable: RenderableType,
options: Optional[ConsoleOptions] = None,
*,
style: Optional[Style] = None,
pad: bool = True,
new_lines: bool = False,
) -> List[List[Segment]]: """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, orNone 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 "\n" characters at end of lines.
Returns:
List[List[Segment]]: A list of lines, where a line is a list of Segment objects. """ with self._lock:
render_options = options or self.options
_rendered = self.render(renderable, render_options) if style:
_rendered = Segment.apply_style(_rendered, style)
render_height = render_options.height if render_height isnotNone:
render_height = max(0, render_height)
def render_str(
self,
text: str,
*,
style: Union[str, Style] = "",
justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None,
emoji: Optional[bool] = None,
markup: Optional[bool] = None,
highlight: Optional[bool] = None,
highlighter: Optional[HighlighterType] = None,
) -> "Text": """Convert a string to a Text instance. This is called automatically if
you print or log a string.
Args:
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:
ConsoleRenderable: Renderable object.
"""
emoji_enabled = emoji or (emoji isNoneand self._emoji)
markup_enabled = markup or (markup isNoneand self._markup)
highlight_enabled = highlight or (highlight isNoneand self._highlight)
_highlighter = (highlighter or self.highlighter) if highlight_enabled elseNone if _highlighter isnotNone:
highlight_text = _highlighter(str(rich_text))
highlight_text.copy_styles(rich_text) return highlight_text
return rich_text
def get_style(
self, name: Union[str, Style], *, default: Optional[Union[Style, str]] = None
) -> Style: """Get a Style instance by its theme name or parse a definition.
Args:
name (str): The name of a style or a style definition.
Returns:
Style: A Style object.
Raises:
MissingStyle: If no style could be parsed from name.
""" if isinstance(name, Style): return name
try:
style = self._theme_stack.get(name) if style isNone:
style = Style.parse(name) return style.copy() if style.link else style except errors.StyleSyntaxError as error: if default isnotNone: return self.get_style(default) raise errors.MissingStyle(
f"Failed to get style {name!r}; {error}"
) fromNone
def _collect_renderables(
self,
objects: Iterable[Any],
sep: str,
end: str,
*,
justify: Optional[JustifyMethod] = None,
emoji: Optional[bool] = None,
markup: Optional[bool] = None,
highlight: Optional[bool] = None,
) -> List[ConsoleRenderable]: """Combine a number of renderables and text into one renderable.
Args:
objects (Iterable[Any]): Anything that Rich can render.
sep (str): String to write between print data.
end (str): String to write at end of print data.
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.
markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.
highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.
Returns:
List[ConsoleRenderable]: A list of things to render. """
renderables: List[ConsoleRenderable] = []
_append = renderables.append
text: List[Text] = []
append_text = text.append
append = _append if justify in ("left", "center", "right"):
Args:
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". """ from .rule import Rule
def control(self, *control: Control) -> None: """Insert non-printing control codes.
Args:
control_codes (str): Control codes, such as those that may move the cursor. """ ifnot self.is_dumb_terminal: with self:
self._buffer.extend(_control.segment for _control in control)
def out(
self,
*objects: Any,
sep: str = " ",
end: str = "\n",
style: Optional[Union[str, Style]] = None,
highlight: Optional[bool] = None,
) -> None: """Output to the terminal. This is a low-level way of writing to the terminal which unlike
:meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will
optionally apply highlighting and a basic style.
Args:
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``. """
raw_output: str = sep.join(str(_object) for _object in objects)
self.print(
raw_output,
style=style,
highlight=highlight,
emoji=False,
markup=False,
no_wrap=True,
overflow="ignore",
crop=False,
end=end,
)
Args:
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``. """ ifnot objects:
objects = (NewLine(),)
if soft_wrap isNone:
soft_wrap = self.soft_wrap if soft_wrap: if no_wrap isNone:
no_wrap = True if overflow isNone:
overflow = "ignore"
crop = False
render_hooks = self._render_hooks[:] with self:
renderables = self._collect_renderables(
objects,
sep,
end,
justify=justify,
emoji=emoji,
markup=markup,
highlight=highlight,
) for hook in render_hooks:
renderables = hook.process_renderables(renderables)
render_options = self.options.update(
justify=justify,
overflow=overflow,
width=min(width, self.width) if width isnotNoneelse NO_CHANGE,
height=height,
no_wrap=no_wrap,
markup=markup,
highlight=highlight,
)
new_segments: List[Segment] = []
extend = new_segments.extend
render = self.render if style isNone: for renderable in renderables:
extend(render(renderable, render_options)) else: for renderable in renderables:
extend(
Segment.apply_style(
render(renderable, render_options), self.get_style(style)
)
) if new_line_start: if (
len("".join(segment.text for segment in new_segments).splitlines())
> 1
):
new_segments.insert(0, Segment.line()) if crop:
buffer_extend = self._buffer.extend for line in Segment.split_and_crop_lines(
new_segments, self.width, pad=False
):
buffer_extend(line) else:
self._buffer.extend(new_segments)
Args:
json (Optional[str]): A string containing JSON.
data (Any): If json isnot 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. """ from rich.json import JSON
if json isNone:
json_renderable = JSON.from_data(
data,
indent=indent,
highlight=highlight,
skip_keys=skip_keys,
ensure_ascii=ensure_ascii,
check_circular=check_circular,
allow_nan=allow_nan,
default=default,
sort_keys=sort_keys,
) else: ifnot isinstance(json, str): raise TypeError(
f"json must be str. Did you mean print_json(data={json!r}) ?"
)
json_renderable = JSON(
json,
indent=indent,
highlight=highlight,
skip_keys=skip_keys,
ensure_ascii=ensure_ascii,
check_circular=check_circular,
allow_nan=allow_nan,
default=default,
sort_keys=sort_keys,
)
self.print(json_renderable, soft_wrap=True)
def update_screen(
self,
renderable: RenderableType,
*,
region: Optional[Region] = None,
options: Optional[ConsoleOptions] = None,
) -> None: """Update the screen at a given offset.
Args:
renderable (RenderableType): A Rich renderable.
region (Region, optional): Region of screen to update, orNonefor entire screen. Defaults to None.
x (int, optional): x offset. Defaults to 0.
y (int, optional): y offset. Defaults to 0.
Raises:
errors.NoAltScreen: If the Console isn't in alt screen mode.
""" ifnot self.is_alt_screen: raise errors.NoAltScreen("Alt screen must be enabled to call update_screen")
render_options = options or self.options if region isNone:
x = y = 0
render_options = render_options.update_dimensions(
render_options.max_width, render_options.height or self.height
) else:
x, y, width, height = region
--> --------------------
--> maximum size reached
--> --------------------
Messung V0.5
¤ Dauer der Verarbeitung: 0.46 Sekunden
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.