async def inner(): if datasette.pdb: pdb.post_mortem(exception.__traceback__) if rich is not None: rich.get_console().print_exception(show_locals=True) title = None if isinstance(exception, Base400): status = exception.status info = {} message = exception.args[0] elif isinstance(exception, DatasetteError): status = exception.status info = exception.error_dict message = exception.message if exception.message_is_html: message = Markup(message) title = exception.title else: status = 500 info = {} message = str(exception) traceback.print_exc() templates = [f"{status}.html", "error.html"] info.update({ "ok": False, "error": message, "status": status, "title": title, }) headers = {} if datasette.cors: add_cors_headers(headers) if request.path.split("?")[0].endswith(".json"): return Response.json(info, status=status, headers=headers) else: template = datasette.jinja_env.select_template(templates) return Response.html( await template.render_async( dict( info, urls=datasette.urls, app_css_hash=datasette.app_css_hash(), menu_links=lambda: [], )), status=status, headers=headers, )
def __init__( self, console=None, level=logging.NOTSET, show_time: bool = False, show_level: bool = False, show_path: bool = False, log_colors: dict[str, str] = None, log_level_colors: dict[str, str] = None, ) -> None: super().__init__(level=level) self.console = console or rich.get_console() self.formatter = self.formatter or logging._defaultFormatter self.show_time = show_time self.show_level = show_level self.show_path = show_path self.log_colors = log_colors or { "time": "blue", "path": "dim white", } self.log_level_colors = log_level_colors or { "INFO": "bold white", "WARNING": "yellow", "DEBUG": "cyan", "ERROR": "red", }
def test_rich_print_results(inputs, expected): console = get_console() with console.capture() as capture: EvaluationLoop._print_results(*inputs) expected = expected[ 1:] # remove the initial line break from the """ string assert capture.get() == expected.lstrip()
def _ipy_display_hook( value: Any, console: Optional["Console"] = None, overflow: "OverflowMethod" = "ignore", crop: bool = False, indent_guides: bool = False, max_length: Optional[int] = None, max_string: Optional[int] = None, expand_all: bool = False, ) -> None: from .console import ConsoleRenderable # needed here to prevent circular import # always skip rich generated jupyter renderables or None values if _safe_isinstance(value, JupyterRenderable) or value is None: return console = console or get_console() if console.is_jupyter: # Delegate rendering to IPython if the object (and IPython) supports it # https://ipython.readthedocs.io/en/stable/config/integrating.html#rich-display ipython_repr_methods = [ "_repr_html_", "_repr_markdown_", "_repr_json_", "_repr_latex_", "_repr_jpeg_", "_repr_png_", "_repr_svg_", "_repr_mimebundle_", ] for repr_method in ipython_repr_methods: method = getattr(value, repr_method, None) if inspect.ismethod(method): # Calling the method ourselves isn't ideal. The interface for the `_repr_*_` methods # specifies that if they return None, then they should not be rendered # by the notebook. try: repr_result = method() except Exception: continue # If the method raises, treat it as if it doesn't exist, try any others if repr_result is not None: return # Delegate rendering to IPython # certain renderables should start on a new line if _safe_isinstance(value, ConsoleRenderable): console.line() 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, expand_all=expand_all, margin=12, ), crop=crop, new_line_start=True, )
def pprint( _object: Any, *, console: Optional["Console"] = None, indent_guides: bool = True, max_length: Optional[int] = None, max_string: Optional[int] = None, max_depth: Optional[int] = None, expand_all: bool = False, ) -> None: """A convenience function for pretty printing. Args: _object (Any): Object to pretty print. console (Console, optional): Console instance, or None to use default. Defaults to None. 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 strings before truncating, or None to disable. Defaults to None. max_depth (int, optional): Maximum depth for nested data structures, or None for unlimited depth. Defaults to None. indent_guides (bool, optional): Enable indentation guides. Defaults to True. expand_all (bool, optional): Expand all containers. Defaults to False. """ _console = get_console() if console is None else console _console.print( Pretty( _object, max_length=max_length, max_string=max_string, max_depth=max_depth, indent_guides=indent_guides, expand_all=expand_all, overflow="ignore", ), soft_wrap=True, )
def install( console: "Console" = None, overflow: "OverflowMethod" = "ignore", crop: bool = False, ) -> None: """Install automatic pretty printing in the Python REPL. Args: 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. """ from rich import get_console console = console or get_console() 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 console.print( value if hasattr(value, "__rich_console__") or hasattr( value, "__rich__") else Pretty(value, overflow=overflow), crop=crop, ) builtins._ = value # type: ignore sys.displayhook = display_hook
def __rich__(self) -> Columns: if self.cell_type == CellType.CODE: counter = self.exec_count or " " if settings.display_cell_index: panel_title = f"Index: {self.cell_index}" else: panel_title = None rendered_cell = Columns([ f"\nIn [{counter}]:", Panel( Syntax(self._source_excerpt, "python", background_color="default"), width=int(rich.get_console().size[0] * 0.85), title=panel_title, ), ]) else: rendered_cell = Columns([ " ", Padding(NotebookMarkdown(self._source_excerpt), (1, 0, 1, 8)), ]) return rendered_cell
def pprint( _object: Any, *, console: "Console" = None, max_length: int = None, max_string: int = None, indent_guides: bool = True, ): """A convenience function for pretty printing. Args: _object (Any): Object to pretty print. console (Console, optional): Console instance, or None to use default. Defaults to None. 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 strings before truncating, or None to disable. Defaults to None. indent_guides (bool, optional): Enable indentation guides. Defaults to True. """ _console = get_console() if console is None else console _console.print( Pretty( _object, max_length=max_length, max_string=max_string, indent_guides=indent_guides, ))
def test_rich_print_json_no_truncation(): console = rich.get_console() with console.capture() as capture: rich.print_json(f'["{"x" * 100}", {int(2e128)}]', indent=4) result = capture.get() print(repr(result)) assert ("x" * 100) in result assert str(int(2e128)) in result
def test_rich_print_json(): console = rich.get_console() with console.capture() as capture: rich.print_json('[false, true, null, "foo"]', indent=4) result = capture.get() print(repr(result)) expected = '[\n false,\n true,\n null,\n "foo"\n]\n' assert result == expected
async def start(bake_id: str) -> TaskStatus: async with LocalsBatchExecutor.create( get_console(), bake_id, patched_client, batch_storage, ) as executor: return await executor.run()
def test_rich_print_json_round_trip(): data = ["x" * 100, 2e128] console = rich.get_console() with console.capture() as capture: rich.print_json(data=data, indent=4) result = capture.get() print(repr(result)) result_data = json.loads(result) assert result_data == data
async def start(bake_id: str) -> None: async with TestBatchExecutor.create( get_console(), bake_id, patched_client, batch_storage, polling_timeout=0.05, ) as executor: await executor.run()
def test_rich_print(): console = rich.get_console() output = io.StringIO() backup_file = console.file try: console.file = output rich.print("foo") assert output.getvalue() == "foo\n" finally: console.file = backup_file
def dump(self) -> None: ''' Dump database to screen. Raw version of tqLS. ''' c = rich.get_console() c.log('dumping configurations') c.print(self[defs.DB_TABLE_CONFIG]) c.log('dumping tasks') c.print(self[defs.DB_TABLE_TASQUE]) c.log('dumping notes') c.print(self[defs.DB_TABLE_NOTES])
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, expand_all=expand_all, ) else: return repr(value)
def nuke_and_launch(self, generator=None): if generator is None: generator = self.get_generator() generator = list(generator) # First, nuke self.nuke(generator) rich.print("[red]-------------------[/red]") if self.in_salvo_arg_block("--wait-before-launch"): console = rich.get_console() with console.status("Waiting [bold]60s[/bold] for launch..."): time.sleep(60) # Next, launch self.launch(generator)
def summarize( summary_data: List[Tuple[str, List[str]]], total_parameters: int, trainable_parameters: int, model_size: float, ) -> None: console = get_console() table = Table(header_style="bold magenta") table.add_column(" ", style="dim") table.add_column("Name", justify="left", no_wrap=True) table.add_column("Type") table.add_column("Params", justify="right") column_names = list(zip(*summary_data))[0] for column_name in ["In sizes", "Out sizes"]: if column_name in column_names: table.add_column(column_name, justify="right", style="white") rows = list(zip(*(arr[1] for arr in summary_data))) for row in rows: table.add_row(*row) console.print(table) parameters = [] for param in [ trainable_parameters, total_parameters - trainable_parameters, total_parameters, model_size ]: parameters.append("{:<{}}".format( get_human_readable_count(int(param)), 10)) grid = Table.grid(expand=True) grid.add_column() grid.add_column() grid.add_row(f"[bold]Trainable params[/]: {parameters[0]}") grid.add_row(f"[bold]Non-trainable params[/]: {parameters[1]}") grid.add_row(f"[bold]Total params[/]: {parameters[2]}") grid.add_row( f"[bold]Total estimated model params size (MB)[/]: {parameters[3]}" ) console.print(grid)
async def create(path: Path) -> BatchRunner: config_dir = ConfigDir( workspace=path, config_dir=path, ) nonlocal runner # BatchRunner should not use client in this case runner = BatchRunner( config_dir, get_console(), client, batch_storage, FakeGlobalOptions(), run_neuro_cli=mock_neuro_cli_runner.run, ) await runner.__aenter__() return runner
def install( console: "Console" = None, overflow: "OverflowMethod" = "ignore", crop: bool = False, indent_guides: bool = False, max_length: int = None, max_string: int = None, expand_all: bool = False, ) -> None: """Install automatic pretty printing in the Python REPL. Args: 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. expand_all (bool, optional): Expand all containers. Defaults to False """ from rich import get_console console = console or get_console() 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 console.print( value if isinstance(value, RichRenderable) else Pretty( value, overflow=overflow, indent_guides=indent_guides, max_length=max_length, max_string=max_string, expand_all=expand_all, ), crop=crop, ) builtins._ = value # type: ignore sys.displayhook = display_hook
def main(): old = {} # 上一次获取的数据 new = {} # 本次获取的数据 if os.path.exists(path): if os.path.getsize(path): with open(path, encoding='utf-8') as file: old = json.load(file) console = get_console() table = Table(box=box.SIMPLE) table.add_column("Name", justify="right", width=int(console.width * 4 / 10)) table.add_column("Url", justify="left", width=int(console.width * 6 / 10)) session = requests.Session() page = 1 with Live(table, refresh_per_second=4): while True: response = session.get(url.format(page)) response = response.json() data = response.get('data') for video in data.get('list'): badge = video.get('badge') if badge in ['限时免费']: _id_ = str(video['media_id']) _title_ = video['title'] _link_ = video['link'] new[_id_] = {'title': _title_, 'link': _link_} if _id_ in old: table.add_row(video['title'], video['link']) else: table.add_row(f"[red]{video['title']}", f"[red]{video['link']}") if not data.get('has_next') or page > 99: break page += 1 session.close() with open(path, 'w+', encoding='utf-8') as file: json.dump(new, file, ensure_ascii=False, indent=4)
def _init_progress(self, trainer): if self.is_enabled and (self.progress is None or self._progress_stopped): self._reset_progress_bar_ids() reconfigure(**self._console_kwargs) self._console = get_console() self._console.clear_live() self._metric_component = MetricsTextColumn(trainer, self.theme.metrics) self.progress = CustomProgress( *self.configure_columns(trainer), self._metric_component, auto_refresh=False, disable=self.is_disabled, console=self._console, ) self.progress.start() # progress has started self._progress_stopped = False
def install(console: "Console" = None, no_wrap: bool = False, overflow: "OverflowMethod" = None) -> None: """Install automatic pretty printing in the Python REPL. Args: console (Console, optional): Console instance or ``None`` to use global console. Defaults to None. """ from rich import get_console console = console or get_console() def display_hook(value: Any) -> None: if value is not None: assert console is not None console.print(value if hasattr(value, "__rich_console__") or hasattr(value, "__rich__") else pretty_repr( value, max_width=console.width, no_wrap=False, overflow=overflow)) sys.displayhook = display_hook
def render_to_string( text: str | Text, *, console: Console | None = None, strip_styles: bool = False, ) -> str: """Render text with rich to string including ANSI codes, etc.. This function allows to render text with is not automatically printed with rich. For example, render warnings with colors or text in exceptions. """ if console is None: console = rich.get_console() segments = console.render(text) output = [] if console.no_color and console._color_system: segments = Segment.remove_color(segments) if strip_styles: segments = Segment.strip_styles(segments) for segment in segments: if segment.style: output.append( segment.style.render( segment.text, color_system=console._color_system, legacy_windows=console.legacy_windows, )) else: output.append(segment.text) rendered = "".join(output) return rendered
async def on_ready(): if bot._uptime is not None: return bot._uptime = datetime.utcnow() guilds = len(bot.guilds) users = len(set([m for m in bot.get_all_members()])) invite_url = discord.utils.oauth_url(bot._app_info.id) prefixes = cli_flags.prefix or (await bot._config.prefix()) lang = await bot._config.locale() red_pkg = pkg_resources.get_distribution("Red-DiscordBot") dpy_version = discord.__version__ table_general_info = Table(show_edge=False, show_header=False, box=box.MINIMAL) table_general_info.add_row("Prefixes", ", ".join(prefixes)) table_general_info.add_row("Language", lang) table_general_info.add_row("Red version", red_version) table_general_info.add_row("Discord.py version", dpy_version) table_general_info.add_row("Storage type", data_manager.storage_type()) table_counts = Table(show_edge=False, show_header=False, box=box.MINIMAL) # String conversion is needed as Rich doesn't deal with ints table_counts.add_row("Shards", str(bot.shard_count)) table_counts.add_row("Servers", str(guilds)) if bot.intents.members: # Lets avoid 0 Unique Users table_counts.add_row("Unique Users", str(users)) outdated_red_message = "" rich_outdated_message = "" with contextlib.suppress(aiohttp.ClientError, asyncio.TimeoutError): pypi_version, py_version_req = await fetch_latest_red_version_info( ) outdated = pypi_version and pypi_version > red_version_info if outdated: outdated_red_message = _( "Your Red instance is out of date! {} is the current " "version, however you are using {}!").format( pypi_version, red_version) rich_outdated_message = ( f"[red]Outdated version![/red]\n" f"[red]!!![/red]Version [cyan]{pypi_version}[/] is available, " f"but you're using [cyan]{red_version}[/][red]!!![/red]") current_python = platform.python_version() extra_update = _( "\n\nWhile the following command should work in most scenarios as it is " "based on your current OS, environment, and Python version, " "**we highly recommend you to read the update docs at <{docs}> and " "make sure there is nothing else that " "needs to be done during the update.**" ).format( docs="https://docs.discord.red/en/stable/update_red.html") if expected_version(current_python, py_version_req): installed_extras = [] for extra, reqs in red_pkg._dep_map.items(): if extra is None or extra in {"dev", "all"}: continue try: pkg_resources.require(req.name for req in reqs) except pkg_resources.DistributionNotFound: pass else: installed_extras.append(extra) if installed_extras: package_extras = f"[{','.join(installed_extras)}]" else: package_extras = "" extra_update += _( "\n\nTo update your bot, first shutdown your " "bot then open a window of {console} (Not as admin) and " "run the following:\n\n").format( console=_("Command Prompt") if platform.system() == "Windows" else _("Terminal")) extra_update += ( '```"{python}" -m pip install -U Red-DiscordBot{package_extras}```' .format(python=sys.executable, package_extras=package_extras)) extra_update += _( "\nOnce you've started up your bot again, if you have any 3rd-party cogs" " installed we then highly recommend you update them with this command" " in Discord: `[p]cog update`") else: extra_update += _( "\n\nYou have Python `{py_version}` and this update " "requires `{req_py}`; you cannot simply run the update command.\n\n" "You will need to follow the update instructions in our docs above, " "if you still need help updating after following the docs go to our " "#support channel in <https://discord.gg/red>").format( py_version=current_python, req_py=py_version_req) outdated_red_message += extra_update rich_console = rich.get_console() rich_console.print(INTRO, style="red", markup=False, highlight=False) if guilds: rich_console.print( Columns( [ Panel(table_general_info, title=str(bot.user.name)), Panel(table_counts) ], equal=True, align="center", )) else: rich_console.print( Columns([Panel(table_general_info, title=str(bot.user.name))])) rich_console.print("Loaded {} cogs with {} commands".format( len(bot.cogs), len(bot.commands))) if invite_url: rich_console.print( f"\nInvite URL: {Text(invite_url, style=f'link {invite_url}')}" ) # We generally shouldn't care if the client supports it or not as Rich deals with it. if not guilds: rich_console.print( f"Looking for a quick guide on setting up Red? Checkout {Text('https://start.discord.red', style='link https://start.discord.red}')}" ) if rich_outdated_message: rich_console.print(rich_outdated_message) bot._color = discord.Colour(await bot._config.color()) bot._red_ready.set() if outdated_red_message: await send_to_owners_with_prefix_replaced(bot, outdated_red_message)
def _print_results(results: List[_OUT_DICT], stage: str) -> None: # remove the dl idx suffix results = [{k.split("/dataloader_idx_")[0]: v for k, v in result.items()} for result in results] metrics_paths = {k for keys in apply_to_collection(results, dict, EvaluationLoop._get_keys) for k in keys} if not metrics_paths: return metrics_strs = [":".join(metric) for metric in metrics_paths] # sort both lists based on metrics_strs metrics_strs, metrics_paths = zip(*sorted(zip(metrics_strs, metrics_paths))) headers = [f"DataLoader {i}" for i in range(len(results))] # fallback is useful for testing of printed output term_size = shutil.get_terminal_size(fallback=(120, 30)).columns or 120 max_length = int(min(max(len(max(metrics_strs, key=len)), len(max(headers, key=len)), 25), term_size / 2)) rows: List[List[Any]] = [[] for _ in metrics_paths] for result in results: for metric, row in zip(metrics_paths, rows): val = EvaluationLoop._find_value(result, metric) if val is not None: if isinstance(val, torch.Tensor): val = val.item() if val.numel() == 1 else val.tolist() row.append(f"{val}") else: row.append(" ") # keep one column with max length for metrics num_cols = int((term_size - max_length) / max_length) for i in range(0, len(headers), num_cols): table_headers = headers[i : (i + num_cols)] table_rows = [row[i : (i + num_cols)] for row in rows] table_headers.insert(0, f"{stage} Metric".capitalize()) if _RICH_AVAILABLE: columns = [Column(h, justify="center", style="magenta", width=max_length) for h in table_headers] columns[0].style = "cyan" table = Table(*columns) for metric, row in zip(metrics_strs, table_rows): row.insert(0, metric) table.add_row(*row) console = get_console() console.print(table) else: row_format = f"{{:^{max_length}}}" * len(table_headers) half_term_size = int(term_size / 2) try: # some terminals do not support this character if sys.stdout.encoding is not None: "─".encode(sys.stdout.encoding) except UnicodeEncodeError: bar_character = "-" else: bar_character = "─" bar = bar_character * term_size lines = [bar, row_format.format(*table_headers).rstrip(), bar] for metric, row in zip(metrics_strs, table_rows): # deal with column overflow if len(metric) > half_term_size: while len(metric) > half_term_size: row_metric = metric[:half_term_size] metric = metric[half_term_size:] lines.append(row_format.format(row_metric, *row).rstrip()) lines.append(row_format.format(metric, " ").rstrip()) else: lines.append(row_format.format(metric, *row).rstrip()) lines.append(bar) print(os.linesep.join(lines))
def test_get_console(): console = rich.get_console() assert isinstance(console, Console)
def install( console: Optional["Console"] = None, overflow: "OverflowMethod" = "ignore", crop: bool = False, indent_guides: bool = False, max_length: Optional[int] = None, max_string: Optional[int] = None, expand_all: bool = False, ) -> None: """Install automatic pretty printing in the Python REPL. Args: 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. 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. """ from rich import get_console from .console import ConsoleRenderable # needed here to prevent circular import 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 console.print( value if isinstance(value, RichRenderable) else Pretty( value, overflow=overflow, indent_guides=indent_guides, max_length=max_length, max_string=max_string, expand_all=expand_all, ), crop=crop, ) builtins._ = value # type: ignore def ipy_display_hook(value: Any) -> None: # pragma: no cover assert console is not None # always skip rich generated jupyter renderables or None values if isinstance(value, JupyterRenderable) or value is None: return # on jupyter rich display, if using one of the special representations don't use rich if console.is_jupyter and any( _re_jupyter_repr.match(attr) for attr in dir(value)): return # certain renderables should start on a new line if isinstance(value, ConsoleRenderable): console.line() console.print( value if isinstance(value, RichRenderable) else Pretty( value, overflow=overflow, indent_guides=indent_guides, max_length=max_length, max_string=max_string, expand_all=expand_all, margin=12, ), crop=crop, new_line_start=True, ) try: # pragma: no cover ip = get_ipython() # type: ignore from IPython.core.formatters import BaseFormatter # replace plain text formatter with rich formatter rich_formatter = BaseFormatter() rich_formatter.for_type(object, func=ipy_display_hook) ip.display_formatter.formatters["text/plain"] = rich_formatter except Exception: sys.displayhook = display_hook
''' Copyright (C) 2020-2021 Mo Zhou <*****@*****.**> Released under the Apache-2.0 License. ''' import os import sys import random import glob import argparse import rich c = rich.get_console() if __name__ == '__main__': ag = argparse.ArgumentParser() ag.add_argument( '-p', '--pool', type=str, default=os.path.expanduser('~/.torch/Stanford_Online_Products')) ag.add_argument('-s', '--suffix', type=str, default='.JPG') ag = ag.parse_args(sys.argv[1:]) #c.print(ag) with c.status('Globbing files ...'): p = os.path.join(ag.pool, '**') files = glob.glob(p, recursive=True) files = list(filter(lambda x: x.endswith(ag.suffix), files)) #c.print(f'Found {len(files)} {ag.suffix} files.') c.print(random.choice(files))
def install( console: Optional["Console"] = None, overflow: "OverflowMethod" = "ignore", crop: bool = False, indent_guides: bool = False, max_length: Optional[int] = None, max_string: Optional[int] = None, expand_all: bool = False, ) -> None: """Install automatic pretty printing in the Python REPL. Args: 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. 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. """ 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, expand_all=expand_all, ), crop=crop, ) builtins._ = value # type: ignore[attr-defined] try: # pragma: no cover ip = get_ipython() # type: ignore[name-defined] 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, 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 except Exception: sys.displayhook = display_hook