### install() Source: https://github.com/textualize/rich/blob/main/docs/source/reference.rst Installs pretty printing as the default repr for all objects. ```APIDOC ## install() ### Description Installs pretty printing as the default repr for all objects. ### Method install ### Parameters - **console** (Console, optional) - Optional - The console to use. - **max_length** (int, optional) - Optional - Maximum length of the repr. - **max_string** (int, optional) - Optional - Maximum length of strings. ### Returns None ``` -------------------------------- ### Run Layout example Source: https://github.com/textualize/rich/blob/main/docs/source/layout.rst Run this command to see an example of a Layout in the terminal. ```default python -m rich.layout ``` -------------------------------- ### start() Source: https://github.com/textualize/rich/blob/main/docs/source/reference/progress.rst Starts the progress display. ```APIDOC ## start() ### Description Starts the progress display. ### Returns None ``` -------------------------------- ### start(refresh=False) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/live.rst Start live rendering display. ```APIDOC ## start(refresh=False) ### Description Start live rendering display. ### Parameters - **refresh** (bool, optional) - Optional - Also refresh. Defaults to False. ### Returns - **None** ``` -------------------------------- ### Run markup examples command Source: https://github.com/textualize/rich/blob/main/docs/source/markup.rst Run this command to see examples of Rich console markup. ```default python -m rich.markup ``` -------------------------------- ### Run rich.repr example Source: https://github.com/textualize/rich/blob/main/docs/source/pretty.rst Run this command to see an example of what the Rich repr protocol can generate. ```default python -m rich.repr ``` -------------------------------- ### Install documentation dependencies Source: https://github.com/textualize/rich/blob/main/CONTRIBUTING.md Install the required Python packages to build the documentation from the docs directory. ```bash pip install -r requirements.txt ``` -------------------------------- ### Live.start() Source: https://github.com/textualize/rich/blob/main/docs/source/reference.rst Starts the live display. ```APIDOC ## Live.start() ### Description Starts the live display. ### Method start ### Signature `Live.start() -> None` ### Returns - None ### Example ```python from rich.live import Live live = Live() live.start() ``` ``` -------------------------------- ### Install Rich pretty printer in REPL Source: https://github.com/textualize/rich/blob/main/docs/source/introduction.rst Installs Rich's pretty printer in the REPL so Python data structures are automatically pretty printed with syntax highlighting. After installation, the example list is displayed with Rich formatting. ```python >>> from rich import pretty >>> pretty.install() >>> ["Rich and pretty", True] ``` -------------------------------- ### Run Rich traceback example Source: https://github.com/textualize/rich/blob/main/docs/source/traceback.rst Run this command to see an example of a Rich traceback rendered with syntax highlighting and formatting. ```default python -m rich.traceback ``` -------------------------------- ### Install dependencies with Poetry Source: https://github.com/textualize/rich/blob/main/CONTRIBUTING.md Installs the project dependencies into the current virtual environment using Poetry. ```bash poetry install ``` -------------------------------- ### Justify alignment example with print Source: https://github.com/textualize/rich/blob/main/docs/source/console.rst Demonstrates the difference between default, left, center, and right justification using the justify argument. The example sets a background color to show padding differences. ```default from rich.console import Console console = Console(width=20) style = "bold white on blue" console.print("Rich", style=style) console.print("Rich", style=style, justify="left") console.print("Rich", style=style, justify="center") console.print("Rich", style=style, justify="right") ``` -------------------------------- ### Install Rich traceback handler Source: https://github.com/textualize/rich/blob/main/docs/source/traceback.rst Install Rich as the default traceback handler so all uncaught exceptions are rendered with highlighting. See install() for configuration options. ```default from rich.traceback import install install(show_locals=True) ``` -------------------------------- ### Install Rich with pip Source: https://github.com/textualize/rich/blob/main/docs/source/introduction.rst Install Rich from PyPI using pip. Add the -U switch to update if already installed. ```default pip install rich ``` -------------------------------- ### Confirm.ask example Source: https://github.com/textualize/rich/blob/main/docs/source/reference/prompt.rst Shows how to ask a yes/no confirmation prompt using Confirm.ask(). The example checks the returned boolean to conditionally run a job. ```pycon >>> if Confirm.ask("Continue"): run_job() ``` -------------------------------- ### Prompt.ask usage example Source: https://github.com/textualize/rich/blob/main/docs/source/reference/prompt.rst A basic example of using the Prompt.ask method to request a filename from the user. ```pycon >>> filename = Prompt.ask("Enter a filename") ``` -------------------------------- ### Text.with_indent_guides Source: https://github.com/textualize/rich/blob/main/docs/source/reference/text.rst Adds indent guide lines to text. Returns a new Text instance with indentation guides. ```APIDOC ## with_indent_guides(indent_size=None, character='│', style='dim green') ### Description Adds indent guide lines to text. ### Method with_indent_guides ### Parameters - **indent_size** (Optional[int]) - Optional - Size of indentation, or None to auto detect. Defaults to None. - **character** (str, optional) - Optional - Character to use for indentation. Defaults to "│". - **style** (Union[Style, str], optional) - Optional - Style of indent guides. ### Returns New text with indentation guides. ### Return Type Text ``` -------------------------------- ### is_started (property) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/live.rst Check if the live display has been started. ```APIDOC ## is_started (property) ### Description Check if the live display has been started. ### Returns - **bool** - True if the live display has been started, False otherwise. ``` -------------------------------- ### Basic markup example Source: https://github.com/textualize/rich/blob/main/docs/source/markup.rst Shows how to apply a style with a closing tag. ```default from rich import print print("[bold red]alert![/bold red] Something happened") ``` -------------------------------- ### Show progress while reading a file with rich.progress.open Source: https://github.com/textualize/rich/blob/main/docs/source/progress.rst Use rich.progress.open to get a context manager that displays a progress bar while reading a file. Example reads a JSON file and prints the loaded data. ```python import json import rich.progress with rich.progress.open("data.json", "rb") as file: data = json.load(file) print(data) ``` -------------------------------- ### Progress.start_task() Source: https://github.com/textualize/rich/blob/main/docs/source/reference.rst Starts a specific task. ```APIDOC ## Progress.start_task() ### Description Starts a specific task. ### Method start_task ### Parameters - **task_id** (TaskID) - Required - The ID of the task. ### Returns None ``` -------------------------------- ### Run Rich demo Source: https://github.com/textualize/rich/blob/main/docs/source/introduction.rst Verifies the Rich installation and demonstrates its features by running the command-line module. ```default python -m rich ``` -------------------------------- ### rich.traceback.install Source: https://github.com/textualize/rich/blob/main/docs/source/reference/traceback.rst Function to install a rich traceback handler globally. ```APIDOC ## rich.traceback.install(console=None, width=100, code_width=88, extra_lines=3, theme=None, word_wrap=False, show_locals=False, locals_max_length=10, locals_max_string=80, locals_max_depth=None, locals_hide_dunder=True, locals_hide_sunder=None, locals_overflow=None, indent_guides=True, suppress=(), max_frames=100) ### Description Installs a rich traceback handler. Once installed, any tracebacks will be printed with syntax highlighting and rich formatting. ### Parameters - **console** (Optional[Console], optional) - Optional - Console to write exception to. Default uses internal Console instance. - **width** (Optional[int], optional) - Optional - Width (in characters) of traceback. Defaults to 100. - **code_width** (Optional[int], optional) - Optional - Code width (in characters) of traceback. Defaults to 88. - **extra_lines** (int, optional) - Optional - Extra lines of code. Defaults to 3. - **theme** (Optional[str], optional) - Optional - Pygments theme to use in traceback. Defaults to `None` which will pick a theme appropriate for the platform. - **word_wrap** (bool, optional) - Optional - Enable word wrapping of long lines. Defaults to False. - **show_locals** (bool, optional) - Optional - Enable display of local variables. Defaults to False. - **locals_max_length** (int, optional) - Optional - Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10. - **locals_max_string** (int, optional) - Optional - Maximum length of string before truncating, or None to disable. Defaults to 80. - **locals_max_depth** (int, optional) - Optional - Maximum depths of locals before truncating, or None to disable. Defaults to None. - **locals_hide_dunder** (bool, optional) - Optional - Hide locals prefixed with double underscore. Defaults to True. - **locals_hide_sunder** (bool, optional) - Optional - Hide locals prefixed with single underscore. Defaults to False. - **locals_overflow** (OverflowMethod, optional) - Optional - How to handle overflowing locals, or None to disable. Defaults to None. - **indent_guides** (bool, optional) - Optional - Enable indent guides in code and locals. Defaults to True. - **suppress** (Sequence[Union[str, ModuleType]]) - Optional - Optional sequence of modules or paths to exclude from traceback. - **max_frames** (int) - Optional - Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. ### Returns The previous exception handler that was replaced. ### Return Type Callable ``` -------------------------------- ### Install Rich with pip Source: https://github.com/textualize/rich/blob/main/README.md Installs the Rich library using pip. Requires Python 3.8 or later. ```sh python -m pip install rich ``` -------------------------------- ### Status.start() Source: https://github.com/textualize/rich/blob/main/docs/source/reference/status.rst Starts the status animation. ```APIDOC ## Status.start() ### Description Start the status animation. ### Return Type None ``` -------------------------------- ### Assemble Text with styled parts using assemble Source: https://github.com/textualize/rich/blob/main/docs/source/text.rst Combines strings and style pairs into a Text instance using the assemble method. This example is equivalent to the previous ANSI example, producing a Text with 'Hello' in bold magenta and ', World!' plain. ```default text = Text.assemble(("Hello", "bold magenta"), ", World!") console.print(text) ``` -------------------------------- ### Console.log() example with output Source: https://github.com/textualize/rich/blob/main/docs/source/console.rst Example of Console.log() output. Logging adds a timestamp column on the left and the file and line of the call on the right. The output shows the log message with timestamp and source location. ```default >>> console.log("Hello, World!") ``` ```default [16:32:08] Hello, World! :1 ``` -------------------------------- ### Console.print() examples Source: https://github.com/textualize/rich/blob/main/docs/source/console.rst Examples of using Console.print() to output rich content. Rich converts objects to strings via __str__, performs syntax highlighting, pretty-prints containers, and renders Console Markup in strings. ```default console.print([1, 2, 3]) console.print("[blue underline]Looks like a link") console.print(locals()) console.print("FOO", style="white on blue") ``` -------------------------------- ### Create a basic Panel with Rich Source: https://github.com/textualize/rich/blob/main/docs/source/panel.rst Construct a Panel with a renderable as the first positional argument to draw a border around it. The example prints a panel containing the text 'Hello, [red]World!'. ```python from rich import print from rich.panel import Panel print(Panel("Hello, [red]World!")) ``` -------------------------------- ### Output of justify alignment example Source: https://github.com/textualize/rich/blob/main/docs/source/console.rst The output produced by the justify example, showing the alignment differences with background color. ```html
Rich
Rich                
        Rich        
                Rich
