### Basic Logging Setup with RichHandler Source: https://rich.readthedocs.io/en/stable/_modules/rich/logging.html Demonstrates how to configure Python's logging to use RichHandler for improved output. Includes examples of various log levels and messages. ```python import logging from time import sleep from rich.logging import RichHandler FORMAT = "%( message)s" # FORMAT = "%( asctime) -15s - %(levelname)s - %(message)s" logging.basicConfig( level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)] ) log = logging.getLogger("rich") log.info("Server starting...") log.info("Listening on http://127.0.0.1:8080") sleep(1) log.info("GET /index.html 200 1298") log.info("GET /imgs/backgrounds/back1.jpg 200 54386") log.info("GET /css/styles.css 200 54386") log.warning("GET /favicon.ico 404 242") sleep(1) log.debug( "JSONRPC request\n--> %r\n<-- %r", { "version": "1.1", "method": "confirmFruitPurchase", "params": [["apple", "orange", "mangoes", "pomelo"], 1.123], "id": "194521489", }, {"version": "1.1", "result": True, "error": None, "id": "194521489"}, ) log.debug( "Loading configuration file /adasd/asdasd/qeqwe/qwrqwrqwr/sdgsdgsdg/werwerwer/dfgerert/ertertert/ertetert/werwerwer" ) log.error("Unable to find 'pomelo' in database!") log.info("POST /jsonrpc/ 200 65532") log.info("POST /admin/ 401 42234") log.warning("password was rejected for admin site.") def divide() -> None: number = 1 divisor = 0 foos = ["foo"] * 100 log.debug("in divide") try: number / divisor except: log.exception("An error of some kind occurred!") divide() sleep(1) log.critical("Out of memory!") log.info("Server exited with code=-1") log.info("[bold]EXITING...[/bold]", extra=dict(markup=True)) ``` -------------------------------- ### Run Pretty Printing Example Source: https://rich.readthedocs.io/en/stable/pretty.html Execute this command to see an example of Rich's pretty printed output for containers. ```bash python -m rich.pretty ``` -------------------------------- ### Start Live Display Source: https://rich.readthedocs.io/en/stable/reference/live.html Manually start the live rendering display. The `refresh` parameter can be set to True to also refresh the display upon starting. ```python from rich.live import Live live = Live() live.start() live.start(refresh=True) ``` -------------------------------- ### start Source: https://rich.readthedocs.io/en/stable/reference/progress.html Starts the overall progress display. ```APIDOC ## start ### Description Start the progress display. ### Returns None ``` -------------------------------- ### Run Console Markup Examples Source: https://rich.readthedocs.io/en/stable/markup.html Execute this command in your terminal to see various console markup examples in action. ```bash python -m rich.markup ``` -------------------------------- ### Live Display Example Source: https://rich.readthedocs.io/en/stable/_modules/rich/live.html This example demonstrates a basic live display that updates a renderable periodically. It requires importing the `Live` class and a renderable object. The `Live` object is used as a context manager. ```python from rich.live import Live from rich.table import Table table = Table() table.add_column("ID", style="dim", width=6) table.add_column("Name") table.add_column("Value", justify="right") with Live(table, refresh_per_second=4, transient=True) as live: for i in range(10): table.add_row(str(i), f"Name {i}", f"{i*100}") live.update(table) # time.sleep(0.5) # Simulate work ``` -------------------------------- ### Live.start Source: https://rich.readthedocs.io/en/stable/_modules/rich/live.html Starts the live rendering display. If auto-refresh is enabled, the display will begin updating automatically. You can optionally trigger an initial refresh upon starting. ```APIDOC ## Live.start ### Description Start live rendering display. ### Parameters * **refresh** (bool, optional): Also refresh. Defaults to False. ### Method start ``` -------------------------------- ### Start and Stop Live Display Source: https://rich.readthedocs.io/en/stable/_modules/rich/live.html Demonstrates the basic usage of starting and stopping a live display. The `Live` context manager ensures that the display is properly stopped even if errors occur. ```python from rich.live import Live from rich.panel import Panel with Live(Panel("Hello world")) as live: # Update the panel content live.update(Panel("Hello again")) # The display will be stopped automatically when exiting the 'with' block ``` -------------------------------- ### Run Rich Repr Protocol Example Source: https://rich.readthedocs.io/en/stable/_sources/pretty.rst.txt Execute this command to see an example of how Rich can format custom objects using the Rich repr protocol. ```bash python -m rich.repr ``` -------------------------------- ### Install Rich Source: https://rich.readthedocs.io/en/stable/_sources/introduction.rst.txt Install Rich using pip. Use the -U flag to update if already installed. ```bash pip install rich ``` -------------------------------- ### Basic ProgressBar Usage Example Source: https://rich.readthedocs.io/en/stable/_modules/rich/progress_bar.html Demonstrates how to create and update a ProgressBar to visually represent progress. This example shows updating the bar in a loop and printing it to the console. ```python if __name__ == "__main__": console = Console() bar = ProgressBar(width=50, total=100) import time console.show_cursor(False) for n in range(0, 101, 1): bar.update(n) console.print(bar) console.file.write("\r") time.sleep(0.05) console.show_cursor(True) console.print() ``` -------------------------------- ### Run prompt examples via CLI Source: https://rich.readthedocs.io/en/stable/_sources/prompt.rst.txt Execute the built-in prompt demonstration script from the command line. ```bash python -m rich.prompt ``` -------------------------------- ### Install Pretty Printing Source: https://rich.readthedocs.io/en/stable/_modules/rich/pretty.html Installs pretty printing for the console. This function can be called with optional arguments to customize the output. ```python from rich import pretty pretty.install() console.print(my_object) ``` -------------------------------- ### Install Global Traceback Handler Source: https://rich.readthedocs.io/en/stable/_sources/traceback.rst.txt Import and call the install function to set Rich as the default handler for uncaught exceptions. Configure with show_locals=True to display local variables. ```python from rich.traceback import install install(show_locals=True) ``` -------------------------------- ### Live Rendering Example with Dynamic Data Source: https://rich.readthedocs.io/en/stable/_modules/rich/live.html Demonstrates live updating of exchange rates in a table. This example showcases how to use the Live context manager to refresh terminal output dynamically. It includes random data generation and logging of other renderables to the console. ```python import random import time from itertools import cycle from typing import Dict, List, Tuple from rich.align import Align from rich.console import Console from rich.live import Live from rich.panel import Panel from rich.rule import Rule from rich.syntax import Syntax from rich.table import Table console = Console() syntax = Syntax( '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: """Iterate and generate a tuple with a flag for last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return for value in iter_values: yield False, previous_value previous_value = value yield True, previous_value''', "python", line_numbers=True, ) table = Table("foo", "bar", "baz") table.add_row("1", "2", "3") progress_renderables = [ "You can make the terminal shorter and taller to see the live table hide" "Text may be printed while the progress bars are rendering.", Panel("In fact, [i]any[/i] renderable will work"), "Such as [magenta]tables[/]...", table, "Pretty printed structures...", {"type": "example", "text": "Pretty printed"}, "Syntax...", syntax, Rule("Give it a try!"), ] examples = cycle(progress_renderables) exchanges = [ "SGD", "MYR", "EUR", "USD", "AUD", "JPY", "CNH", "HKD", "CAD", "INR", "DKK", "GBP", "RUB", "NZD", "MXN", "IDR", "TWD", "THB", "VND", ] with Live(console=console) as live_table: exchange_rate_dict: Dict[Tuple[str, str], float] = {} for index in range(100): select_exchange = exchanges[index % len(exchanges)] for exchange in exchanges: if exchange == select_exchange: continue time.sleep(0.4) if random.randint(0, 10) < 1: console.log(next(examples)) exchange_rate_dict[(select_exchange, exchange)] = 200 / ( (random.random() * 320) + 1 ) if len(exchange_rate_dict) > len(exchanges) - 1: exchange_rate_dict.pop(list(exchange_rate_dict.keys())[0]) table = Table(title="Exchange Rates") table.add_column("Source Currency") table.add_column("Destination Currency") table.add_column("Exchange Rate") ``` -------------------------------- ### Run Rich Demo Source: https://rich.readthedocs.io/en/stable/introduction.html Verify Rich installation and explore its capabilities by running the demo module from the command line. ```bash python -m rich ``` -------------------------------- ### Live.is_started Source: https://rich.readthedocs.io/en/stable/_modules/rich/live.html A property that returns True if the live display has been started, and False otherwise. ```APIDOC ## Live.is_started ### Description Check if live display has been started. ### Method is_started ``` -------------------------------- ### Create a Rich Panel Source: https://rich.readthedocs.io/en/stable/_sources/introduction.rst.txt Example of creating a Rich Panel renderable with styling and text content. ```python from rich.panel import Panel Panel.fit("[bold yellow]Hi, I'm a Panel", border_style="red") ``` -------------------------------- ### Demonstrate Console Justification Source: https://rich.readthedocs.io/en/stable/_modules/rich/text.html Example usage of Rich Console to print text with different justification settings. ```python if __name__ == "__main__": # pragma: no cover from rich.console import Console text = Text( ""\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n""" ) text.highlight_words(["Lorem"], "bold") text.highlight_words(["ipsum"], "italic") console = Console() console.rule("justify='left'") console.print(text, style="red") console.print() console.rule("justify='center'") console.print(text, style="green", justify="center") console.print() console.rule("justify='right'") console.print(text, style="blue", justify="right") console.print() console.rule("justify='full'") console.print(text, style="magenta", justify="full") console.print() ``` -------------------------------- ### Progress.start Source: https://rich.readthedocs.io/en/stable/_modules/rich/progress.html Starts the progress display. This method should be called before any tasks are added or tracked. ```APIDOC ## Progress.start ### Description Starts the progress display. This method should be called before any tasks are added or tracked. ### Method None (This is a method call, not an HTTP endpoint) ### Endpoint None ``` -------------------------------- ### rich.pretty.install Source: https://rich.readthedocs.io/en/stable/reference/pretty.html Installs automatic pretty printing for the Python REPL, allowing objects to be displayed in a formatted way by default. ```APIDOC ## rich.pretty.install ### Description Install automatic pretty printing in the Python REPL. ### Parameters * **console** (Console, optional) – Console instance or `None` to use global console. Defaults to None. * **overflow** (Optional[OverflowMethod], optional) – Overflow method. Defaults to “ignore”. * **crop** (Optional[bool], optional) – Enable cropping of long lines. Defaults to False. * **indent_guides** (bool, optional) – Enable indentation guides. Defaults to False. * **max_length** (int, optional) – Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to None. * **max_string** (int, optional) – Maximum length of string before truncating, or None to disable. Defaults to None. * **max_depth** (int, optional) – Maximum depth of nested data structures, or None for no maximum. Defaults to None. * **expand_all** (bool, optional) – Expand all containers. Defaults to False. * **max_frames** (int) – Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. ### Return type None ``` -------------------------------- ### Running Console Markup Examples Source: https://rich.readthedocs.io/en/stable/_sources/markup.rst.txt Command to execute a Python module that demonstrates various console markup features. ```bash python -m rich.markup ``` -------------------------------- ### Run Live Display Demonstration Source: https://rich.readthedocs.io/en/stable/_sources/live.rst.txt Execute the built-in demonstration of the Live class via the command line. ```bash python -m rich.live ``` -------------------------------- ### Get syntax segments Source: https://rich.readthedocs.io/en/stable/_modules/rich/syntax.html Generates the segments for the syntax object, handling code width, indentation guides, and background transparency. ```python def _get_syntax( self, console: Console, options: ConsoleOptions, ) -> Iterable[Segment]: """ Get the Segments for the Syntax object, excluding any vertical/horizontal padding """ transparent_background = self._get_base_style().transparent_background _pad_top, pad_right, _pad_bottom, pad_left = self.padding horizontal_padding = pad_left + pad_right code_width = ( ( (options.max_width - self._numbers_column_width - 1) if self.line_numbers else options.max_width ) - horizontal_padding if self.code_width is None else self.code_width ) code_width = max(0, code_width) ends_on_nl, processed_code = self._process_code(self.code) text = self.highlight(processed_code, self.line_range) if not self.line_numbers and not self.word_wrap and not self.line_range: if not ends_on_nl: text.remove_suffix("\n") # Simple case of just rendering text style = ( self._get_base_style() + self._theme.get_style_for_token(Comment) + Style(dim=True) + self.background_style ) if self.indent_guides and not options.ascii_only: text = text.with_indent_guides(self.tab_size, style=style) text.overflow = "crop" if style.transparent_background: yield from console.render( text, options=options.update(width=code_width) ) else: ``` -------------------------------- ### Run progress display demo Source: https://rich.readthedocs.io/en/stable/_sources/progress.rst.txt Execute the built-in progress display demonstration from the command line. ```bash python -m rich.progress ``` -------------------------------- ### Install Rich with Jupyter Support Source: https://rich.readthedocs.io/en/stable/_sources/introduction.rst.txt Install Rich with additional dependencies for Jupyter notebook integration. ```bash pip install "rich[jupyter]" ``` -------------------------------- ### Run Live Display Demo Source: https://rich.readthedocs.io/en/stable/live.html Demonstrates the live display functionality by running a Rich module from the command line. ```bash python -m rich.live ``` -------------------------------- ### Run Rich Layout Example Source: https://rich.readthedocs.io/en/stable/layout.html Execute the layout module from the command line to see a demonstration of the Rich Layout class. ```bash python -m rich.layout ``` -------------------------------- ### Get Layout by Name Source: https://rich.readthedocs.io/en/stable/_modules/rich/layout.html Retrieve a specific layout by its name using the get method. Returns None if not found. ```python def get(self, name: str) -> Optional["Layout"]: """Get a named layout, or None if it doesn't exist. Args: name (str): Name of layout. Returns: Optional[Layout]: Layout instance or None if no layout was found. """ if self.name == name: return self else: for child in self._children: named_layout = child.get(name) if named_layout is not None: return named_layout return None ``` -------------------------------- ### Basic Prompt Example Source: https://rich.readthedocs.io/en/stable/_modules/rich/prompt.html Demonstrates how to create and use a basic string prompt. The prompt will display the provided text and return the user's input as a string. ```python from rich.prompt import Prompt console = Console() name = Prompt.get_input(console, "What is your name? ", password=False) console.print(f"Hello {name}") ``` -------------------------------- ### Starting a Task Manually Source: https://rich.readthedocs.io/en/stable/reference/progress.html Manually start a task if it was initially added with `start=False`. This is necessary for accurate elapsed time calculation. ```python progress.start_task(task_id) ``` -------------------------------- ### Task Elapsed Time Source: https://rich.readthedocs.io/en/stable/_modules/rich/progress.html Calculates the time elapsed since a task started. Returns None if the task hasn't started. ```python if self.start_time is None: return None if self.stop_time is not None: return self.stop_time - self.start_time return self.get_time() - self.start_time ``` -------------------------------- ### Table Construction and Layout Demonstration Source: https://rich.readthedocs.io/en/stable/_modules/rich/table.html Demonstrates creating a Table, adding columns and rows, and modifying layout properties like width, expansion, and row styles. ```python if __name__ == "__main__": # pragma: no cover from rich.console import Console from rich.highlighter import ReprHighlighter from ._timer import timer with timer("Table render"): table = Table( title="Star Wars Movies", caption="Rich example table", caption_justify="right", ) table.add_column( "Released", header_style="bright_cyan", style="cyan", no_wrap=True ) table.add_column("Title", style="magenta") table.add_column("Box Office", justify="right", style="green") table.add_row( "Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690", ) table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347") table.add_row( "Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889", style="on black", end_section=True, ) table.add_row( "Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889", ) def header(text: str) -> None: console.print() console.rule(highlight(text)) console.print() console = Console() highlight = ReprHighlighter() header("Example Table") console.print(table, justify="center") table.expand = True header("expand=True") console.print(table) table.width = 50 header("width=50") console.print(table, justify="center") table.width = None table.expand = False table.row_styles = ["dim", "none"] header("row_styles=['dim', 'none']") console.print(table, justify="center") table.width = None table.expand = False table.row_styles = ["dim", "none"] table.leading = 1 ``` -------------------------------- ### Start Status Animation Source: https://rich.readthedocs.io/en/stable/reference/status.html Call the start() method on a Status object to begin the spinner animation. This method does not return any value. ```python start() ``` -------------------------------- ### Start a Rich Progress Task Source: https://rich.readthedocs.io/en/stable/_modules/rich/progress.html Starts a task, which is used for calculating elapsed time. This method can be called manually if `add_task` was used with `start=False`. ```python def start_task(self, task_id: TaskID) -> None: """Start a task. Starts a task (used when calculating elapsed time). You may need to call this manually, if you called ``add_task`` with ``start=False``. Args: task_id (TaskID): ID of task. """ with self._lock: task = self._tasks[task_id] if task.start_time is None: task.start_time = self.get_time() ``` -------------------------------- ### Run Rich Prompt Example from Command Line Source: https://rich.readthedocs.io/en/stable/prompt.html Execute a module directly from the command line to see various Rich prompts in action. This is a convenient way to test the interactive features. ```bash python -m rich.prompt ``` -------------------------------- ### Apply Indent Guides Source: https://rich.readthedocs.io/en/stable/_modules/rich/text.html Adds visual guide characters to indented text blocks. Requires the text to be processed as a Rich Text object. ```python def with_indent_guides( self, indent_size: Optional[int] = None, *, character: str = "│", style: StyleType = "dim green", ) -> "Text": """Adds indent guide lines to text. Args: indent_size (Optional[int]): Size of indentation, or None to auto detect. Defaults to None. character (str, optional): Character to use for indentation. Defaults to "│". style (Union[Style, str], optional): Style of indent guides. Returns: Text: New text with indentation guides. """ _indent_size = self.detect_indentation() if indent_size is None else indent_size text = self.copy() text.expand_tabs() indent_line = f"{character}{' ' * (_indent_size - 1)}" re_indent = re.compile(r"^( *)(.*)$") new_lines: List[Text] = [] add_line = new_lines.append blank_lines = 0 for line in text.split(allow_blank=True): match = re_indent.match(line.plain) if not match or not match.group(2): blank_lines += 1 continue indent = match.group(1) full_indents, remaining_space = divmod(len(indent), _indent_size) new_indent = f"{indent_line * full_indents}{' ' * remaining_space}" line.plain = new_indent + line.plain[len(new_indent) :] line.stylize(style, 0, len(new_indent)) if blank_lines: new_lines.extend([Text(new_indent, style=style)] * blank_lines) blank_lines = 0 add_line(line) if blank_lines: new_lines.extend([Text("", style=style)] * blank_lines) new_text = text.blank_copy("\n").join(new_lines) return new_text ``` -------------------------------- ### Basic Progress Bar Setup Source: https://rich.readthedocs.io/en/stable/_modules/rich/progress.html This snippet demonstrates how to set up a basic progress bar with default columns (description, bar, task progress, time remaining). It yields control to the progress bar context manager. ```python columns: List["ProgressColumn"] = ( [TextColumn("[progress.description]{task.description}")] if description else [] ) columns.extend( ( BarColumn( style=style, complete_style=complete_style, finished_style=finished_style, pulse_style=pulse_style, ), TaskProgressColumn(show_speed=show_speed), TimeRemainingColumn(elapsed_when_finished=True), ) ) progress = Progress( *columns, auto_refresh=auto_refresh, console=console, transient=transient, get_time=get_time, refresh_per_second=refresh_per_second or 10, disable=disable, ) with progress: yield from progress.track( sequence, total=total, completed=completed, description=description, update_period=update_period, ) ``` -------------------------------- ### Start and Stop Status Animation Source: https://rich.readthedocs.io/en/stable/_modules/rich/status.html Control the visibility and animation of the status indicator. `start` begins the display, and `stop` ends it. Can be used as a context manager. ```python def start(self) -> None: """Start the status animation.""" self._live.start() ``` ```python def stop(self) -> None: """Stop the spinner animation.""" self._live.stop() ``` ```python def __enter__(self) -> "Status": self.start() return self ``` ```python def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.stop() ``` -------------------------------- ### Construct Tables with Columns Source: https://rich.readthedocs.io/en/stable/_sources/tables.rst.txt Demonstrates different ways to define columns during table initialization. ```python table = Table("Released", "Title", "Box Office", title="Star Wars Movies") ``` ```python from rich.table import Column, Table table = Table( "Released", "Title", Column(header="Box Office", justify="right"), title="Star Wars Movies" ) ``` -------------------------------- ### Install Rich Traceback Handler Source: https://rich.readthedocs.io/en/stable/_modules/rich/traceback.html Installs the rich traceback handler, which provides enhanced, syntax-highlighted tracebacks. This function replaces the default Python exception hook. ```APIDOC ## POST /install ### Description Installs a rich traceback handler. Once installed, any tracebacks will be printed with syntax highlighting and rich formatting. ### Method POST ### Endpoint /install ### Parameters #### Query Parameters - **console** (Optional[Console]) - Optional - Console to write exception to. Default uses internal Console instance. - **width** (Optional[int]) - Optional - Width (in characters) of traceback. Defaults to 100. - **code_width** (Optional[int]) - Optional - Code width (in characters) of traceback. Defaults to 88. - **extra_lines** (int) - Optional - Extra lines of code. Defaults to 3. - **theme** (Optional[str]) - Optional - Pygments theme to use in traceback. Defaults to ``None`` which will pick a theme appropriate for the platform. - **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. - **locals_max_length** (int) - Optional - Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10. - **locals_max_string** (int) - Optional - Maximum length of string before truncating, or None to disable. Defaults to 80. - **locals_hide_dunder** (bool) - Optional - Hide locals prefixed with double underscore. Defaults to True. - **locals_hide_sunder** (Optional[bool]) - Optional - Hide locals prefixed with single underscore. Defaults to False. - **indent_guides** (bool) - Optional - Enable indent guides in code and locals. Defaults to True. - **suppress** (Iterable[Union[str, ModuleType]]) - Optional - Sequence of modules or paths to exclude from traceback. - **max_frames** (int) - Optional - Maximum number of frames to display. Defaults to 100. ### Returns Callable: The previous exception handler that was replaced. ### Request Example ```python from rich.traceback import install install( show_locals=True, width=120, theme="monokai" ) ``` ### Response #### Success Response (200) - **handler** (Callable) - The previously installed exception handler. #### Response Example ```python # No specific response body, the function returns the previous handler. ``` ``` -------------------------------- ### Install Pretty Printing in Python REPL Source: https://rich.readthedocs.io/en/stable/_modules/rich/pretty.html Installs automatic pretty printing in the Python REPL using sys.displayhook. Supports customization of overflow, indentation, and length limits. ```python from rich import get_console console = console or get_console() assert console is not None def display_hook(value: Any) -> None: """Replacement sys.displayhook which prettifies objects with Rich.""" if value is not None: assert console is not None builtins._ = None # type: ignore[attr-defined] console.print( ( value if _safe_isinstance(value, RichRenderable) else Pretty( value, overflow=overflow, indent_guides=indent_guides, max_length=max_length, max_string=max_string, max_depth=max_depth, expand_all=expand_all, ) ), crop=crop, ) builtins._ = value # type: ignore[attr-defined] try: ip = get_ipython() # type: ignore[name-defined] except NameError: sys.displayhook = display_hook else: from IPython.core.formatters import BaseFormatter class RichFormatter(BaseFormatter): # type: ignore[misc] pprint: bool = True def __call__(self, value: Any) -> Any: if self.pprint: return _ipy_display_hook( value, console=get_console(), overflow=overflow, indent_guides=indent_guides, max_length=max_length, max_string=max_string, max_depth=max_depth, expand_all=expand_all, ) else: return repr(value) # replace plain text formatter with rich formatter rich_formatter = RichFormatter() ip.display_formatter.formatters["text/plain"] = rich_formatter ``` -------------------------------- ### Initialize a Theme Source: https://rich.readthedocs.io/en/stable/_modules/rich/theme.html Create a new Theme instance, optionally with custom styles and inheritance from defaults. Styles can be provided as a dictionary of Style objects or strings that can be parsed into Styles. ```python theme = Theme() print(theme.config) ``` -------------------------------- ### Install Rich Traceback Handler Source: https://rich.readthedocs.io/en/stable/traceback.html Install Rich as the default traceback handler to automatically render uncaught exceptions with highlighting. The `show_locals=True` option includes local variable values. ```python from rich.traceback import install install(show_locals=True) ``` -------------------------------- ### Create Basic Live Display Source: https://rich.readthedocs.io/en/stable/_sources/live.rst.txt Construct a Live object as a context manager to update a renderable over time. ```python import time from rich.live import Live from rich.table import Table table = Table() table.add_column("Row ID") table.add_column("Description") table.add_column("Level") with Live(table, refresh_per_second=4): # update 4 times a second to feel fluid for row in range(12): time.sleep(0.4) # arbitrary delay # update the renderable internally table.add_row(f"{row}", f"description {row}", "[red]ERROR") ``` -------------------------------- ### Basic Panel Usage Source: https://rich.readthedocs.io/en/stable/_modules/rich/panel.html Demonstrates how to create a simple panel with a title and render a string within it. Requires importing the Panel class. ```python from rich.panel import Panel from rich.console import Console console = Console() console.print(Panel("Hello, world!", title="[b]My Panel[/b]", style="bold red")) ``` -------------------------------- ### Run Rich Tree Demonstration Source: https://rich.readthedocs.io/en/stable/_sources/tree.rst.txt Execute this command in your terminal to see a pre-built demonstration of the Rich tree view. ```bash python -m rich.tree ``` -------------------------------- ### Create Style Object and Apply Source: https://rich.readthedocs.io/en/stable/_sources/style.rst.txt Instantiate a Style object directly with color and attributes, then pass it to console.print. ```python from rich.style import Style danger_style = Style(color="red", blink=True, bold=True) console.print("Danger, Will Robinson!", style=danger_style) ``` -------------------------------- ### Console.height Source: https://rich.readthedocs.io/en/stable/_modules/rich/console.html Gets the height of the console in lines. ```APIDOC ## Console.height ### Description Gets the height of the console in lines. ### Returns * **int**: The height of the console. ``` -------------------------------- ### Use External Console with Live Display Source: https://rich.readthedocs.io/en/stable/live.html Demonstrates initializing Live with a pre-existing Console object. Output to this console will appear above the live display. ```python from my_project import my_console with Live(console=my_console) as live: my_console.print("[bold blue]Starting work!") ... ``` -------------------------------- ### height Source: https://rich.readthedocs.io/en/stable/reference/console.html Gets the current height of the console in lines. ```APIDOC ## height ### Description Get the height of the console. ### Property * **height** (_int_) ### Returns The height (in lines) of the console. ### Return type int ``` -------------------------------- ### get_renderable Source: https://rich.readthedocs.io/en/stable/reference/progress.html Gets a renderable object for the progress display. ```APIDOC ## get_renderable ### Description Get a renderable for the progress display. ### Returns A ConsoleRenderable, RichCast, or str. ``` -------------------------------- ### Create sitecustomize.py for Automatic Traceback Source: https://rich.readthedocs.io/en/stable/traceback.html Manually create or modify the `sitecustomize.py` file in your virtual environment's `site-packages` directory to automatically install the Rich traceback handler. ```bash $ touch .venv/lib/python3.9/site-packages/sitecustomize.py ``` -------------------------------- ### padding Source: https://rich.readthedocs.io/en/stable/reference/table.html Property to get the cell padding dimensions. ```APIDOC ## padding ### Description Get cell padding. ### Property padding: Tuple[int, int, int, int] ### Parameters None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) None #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Basic Logging Handler Setup Source: https://rich.readthedocs.io/en/stable/_modules/rich/logging.html Instantiate a Rich handler and add it to the root logger. This handler will format log messages using Rich's capabilities. ```python from rich.logging import RichHandler import logging logging.basicConfig( level="INFO", format="%(message)s", datefmt="[%X]", handlers=[RichHandler()] ) log = logging.getLogger("rich.logging") log.info("Hello, world!") log.error("This is an error message") log.warning("This is a warning message") ``` -------------------------------- ### Console Width Property Source: https://rich.readthedocs.io/en/stable/reference/console.html Get the width of the console in characters. ```APIDOC ## Console Width Property ### Description Get the width of the console. ### Returns The width (in characters) of the console. ### Return type int ``` -------------------------------- ### Live Display with get_renderable Source: https://rich.readthedocs.io/en/stable/_modules/rich/live.html This example uses the `get_renderable` callable to dynamically fetch the renderable content. This is useful when the content changes frequently and you don't want to manually call `update` or `refresh`. ```python import time from rich.live import Live from rich.text import Text def get_text() -> Text: return Text(f"Current time: {time.time():.2f}") with Live(get_renderable=get_text, auto_refresh=True, refresh_per_second=1) as live: time.sleep(5) # Let it update for 5 seconds ``` -------------------------------- ### encoding Source: https://rich.readthedocs.io/en/stable/reference/console.html Gets the encoding of the console file, typically 'utf-8'. ```APIDOC ## encoding ### Description Get the encoding of the console file, e.g. "utf-8". ### Returns A standard encoding string. ### Return type str ``` -------------------------------- ### Render a basic table with Rich Source: https://rich.readthedocs.io/en/stable/_sources/tables.rst.txt Construct a Table object, define columns, add rows, and print to the console. ```python from rich.console import Console from rich.table import Table table = Table(title="Star Wars Movies") table.add_column("Released", justify="right", style="cyan", no_wrap=True) table.add_column("Title", style="magenta") table.add_column("Box Office", justify="right", style="green") table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690") table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347") table.add_row("Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889") table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889") console = Console() console.print(table) ``` -------------------------------- ### Syntax Highlighting from Path Source: https://rich.readthedocs.io/en/stable/_sources/syntax.rst.txt Use the from_path constructor to load code from disk and auto-detect the file type. ```python from rich.console import Console from rich.syntax import Syntax console = Console() syntax = Syntax.from_path("syntax.py") console.print(syntax) ``` -------------------------------- ### get_renderables Source: https://rich.readthedocs.io/en/stable/reference/progress.html Gets multiple renderable objects for the progress display. ```APIDOC ## get_renderables ### Description Get a number of renderables for the progress display. ### Returns An iterable of ConsoleRenderable, RichCast, or str. ``` -------------------------------- ### row_count Source: https://rich.readthedocs.io/en/stable/reference/table.html Property to get the current number of rows in the table. ```APIDOC ## row_count ### Description Get the current number of rows. ### Property row_count: int ### Parameters None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) None #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Get shape Source: https://rich.readthedocs.io/en/stable/_modules/rich/segment.html Determines the width and height of a list of lines. ```python @classmethod def get_shape(cls, lines: List[List["Segment"]]) -> Tuple[int, int]: """Get the shape (enclosing rectangle) of a list of lines. Args: lines (List[List[Segment]]): A list of lines (no '\\n' characters). Returns: Tuple[int, int]: Width and height in characters. """ get_line_length = cls.get_line_length max_width = max(get_line_length(line) for line in lines) if lines else 0 return (max_width, len(lines)) ``` -------------------------------- ### Initialize Live Display Source: https://rich.readthedocs.io/en/stable/reference/live.html Instantiate the Live class to create an auto-updating display. You can specify the initial renderable, console, refresh rate, and other options. ```python from rich.live import Live from rich.panel import Panel with Live(Panel("Hello world"), refresh_per_second=4, screen=True) as live: # Live display is active here pass # Live display is stopped and screen cleared here ``` -------------------------------- ### measure_renderables Source: https://rich.readthedocs.io/en/stable/_modules/rich/measure.html Get a measurement that would fit a number of renderables. ```APIDOC ## measure_renderables Get a measurement that would fit a number of renderables. Args: console (Console): Console instance. options (ConsoleOptions): Console options. renderables (Sequence[RenderableType]): One or more renderable objects. Returns: Measurement: Measurement object containing range of character widths required to render the objects. ``` -------------------------------- ### Run Rich Progress Demo Source: https://rich.readthedocs.io/en/stable/progress.html Execute the Rich progress display demo from the command line to see its default appearance. ```bash python -m rich.progress ``` -------------------------------- ### Emoji Module Example Usage Source: https://rich.readthedocs.io/en/stable/_modules/rich/emoji.html An example demonstrating the usage of the Emoji class and the EMOJI dictionary within the rich.emoji module. It prints a sorted list of available emoji names to the console, optionally saving the output to an HTML file if a filename is provided as a command-line argument. ```python import sys from rich.columns import Columns from rich.console import Console from ._emoji_codes import EMOJI console = Console(record=True) columns = Columns( (f":{name}: {name}" for name in sorted(EMOJI.keys()) if "\u200D" not in name), column_first=True, ) console.print(columns) if len(sys.argv) > 1: console.save_html(sys.argv[1]) ``` -------------------------------- ### Create a Basic Panel Source: https://rich.readthedocs.io/en/stable/panel.html Construct a Panel with a renderable as the first argument to draw a border around it. This example shows a simple panel with text. ```python from rich import print from rich.panel import Panel print(Panel("Hello, [red]World!")) ``` -------------------------------- ### Get Measurement for Renderable Source: https://rich.readthedocs.io/en/stable/_modules/rich/measure.html Calculates the measurement for a given renderable object. ```python @classmethod def get( cls, console: "Console", options: "ConsoleOptions", renderable: "RenderableType", ) -> "Measurement": """Get a measurement for a renderable. Args: console (~rich.console.Console): Console instance. options (~rich.console.ConsoleOptions): Console options. renderable (RenderableType): An object that may be rendered with Rich. Raises: errors.NotRenderableError: If the object is not renderable. Returns: Measurement: Measurement object containing range of character widths required to render the object. """ _max_width = options.max_width if _max_width < 1: return Measurement(0, 0) if isinstance(renderable, str): renderable = console.render_str( renderable, markup=options.markup, highlight=False ) renderable = rich_cast(renderable) if is_renderable(renderable): get_console_width: Optional[ Callable[[Console, ConsoleOptions], "Measurement"] ] = getattr(renderable, "__rich_measure__", None) if get_console_width is not None: render_width = ( get_console_width(console, options) .normalize() .with_maximum(_max_width) ) if render_width.maximum < 1: return Measurement(0, 0) return render_width.normalize() else: return Measurement(0, _max_width) else: raise errors.NotRenderableError( f"Unable to get render width for {renderable!r}; " "a str, Segment, or object with __rich_console__ method is required" ) ``` -------------------------------- ### Tree.TREE_GUIDES Source: https://rich.readthedocs.io/en/stable/reference/tree.html Class attribute representing the default guide lines for the tree. ```APIDOC ## Attribute Tree.TREE_GUIDES ### Description Default guide lines. ### Type List[GuideType, GuideType, GuideType] ``` -------------------------------- ### Demonstrate Segment rendering Source: https://rich.readthedocs.io/en/stable/_modules/rich/segment.html Example showing how Rich processes text into segments. ```python if __name__ == "__main__": # pragma: no cover from rich.console import Console from rich.syntax import Syntax from rich.text import Text code = """from rich.console import Console console = Console() text = Text.from_markup("Hello, [bold magenta]World[/]!") console.print(text)""" text = Text.from_markup("Hello, [bold magenta]World[/]!") console = Console() console.rule("rich.Segment") console.print( "A Segment is the last step in the Rich render process before generating text with ANSI codes." ) console.print("\nConsider the following code:\n") console.print(Syntax(code, "python", line_numbers=True)) console.print() console.print( "When you call [b]print()[/b], Rich [i]renders[/i] the object in to the following:\n" ) fragments = list(console.render(text)) console.print(fragments) console.print() console.print("The Segments are then processed to produce the following output:\n") console.print(text) console.print( ``` -------------------------------- ### Basic Table Creation and Rendering Source: https://rich.readthedocs.io/en/stable/tables.html Create a table with a title, add columns with specified alignment and style, and populate it with rows of data. Finally, print the table to the console. ```python from rich.console import Console from rich.table import Table table = Table(title="Star Wars Movies") table.add_column("Released", justify="right", style="cyan", no_wrap=True) table.add_column("Title", style="magenta") table.add_column("Box Office", justify="right", style="green") table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690") table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347") table.add_row("Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889") table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889") console = Console() console.print(table) ``` -------------------------------- ### Rule Rendering Examples Source: https://rich.readthedocs.io/en/stable/_modules/rich/rule.html Shows how the Rule class is rendered in different scenarios. ```APIDOC ## Rule Rendering ### Description This section covers how the `Rule` class is rendered to the console, including its behavior with different options and console states. ### Method __rich_console__ ### Endpoint N/A (This is a class method for rendering) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from rich.console import Console from rich.rule import Rule console = Console() # Default rule console.print(Rule()) # Rule with a title console.print(Rule("Section Title")) # Rule with custom characters and alignment console.print(Rule(title="Data", characters="*", align="left")) # Rule with a specific width (demonstrating truncation) console.print(Rule("Long Title That Will Be Truncated"), width=20) ``` ### Response #### Success Response (200) When rendered, the `Rule` object outputs a horizontal line to the console, optionally with a title. #### Response Example ``` ──────────────────────────────────────── My Section ──────────────────────────────────────── ``` Or with custom characters: ``` ======================================== My Section ======================================== ``` ``` -------------------------------- ### Run Rich Pretty Printing Example Source: https://rich.readthedocs.io/en/stable/_sources/pretty.rst.txt Execute this command in your terminal to observe Rich's default pretty printing behavior for containers. ```bash python -m rich.pretty ``` -------------------------------- ### Array braces Source: https://rich.readthedocs.io/en/stable/_modules/rich/pretty.html Helper function to get the opening and closing braces for an array. ```python def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]: return (f"array({_object.typecode!r}, [", "])", f"array({_object.typecode!r})") ``` -------------------------------- ### Deque braces Source: https://rich.readthedocs.io/en/stable/_modules/rich/pretty.html Helper function to get the opening and closing braces for a deque. ```python def _get_braces_for_deque(_object: Deque[Any]) -> Tuple[str, str, str]: if _object.maxlen is None: return ("deque([", "])", "deque()") return ( "deque([", f"], maxlen={_object.maxlen})", f"deque(maxlen={_object.maxlen})", ) ``` -------------------------------- ### Define and Use Custom Styles Source: https://rich.readthedocs.io/en/stable/style.html Create a custom theme with 'info', 'warning', and 'danger' styles and apply them to console output. Style names must be lowercase and follow specific naming conventions. ```python from rich.console import Console from rich.theme import Theme custom_theme = Theme({ "info": "dim cyan", "warning": "magenta", "danger": "bold red" }) console = Console(theme=custom_custom_theme) console.print("This is information", style="info") console.print("[warning]The pod bay doors are locked[/warning]") console.print("Something terrible happened!", style="danger") ``` -------------------------------- ### Defaultdict braces Source: https://rich.readthedocs.io/en/stable/_modules/rich/pretty.html Helper function to get the opening and closing braces for a defaultdict. ```python def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]: return ( f"defaultdict({_object.default_factory!r}, {{', "))", f"defaultdict({_object.default_factory!r}, {{}})", ) ```