import sys from threading import Event, RLock, Thread from types import TracebackType from typing import IO, Any, Callable, List, Optional, TextIO, Type, cast
from . import get_console from .console import Console, ConsoleRenderable, RenderableType, RenderHook from .control import Control from .file_proxy import FileProxy from .jupyter import JupyterMixin from .live_render import LiveRender, VerticalOverflowMethod from .screen import Screen from .text import Text
class _RefreshThread(Thread): """A thread that calls refresh() at regular intervals."""
class Live(JupyterMixin, RenderHook): """Renders an auto-updating live display of any given renderable.
Args:
renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing.
console (Console, optional): Optional Console instance. Default will an internal Console instance writing to stdout.
screen (bool, optional): Enable alternate screen mode. Defaults to False.
auto_refresh (bool, 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): Number of times per second to refresh the live display. Defaults to 4.
transient (bool, optional): Clear the renderable on exit (has no effect when screen=True). Defaults to False.
redirect_stdout (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.
redirect_stderr (bool, optional): Enable redirection of stderr. Defaults to True.
vertical_overflow (VerticalOverflowMethod, optional): How to handle renderable when it istoo tall for the console. Defaults to "ellipsis".
get_renderable (Callable[[], RenderableType], optional): Optional callable to get renderable. Defaults to None. """
Args:
refresh (bool, optional): Also refresh. Defaults to False. """ with self._lock: if self._started: return
self.console.set_live(self)
self._started = True if self._screen:
self._alt_screen = self.console.set_alt_screen(True)
self.console.show_cursor(False)
self._enable_redirect_io()
self.console.push_render_hook(self) if refresh: try:
self.refresh() except Exception: # If refresh fails, we want to stop the redirection of sys.stderr, # so the error stacktrace is properly displayed in the terminal. # (or, if the code that calls Rich captures the exception and wants to display something, # let this be displayed in the terminal).
self.stop() raise if self.auto_refresh:
self._refresh_thread = _RefreshThread(self, self.refresh_per_second)
self._refresh_thread.start()
def stop(self) -> None: """Stop live rendering display.""" with self._lock: ifnot self._started: return
self.console.clear_live()
self._started = False
if self.auto_refresh and self._refresh_thread isnotNone:
self._refresh_thread.stop()
self._refresh_thread = None # allow it to fully render on the last even if overflow
self.vertical_overflow = "visible" with self.console: try: ifnot self._alt_screen andnot self.console.is_jupyter:
self.refresh() finally:
self._disable_redirect_io()
self.console.pop_render_hook() ifnot self._alt_screen and self.console.is_terminal:
self.console.line()
self.console.show_cursor(True) if self._alt_screen:
self.console.set_alt_screen(False)
if self.transient andnot self._alt_screen:
self.console.control(self._live_render.restore_cursor()) if self.ipy_widget isnotNoneand self.transient:
self.ipy_widget.close() # pragma: no cover
def update(self, renderable: RenderableType, *, refresh: bool = False) -> None: """Update the renderable that is being displayed
Args:
renderable (RenderableType): New renderable to use.
refresh (bool, optional): Refresh the display. Defaults to False. """ if isinstance(renderable, str):
renderable = self.console.render_str(renderable) with self._lock:
self._renderable = renderable if refresh:
self.refresh()
def refresh(self) -> None: """Update the display of the Live Render.""" with self._lock:
self._live_render.set_renderable(self.renderable) if self.console.is_jupyter: # pragma: no cover try: from IPython.display import display from ipywidgets import Output except ImportError: import warnings
warnings.warn('install "ipywidgets" for Jupyter support') else: if self.ipy_widget isNone:
self.ipy_widget = Output()
display(self.ipy_widget)
with self.ipy_widget:
self.ipy_widget.clear_output(wait=True)
self.console.print(self._live_render.renderable) elif self.console.is_terminal andnot self.console.is_dumb_terminal: with self.console:
self.console.print(Control()) elif ( not self._started andnot self.transient
): # if it is finished allow files or dumb-terminals to see final result with self.console:
self.console.print(Control())
def process_renderables(
self, renderables: List[ConsoleRenderable]
) -> List[ConsoleRenderable]: """Process renderables to restore cursor and display progress."""
self._live_render.vertical_overflow = self.vertical_overflow if self.console.is_interactive: # lock needs acquiring as user can modify live_render renderable at any time unlike in Progress. with self._lock:
reset = (
Control.home() if self._alt_screen else self._live_render.position_cursor()
)
renderables = [reset, *renderables, self._live_render] elif ( not self._started andnot self.transient
): # if it is finished render the final output for files or dumb_terminals
renderables = [*renderables, self._live_render]
return renderables
if __name__ == "__main__": # pragma: no cover import random import time from itertools import cycle from typing import Dict, List, Tuple
from .align import Align from .console import Console from .live import Live as Live from .panel import Panel from .rule import Rule from .syntax import Syntax from .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: yieldFalse, previous_value
previous_value = value yieldTrue, previous_value''', "python",
line_numbers=True,
)
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!"),
]
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.