``` -------------------------------- ### Install Rich in the Python REPL Source: https://github.com/textualize/rich/blob/main/README.md Installs Rich into the Python REPL so that data structures are pretty printed and highlighted. ```python >>> from rich import pretty >>> pretty.install() ``` -------------------------------- ### Hyperlink markup example Source: https://github.com/textualize/rich/blob/main/docs/source/markup.rst Output a hyperlink with the syntax [link=URL]text[/link]. ```default print("Visit my [link=https://www.willmcgugan.com]blog[/link]!") ``` -------------------------------- ### Import and use pprint Source: https://github.com/textualize/rich/blob/main/docs/source/pretty.rst Import the pprint method and pretty print the local variables. The pprint method enables indent guides by default; set indent_guides=False to disable them. ```default >>> from rich.pretty import pprint >>> pprint(locals()) ``` -------------------------------- ### IntPrompt.ask example Source: https://github.com/textualize/rich/blob/main/docs/source/reference/prompt.rst Shows how to ask for an integer value using IntPrompt.ask(). The result is assigned to a variable. ```pycon >>> burrito_count = IntPrompt.ask("How many burritos do you want to order") ``` -------------------------------- ### Prompt.get_input Source: https://github.com/textualize/rich/blob/main/docs/source/reference/prompt.rst Gets input from the user. ```APIDOC ## Prompt.get_input ### Description Get input from user. ### Parameters - **console** (Console) - Console instance. - **prompt** (TextType) - Prompt text. - **password** (bool) - Enable password entry. - **stream** (TextIO | None) - Optional stream. ### Returns - **str** - String from user. ``` -------------------------------- ### rich.pretty.install Source: https://github.com/textualize/rich/blob/main/docs/source/reference/pretty.rst Install automatic pretty printing in the Python REPL. This function configures the console to use pretty printing for all output. ```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. ### Returns - **None** - This function does not return a value. ``` -------------------------------- ### start_task(task_id) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/progress.rst Starts 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`. ```APIDOC ## start_task(task_id) ### Description Starts 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`. ### Parameters - **task_id** (TaskID) - Required - ID of task. ### Returns None ``` -------------------------------- ### Run rich.pretty module Source: https://github.com/textualize/rich/blob/main/docs/source/pretty.rst Run this command to see an example of pretty printed output. The output will change to fit within the terminal width. ```default python -m rich.pretty ``` -------------------------------- ### Syntax highlighting with Syntax object Source: https://github.com/textualize/rich/blob/main/docs/source/syntax.rst Construct a Syntax object from a string and print it to the console. The example reads a Python file and highlights it as Python. ```python from rich.console import Console from rich.syntax import Syntax console = Console() with open("syntax.py", "rt") as code_file: syntax = Syntax(code_file.read(), "python") console.print(syntax) ``` -------------------------------- ### Prompt.ask example Source: https://github.com/textualize/rich/blob/main/docs/source/reference/prompt.rst Shows how to ask for a string value using Prompt.ask(). The result is assigned to a variable. ```pycon >>> name = Prompt.ask("Enter your name") ``` -------------------------------- ### Print with console markup and locals() Source: https://github.com/textualize/rich/blob/main/docs/source/introduction.rst Demonstrates console markup and pretty formatting of Python objects. The example shows the output with colors and styles. ```default >>> print("[italic red]Hello[/italic red] World!", locals()) ``` ```html
Hello World!
{
    '_\_annotations_\_': {},
    '_\_builtins_\_': <module 'builtins' (built-in)>,
    '_\_doc_\_': None,
    '_\_loader_\_': <class '_frozen_importlib.BuiltinImporter'>,
    '_\_name_\_': '_\_main_\_',
    '_\_package_\_': None,
    '_\_spec_\_': None,
    'print': <function print at 0x1027fd4c0>,
} 
``` -------------------------------- ### FloatPrompt.ask example Source: https://github.com/textualize/rich/blob/main/docs/source/reference/prompt.rst Shows how to ask for a float value using FloatPrompt.ask(). The result is assigned to a variable. ```pycon >>> temperature = FloatPrompt.ask("Enter desired temperature") ``` -------------------------------- ### Use custom Console with Progress constructor Source: https://github.com/textualize/rich/blob/main/docs/source/progress.rst Pass an existing Console object to the Progress constructor to use it for both progress display and console output. Example prints a message before starting work. ```python from my_project import my_console with Progress(console=my_console) as progress: my_console.print("[bold blue]Starting work!") do_work(progress) ``` -------------------------------- ### Auto-generate rich repr with @rich.repr.auto Source: https://github.com/textualize/rich/blob/main/docs/source/pretty.rst Use the @rich.repr.auto decorator to automatically generate a rich repr for a class whose __init__ parameters match attribute names. The decorator also creates a __repr__, so you get an auto-generated repr even without Rich printing. This example also prints a dictionary of Bird instances with rich.print. ```python import rich.repr @rich.repr.auto class Bird: def __init__(self, name, eats=None, fly=True, extinct=False): self.name = name self.eats = list(eats) if eats else [] self.fly = fly self.extinct = extinct BIRDS = { "gull": Bird("gull", eats=["fish", "chips", "ice cream", "sausage rolls"]), "penguin": Bird("penguin", eats=["fish"], fly=False), "dodo": Bird("dodo", eats=["fruit"], fly=False, extinct=True) } from rich import print print(BIRDS) ``` -------------------------------- ### Build documentation Source: https://github.com/textualize/rich/blob/main/CONTRIBUTING.md Generate the static HTML documentation from the project root directory. ```bash make docs ``` -------------------------------- ### External theme configuration format Source: https://github.com/textualize/rich/blob/main/docs/source/style.rst Example of the file format used for defining styles in an external configuration file. ```ini [styles] info = dim cyan warning = magenta danger = bold red ``` -------------------------------- ### Create sitecustomize.py Source: https://github.com/textualize/rich/blob/main/docs/source/traceback.rst Create the sitecustomize.py file if it does not exist. ```default $ touch .venv/lib/python3.9/site-packages/sitecustomize.py ``` -------------------------------- ### Live(renderable=None, console=None, screen=False, auto_refresh=True, refresh_per_second=4, transient=False, redirect_stdout=True, redirect_stderr=True, vertical_overflow='ellipsis', get_renderable=None) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/live.rst Creates a Live instance to render an auto-updating live display of a given renderable. Configure console, screen mode, refresh rate, and output redirection. ```APIDOC ## Live(renderable=None, console=None, screen=False, auto_refresh=True, refresh_per_second=4, transient=False, redirect_stdout=True, redirect_stderr=True, vertical_overflow='ellipsis', get_renderable=None) ### Description Creates a Live instance to render an auto-updating live display of a given renderable. Configure console, screen mode, refresh rate, and output redirection. ### Parameters - **renderable** (RenderableType, optional) - Optional - The renderable to live display. Defaults to displaying nothing. - **console** (Console, optional) - Optional - Optional Console instance. Defaults to an internal Console instance writing to stdout. - **screen** (bool, optional) - Optional - Enable alternate screen mode. Defaults to False. - **auto_refresh** (bool, optional) - Optional - Enable auto refresh. If disabled, you will need to call refresh() or update() with refresh flag. Defaults to True. - **refresh_per_second** (float, optional) - Optional - Number of times per second to refresh the live display. Defaults to 4. - **transient** (bool, optional) - Optional - Clear the renderable on exit (has no effect when screen=True). Defaults to False. - **redirect_stdout** (bool, optional) - Optional - Enable redirection of stdout, so `print` may be used. Defaults to True. - **redirect_stderr** (bool, optional) - Optional - Enable redirection of stderr. Defaults to True. - **vertical_overflow** (VerticalOverflowMethod, optional) - Optional - How to handle renderable when it is too tall for the console. Defaults to "ellipsis". - **get_renderable** (Callable[[], RenderableType], optional) - Optional - Optional callable to get renderable. Defaults to None. ``` -------------------------------- ### Stylize Text with bold magenta Source: https://github.com/textualize/rich/blob/main/docs/source/text.rst Creates a Text instance and applies a style to a range of characters using the stylize method, then prints it to the console. The example prints 'Hello, World!' with the first word in bold magenta. ```default from rich.console import Console from rich.text import Text console = Console() text = Text("Hello, World!") text.stylize("bold magenta", 0, 6) console.print(text) ``` -------------------------------- ### Console.begin_capture() Source: https://github.com/textualize/rich/blob/main/docs/source/reference.rst Begins capturing output. This method starts capturing all output written to the console, allowing it to be retrieved later. ```APIDOC ## Console.begin_capture() ### Description Begins capturing output. ### Method instance method ### Signature `Console.begin_capture()` ### Returns - **Capture** - A Capture object to retrieve the captured output. ``` -------------------------------- ### Install Rich with Jupyter extras Source: https://github.com/textualize/rich/blob/main/docs/source/introduction.rst Installs Rich with additional dependencies required for Jupyter integration. ```default pip install "rich[jupyter]" ``` -------------------------------- ### Create a basic live display with Live context manager Source: https://github.com/textualize/rich/blob/main/docs/source/live.rst Construct a Live object with a renderable and use it as a context manager. The live display persists for the duration of the context. Update the renderable internally to update the display. The refresh_per_second parameter controls the update rate. ```default 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") ``` -------------------------------- ### Use a custom Console with Live Source: https://github.com/textualize/rich/blob/main/docs/source/live.rst Pass a custom Console object to the Live constructor to use it for printing. The example prints a message to the custom console inside the Live context. ```python from my_project import my_console with Live(console=my_console) as live: my_console.print("[bold blue]Starting work!") ... ``` -------------------------------- ### Using console.pager() with make_test_card Source: https://github.com/textualize/rich/blob/main/docs/source/reference/console.rst Shows how to use the pager context manager to display content in a system pager. Requires importing Console and make_test_card from rich.__main__. The example prints a test card inside the pager context. ```pycon >>> from rich.console import Console >>> from rich.__main__ import make_test_card >>> console = Console() >>> with console.pager(): console.print(make_test_card()) ``` -------------------------------- ### Demonstrate tree rendering with python -m rich.tree Source: https://github.com/textualize/rich/blob/main/README.md Run the rich.tree module to demonstrate rendering a tree with guide lines. The output is a tree structure displayed in the terminal. ```bash python -m rich.tree ``` -------------------------------- ### Set up RichHandler for logging Source: https://github.com/textualize/rich/blob/main/docs/source/logging.rst Sets up a RichHandler as the logging handler for Python's logging module, formatting and colorizing log output. The example configures basicConfig with the handler and logs a simple message. ```python import logging from rich.logging import RichHandler FORMAT = "%(message)s" logging.basicConfig( level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()] ) log = logging.getLogger("rich") log.info("Hello, World!") ``` -------------------------------- ### Run Rich progress demo from command line Source: https://github.com/textualize/rich/blob/main/docs/source/progress.rst Run this command to see how the progress display looks. It launches the built-in demo. ```default python -m rich.progress ``` -------------------------------- ### Defining and using a custom Theme Source: https://github.com/textualize/rich/blob/main/docs/source/style.rst Demonstrates creating a Theme instance and passing it to the Console constructor to use semantic style names. ```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_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") ``` -------------------------------- ### Syntax highlight code with rich.syntax.Syntax Source: https://github.com/textualize/rich/blob/main/README.md Apply syntax highlighting to a code string using rich.syntax.Syntax. The example uses the monokai theme and enables line numbers, then prints the highlighted code to the console. ```python from rich.console import Console from rich.syntax import Syntax my_code = ''' def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]: """Iterate and generate a tuple with a flag for first and last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return first = True for value in iter_values: yield first, False, previous_value first = False previous_value = value yield first, True, previous_value ''' syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True) console = Console() console.print(syntax) ``` -------------------------------- ### Print/log above progress with progress.console Source: https://github.com/textualize/rich/blob/main/docs/source/progress.rst Use Progress() to create a console accessible via progress.console to print output above the progress display. Example adds a task and iterates to print job messages and advance the progress. ```python with Progress() as progress: task = progress.add_task("twiddling thumbs", total=10) for job in range(10): progress.console.print(f"Working on job #{job}") run_job(job) progress.advance(task) ``` -------------------------------- ### Print to live.console in a Live context Source: https://github.com/textualize/rich/blob/main/docs/source/live.rst Use the internal console of a Live instance to print messages above the live display. The example updates a table 4 times per second and prints progress messages via live.console.print. ```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) as live: # update 4 times a second to feel fluid for row in range(12): live.console.print(f"Working on row #{row}") time.sleep(0.4) table.add_row(f"{row}", f"description {row}", "[red]ERROR") ``` -------------------------------- ### Syntax CLI: show help Source: https://github.com/textualize/rich/blob/main/docs/source/syntax.rst Run 'python -m rich.syntax -h' to see the full list of command-line arguments. ```bash python -m rich.syntax -h ``` -------------------------------- ### Run the live display demo with python -m rich.live Source: https://github.com/textualize/rich/blob/main/docs/source/live.rst Run this command to see a demonstration of a live display. If you see ellipsis "…", the terminal is not tall enough to show the full table. ```default python -m rich.live ``` -------------------------------- ### Create and print a Panel Source: https://github.com/textualize/rich/blob/main/docs/source/reference/panel.rst Creates a Panel with the text "Hello, World!" and prints it to the console. The panel uses the default rounded box and other default settings. ```pycon >>> console.print(Panel("Hello, World!")) ``` -------------------------------- ### Progress without context manager with start/stop Source: https://github.com/textualize/rich/blob/main/docs/source/progress.rst When not using the context manager, call start() before adding tasks and stop() in a finally block to ensure proper cleanup. Uses try/finally to guarantee stop() is called. ```python import time from rich.progress import Progress progress = Progress() progress.start() try: task1 = progress.add_task("[red]Downloading...", total=1000) task2 = progress.add_task("[green]Processing...", total=1000) task3 = progress.add_task("[cyan]Cooking...", total=1000) while not progress.finished: progress.update(task1, advance=0.5) progress.update(task2, advance=0.3) progress.update(task3, advance=0.9) time.sleep(0.02) finally: progress.stop() ``` -------------------------------- ### Fit Panel to content with Panel.fit Source: https://github.com/textualize/rich/blob/main/docs/source/panel.rst By default, panels extend to the full width of the terminal. Use expand=False or the fit() method to make the panel fit the content. The example uses Panel.fit to print a panel that fits its content. ```python from rich import print from rich.panel import Panel print(Panel.fit("Hello, [red]World!")) ``` -------------------------------- ### Basic Columns example: clone of ls command Source: https://github.com/textualize/rich/blob/main/docs/source/columns.rst Constructs a Columns instance from a directory listing and prints it, using equal=True and expand=True to space the columns evenly. Requires a directory argument on the command line; otherwise prints usage. ```python import os import sys from rich import print from rich.columns import Columns if len(sys.argv) < 2: print("Usage: python columns.py DIRECTORY") else: directory = os.listdir(sys.argv[1]) columns = Columns(directory, equal=True, expand=True) print(columns) ``` -------------------------------- ### Padding with tuple of 2 values Source: https://github.com/textualize/rich/blob/main/docs/source/padding.rst Uses a tuple of 2 values to set top/bottom and left/right padding. This example adds 2 blank lines above and below and 4 spaces on left and right. ```default from rich import print from rich.padding import Padding test = Padding("Hello", (2, 4)) print(test) ``` -------------------------------- ### Run the prompts demo Source: https://github.com/textualize/rich/blob/main/docs/source/prompt.rst Command to run the prompts demo from the command line. ```bash python -m rich.prompt ``` -------------------------------- ### Create and print a basic Layout Source: https://github.com/textualize/rich/blob/main/docs/source/layout.rst Creates a basic Layout object and prints it, which draws a placeholder box the size of the terminal. ```default from rich import print from rich.layout import Layout layout = Layout() print(layout) ``` -------------------------------- ### Custom Progress with Spinner, Default Columns, and Elapsed Time Source: https://github.com/textualize/rich/blob/main/docs/source/reference/progress.rst Constructs a Progress instance with a spinner column on the left, the default progress columns, and a labeled elapsed time column. This example appears in the get_default_columns() documentation. ```python progress = Progress( SpinnerColumn(), * Progress.get_default_columns(), "Elapsed:", TimeElapsedColumn(), ) ``` -------------------------------- ### Constructing a Style instance Source: https://github.com/textualize/rich/blob/main/docs/source/style.rst Demonstrates creating a Style object directly instead of using a style definition string. ```python from rich.style import Style danger_style = Style(color="red", blink=True, bold=True) console.print("Danger, Will Robinson!", style=danger_style) ``` -------------------------------- ### Output of overflow methods example Source: https://github.com/textualize/rich/blob/main/docs/source/console.rst Output produced by the overflow methods example. Shows the fold method wrapping the word across three lines, crop truncating at the line end, and ellipsis truncating with an ellipsis character. ```text ──── fold ──── supercalifragi listicexpialid ocious ──── crop ──── supercalifragi ── ellipsis ── supercalifrag… ``` -------------------------------- ### open(file, mode, buffering=-1, encoding=None, errors=None, newline=None, total=None, task_id=None, description='Reading...') Source: https://github.com/textualize/rich/blob/main/docs/source/reference/progress.rst Tracks progress while reading from a binary or text file. Returns a file-like object. ```APIDOC ## open(file, mode, buffering=-1, encoding=None, errors=None, newline=None, total=None, task_id=None, description='Reading...') ### Description Track progress while reading from a binary file. ### Method open ### Parameters - **file** (str | PathLike[str] | bytes) - Required - The path to the file to read. - **mode** (Literal['rb'] or Literal['r', 'rt']) - Required - The mode to use to open the file. Only supports "r", "rb" or "rt". - **buffering** (int) - Optional - The buffering strategy to use, see io.open(). - **encoding** (str, optional) - The encoding to use when reading in text mode, see io.open(). - **errors** (str, optional) - The error handling strategy for decoding errors, see io.open(). - **newline** (str, optional) - The strategy for handling newlines in text mode, see io.open(). - **total** (int, optional) - Total number of bytes to read. If none given, os.stat(path).st_size is used. - **task_id** (TaskID) - Optional - Task to track. Default is new task. - **description** (str, optional) - Description of task, if new task is created. ### Returns BinaryIO or TextIO - A readable file-like object. ### Raises ValueError - When an invalid mode is given. ``` -------------------------------- ### renderable (property) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/live.rst Get the renderable that is being displayed. ```APIDOC ## renderable (property) ### Description Get the renderable that is being displayed. ### Returns - **RenderableType** - The displayed renderable. ``` -------------------------------- ### property width Source: https://github.com/textualize/rich/blob/main/docs/source/reference/console.rst Gets the width of the console in characters. ```APIDOC ## property width ### Description Get the width of the console. ### Method property width ### Returns - **int** - The width (in characters) of the console. ``` -------------------------------- ### Syntax highlighting with from_path() Source: https://github.com/textualize/rich/blob/main/docs/source/syntax.rst Use the from_path() alternative constructor to load code from disk and auto-detect the file type. This is a more concise way to highlight a file. ```python from rich.console import Console from rich.syntax import Syntax console = Console() syntax = Syntax.from_path("syntax.py") console.print(syntax) ``` -------------------------------- ### plain (property) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/text.rst Gets the text as a single string. ```APIDOC ## plain (property) ### Description Get the text as a single string. ### Returns - **str** - The plain text content. ``` -------------------------------- ### tasks (property) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/progress.rst Get a list of Task instances. ```APIDOC ## tasks (property) ### Description Get a list of Task instances. ### Returns List[Task] ``` -------------------------------- ### StyleStack.current (property) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/style.rst Gets the Style at the top of the stack. ```APIDOC ## StyleStack.current (property) ### Description Gets the Style at the top of the stack. ### Property Style ``` -------------------------------- ### Progress.open() Source: https://github.com/textualize/rich/blob/main/docs/source/reference.rst Opens a file and wraps it with progress tracking. ```APIDOC ## Progress.open() ### Description Opens a file and wraps it with progress tracking. ### Method open ### Parameters - **file** (str) - Required - Path to the file. - **mode** (str, optional) - Optional - Mode to open the file. ### Returns - **file** - A file object. ``` -------------------------------- ### spans (property) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/text.rst Gets a reference to the internal list of spans. ```APIDOC ## spans (property) ### Description Get a reference to the internal list of spans. ### Returns - **List[Span]** - The internal list of spans. ``` -------------------------------- ### Style.without_color (property) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/style.rst Gets a copy of the style with color removed. ```APIDOC ## Style.without_color (property) ### Description Gets a copy of the style with color removed. ### Property Style ``` -------------------------------- ### measure_renderables Source: https://github.com/textualize/rich/blob/main/docs/source/reference/measure.rst Gets a measurement that would fit a number of renderables. ```APIDOC ## measure_renderables ### Description Get a measurement that would fit a number of renderables. ### Method measure_renderables ### Parameters - **console** (Console) - Console instance. - **options** (ConsoleOptions) - Console options. - **renderables** (Iterable[RenderableType]) - One or more renderable objects. ### Returns Measurement object containing range of character widths required to contain all given renderables. ### Return Type Measurement ``` -------------------------------- ### Color.default() Source: https://github.com/textualize/rich/blob/main/docs/source/reference/color.rst Class method to get the default color instance. ```APIDOC ## Color.default() ### Description Returns a Color instance representing the default color. ### Method classmethod ### Signature `default()` ### Parameters None ### Returns - **Color** - Default color. ### Return Type `Color` ``` -------------------------------- ### Syntax.__init__ Source: https://github.com/textualize/rich/blob/main/docs/source/reference/syntax.rst Constructs a Syntax object to render syntax highlighted code. Accepts the code string, a lexer, and various formatting options. ```APIDOC ## Syntax.__init__ ### Description Constructs a Syntax object to render syntax highlighted code. ### Method Constructor ### Signature Syntax(code, lexer, theme='monokai', dedent=False, line_numbers=False, start_line=1, line_range=None, highlight_lines=None, code_width=None, tab_size=4, word_wrap=False, background_color=None, indent_guides=False, padding=0) ### Parameters - **code** (str) - Required - Code to highlight. - **lexer** (Lexer | str) - Required - Lexer to use (see https://pygments.org/docs/lexers/). - **theme** (str, optional) - Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "monokai". - **dedent** (bool, optional) - Enable stripping of initial whitespace. Defaults to False. - **line_numbers** (bool, optional) - Enable rendering of line numbers. Defaults to False. - **start_line** (int, optional) - Starting number for line numbers. Defaults to 1. - **line_range** (Tuple[int | None, int | None], optional) - If given should be a tuple of the start and end line to render. A value of None in the tuple indicates the range is open in that direction. - **highlight_lines** (Set[int]) - A set of line numbers to highlight. - **code_width** (Optional[int]) - Width of code to render (not including line numbers), or None to use all available width. - **tab_size** (int, optional) - Size of tabs. Defaults to 4. - **word_wrap** (bool, optional) - Enable word wrapping. - **background_color** (str, optional) - Optional background color, or None to use theme color. Defaults to None. - **indent_guides** (bool, optional) - Show indent guides. Defaults to False. - **padding** (PaddingDimensions) - Padding to apply around the syntax. Defaults to 0 (no padding). ``` -------------------------------- ### Emoji variant example Source: https://github.com/textualize/rich/blob/main/docs/source/markup.rst Specify the emoji variant with -emoji or -text. ```pycon >>> from rich import print >>> print(":red_heart-emoji:") >>> print(":red_heart-text:") ``` -------------------------------- ### property size Source: https://github.com/textualize/rich/blob/main/docs/source/reference/console.rst Gets the size of the console as a named tuple of dimensions. ```APIDOC ## property size ### Description Get the size of the console. ### Method property size ### Returns - **ConsoleDimensions** - A named tuple containing the dimensions. ``` -------------------------------- ### get_table_column() Source: https://github.com/textualize/rich/blob/main/docs/source/reference/progress.rst Get a table column, used to build tasks table. ```APIDOC ## get_table_column() ### Description Get a table column, used to build tasks table. ### Returns Column ``` -------------------------------- ### class rich.bar.Bar(size, begin, end, width=None, color='default', bgcolor='default') Source: https://github.com/textualize/rich/blob/main/docs/source/reference/bar.rst Creates a Bar instance that renders a solid block bar. The constructor takes a size value for the end of the bar, a begin point, an end point, and optionally a width, bar color, and background color. ```APIDOC ## class rich.bar.Bar(size, begin, end, width=None, color='default', bgcolor='default') ### Description Renders a solid block bar. Initializes a bar with a given size and range. ### Method Constructor ### Parameters - **size** (*float*) - Required - Value for the end of the bar. - **begin** (*float*) - Required - Begin point (between 0 and size, inclusive). - **end** (*float*) - Required - End point (between 0 and size, inclusive). - **width** (*int*, optional) - Optional - Width of the bar, or None for maximum width. Defaults to None. - **color** (Union[Color, str], optional) - Optional - Color of the bar. Defaults to "default". - **bgcolor** (Union[Color, str], optional) - Optional - Color of bar background. Defaults to "default". ``` -------------------------------- ### RowSplitter.get_tree_icon() Source: https://github.com/textualize/rich/blob/main/docs/source/reference/layout.rst Get the icon (emoji) used in layout.tree. Returns a string. ```APIDOC ## RowSplitter.get_tree_icon() ### Description Get the icon (emoji) used in layout.tree. Returns a string. ### Signature ```python def get_tree_icon() -> str ``` ### Returns - **str** - The icon used in layout.tree. ``` -------------------------------- ### Color.system (property) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/color.rst Property to get the native color system for this color. ```APIDOC ## Color.system (property) ### Description Gets the native color system for this color. ### Method property ### Signature `system` ### Parameters None ### Returns - **ColorSystem** - The native color system. ### Return Type `ColorSystem` ``` -------------------------------- ### encoding property Source: https://github.com/textualize/rich/blob/main/docs/source/reference/console.rst Gets the encoding of the console file, e.g. 'utf-8'. ```APIDOC ## encoding property ### Description Gets the encoding of the console file, e.g. 'utf-8'. ### Property encoding ### Returns - **str** - A standard encoding string. ``` -------------------------------- ### Rendering Markdown with Rich: Python example using Markdown class Source: https://github.com/textualize/rich/blob/main/docs/source/markdown.rst Construct a Markdown object with markdown text and print it to a Console. This snippet shows a minimal example with a markdown string that includes an h1, italic text, and a list. Note that code blocks are rendered with full syntax highlighting. ```python MARKDOWN = """ # This is an h1 Rich can do a pretty *decent* job of rendering markdown. 1. This is a list item 2. This is another list item """ from rich.console import Console from rich.markdown import Markdown console = Console() md = Markdown(MARKDOWN) console.print(md) ``` -------------------------------- ### update(text='', style=None, speed=None) Source: https://github.com/textualize/rich/blob/main/docs/source/reference/spinner.rst Updates attributes of a spinner after it has been started. ```APIDOC ## update(text='', style=None, speed=None) ### Description Updates attributes of a spinner after it has been started. ### Parameters - **text** (RenderableType, optional) - A renderable to display at the right of the spinner (str or Text typically). Defaults to "". - **style** (StyleType, optional) - Style for spinner animation. Defaults to None. - **speed** (float, optional) - Speed factor for animation. Defaults to None. ### Returns - **None** ``` -------------------------------- ### Import the console from my_project.console Source: https://github.com/textualize/rich/blob/main/docs/source/console.rst Import the previously created Console instance from the project's console module. ```python from my_project.console import console ``` -------------------------------- ### Unclosed style example Source: https://github.com/textualize/rich/blob/main/docs/source/markup.rst If you don't close a style, it applies until the end of the string. ```default print("[bold italic yellow on red blink]This text is impossible to read") ```