live.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. import sys
  2. from threading import Event, RLock, Thread
  3. from types import TracebackType
  4. from typing import IO, Any, Callable, List, Optional, TextIO, Type, cast
  5. from . import get_console
  6. from .console import Console, ConsoleRenderable, RenderableType, RenderHook
  7. from .control import Control
  8. from .file_proxy import FileProxy
  9. from .jupyter import JupyterMixin
  10. from .live_render import LiveRender, VerticalOverflowMethod
  11. from .screen import Screen
  12. from .text import Text
  13. class _RefreshThread(Thread):
  14. """A thread that calls refresh() at regular intervals."""
  15. def __init__(self, live: "Live", refresh_per_second: float) -> None:
  16. self.live = live
  17. self.refresh_per_second = refresh_per_second
  18. self.done = Event()
  19. super().__init__(daemon=True)
  20. def stop(self) -> None:
  21. self.done.set()
  22. def run(self) -> None:
  23. while not self.done.wait(1 / self.refresh_per_second):
  24. with self.live._lock:
  25. if not self.done.is_set():
  26. self.live.refresh()
  27. class Live(JupyterMixin, RenderHook):
  28. """Renders an auto-updating live display of any given renderable.
  29. Args:
  30. renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing.
  31. console (Console, optional): Optional Console instance. Default will an internal Console instance writing to stdout.
  32. screen (bool, optional): Enable alternate screen mode. Defaults to False.
  33. auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()` or `update()` with refresh flag. Defaults to True
  34. refresh_per_second (float, optional): Number of times per second to refresh the live display. Defaults to 4.
  35. transient (bool, optional): Clear the renderable on exit (has no effect when screen=True). Defaults to False.
  36. redirect_stdout (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.
  37. redirect_stderr (bool, optional): Enable redirection of stderr. Defaults to True.
  38. vertical_overflow (VerticalOverflowMethod, optional): How to handle renderable when it is too tall for the console. Defaults to "ellipsis".
  39. get_renderable (Callable[[], RenderableType], optional): Optional callable to get renderable. Defaults to None.
  40. """
  41. def __init__(
  42. self,
  43. renderable: Optional[RenderableType] = None,
  44. *,
  45. console: Optional[Console] = None,
  46. screen: bool = False,
  47. auto_refresh: bool = True,
  48. refresh_per_second: float = 4,
  49. transient: bool = False,
  50. redirect_stdout: bool = True,
  51. redirect_stderr: bool = True,
  52. vertical_overflow: VerticalOverflowMethod = "ellipsis",
  53. get_renderable: Optional[Callable[[], RenderableType]] = None,
  54. ) -> None:
  55. assert refresh_per_second > 0, "refresh_per_second must be > 0"
  56. self._renderable = renderable
  57. self.console = console if console is not None else get_console()
  58. self._screen = screen
  59. self._alt_screen = False
  60. self._redirect_stdout = redirect_stdout
  61. self._redirect_stderr = redirect_stderr
  62. self._restore_stdout: Optional[IO[str]] = None
  63. self._restore_stderr: Optional[IO[str]] = None
  64. self._lock = RLock()
  65. self.ipy_widget: Optional[Any] = None
  66. self.auto_refresh = auto_refresh
  67. self._started: bool = False
  68. self.transient = True if screen else transient
  69. self._refresh_thread: Optional[_RefreshThread] = None
  70. self.refresh_per_second = refresh_per_second
  71. self.vertical_overflow = vertical_overflow
  72. self._get_renderable = get_renderable
  73. self._live_render = LiveRender(
  74. self.get_renderable(), vertical_overflow=vertical_overflow
  75. )
  76. @property
  77. def is_started(self) -> bool:
  78. """Check if live display has been started."""
  79. return self._started
  80. def get_renderable(self) -> RenderableType:
  81. renderable = (
  82. self._get_renderable()
  83. if self._get_renderable is not None
  84. else self._renderable
  85. )
  86. return renderable or ""
  87. def start(self, refresh: bool = False) -> None:
  88. """Start live rendering display.
  89. Args:
  90. refresh (bool, optional): Also refresh. Defaults to False.
  91. """
  92. with self._lock:
  93. if self._started:
  94. return
  95. self.console.set_live(self)
  96. self._started = True
  97. if self._screen:
  98. self._alt_screen = self.console.set_alt_screen(True)
  99. self.console.show_cursor(False)
  100. self._enable_redirect_io()
  101. self.console.push_render_hook(self)
  102. if refresh:
  103. self.refresh()
  104. if self.auto_refresh:
  105. self._refresh_thread = _RefreshThread(self, self.refresh_per_second)
  106. self._refresh_thread.start()
  107. def stop(self) -> None:
  108. """Stop live rendering display."""
  109. with self._lock:
  110. if not self._started:
  111. return
  112. self.console.clear_live()
  113. self._started = False
  114. if self.auto_refresh and self._refresh_thread is not None:
  115. self._refresh_thread.stop()
  116. self._refresh_thread = None
  117. # allow it to fully render on the last even if overflow
  118. self.vertical_overflow = "visible"
  119. with self.console:
  120. try:
  121. if not self._alt_screen and not self.console.is_jupyter:
  122. self.refresh()
  123. finally:
  124. self._disable_redirect_io()
  125. self.console.pop_render_hook()
  126. if not self._alt_screen and self.console.is_terminal:
  127. self.console.line()
  128. self.console.show_cursor(True)
  129. if self._alt_screen:
  130. self.console.set_alt_screen(False)
  131. if self.transient and not self._alt_screen:
  132. self.console.control(self._live_render.restore_cursor())
  133. if self.ipy_widget is not None and self.transient:
  134. self.ipy_widget.close() # pragma: no cover
  135. def __enter__(self) -> "Live":
  136. self.start(refresh=self._renderable is not None)
  137. return self
  138. def __exit__(
  139. self,
  140. exc_type: Optional[Type[BaseException]],
  141. exc_val: Optional[BaseException],
  142. exc_tb: Optional[TracebackType],
  143. ) -> None:
  144. self.stop()
  145. def _enable_redirect_io(self) -> None:
  146. """Enable redirecting of stdout / stderr."""
  147. if self.console.is_terminal or self.console.is_jupyter:
  148. if self._redirect_stdout and not isinstance(sys.stdout, FileProxy):
  149. self._restore_stdout = sys.stdout
  150. sys.stdout = cast("TextIO", FileProxy(self.console, sys.stdout))
  151. if self._redirect_stderr and not isinstance(sys.stderr, FileProxy):
  152. self._restore_stderr = sys.stderr
  153. sys.stderr = cast("TextIO", FileProxy(self.console, sys.stderr))
  154. def _disable_redirect_io(self) -> None:
  155. """Disable redirecting of stdout / stderr."""
  156. if self._restore_stdout:
  157. sys.stdout = cast("TextIO", self._restore_stdout)
  158. self._restore_stdout = None
  159. if self._restore_stderr:
  160. sys.stderr = cast("TextIO", self._restore_stderr)
  161. self._restore_stderr = None
  162. @property
  163. def renderable(self) -> RenderableType:
  164. """Get the renderable that is being displayed
  165. Returns:
  166. RenderableType: Displayed renderable.
  167. """
  168. renderable = self.get_renderable()
  169. return Screen(renderable) if self._alt_screen else renderable
  170. def update(self, renderable: RenderableType, *, refresh: bool = False) -> None:
  171. """Update the renderable that is being displayed
  172. Args:
  173. renderable (RenderableType): New renderable to use.
  174. refresh (bool, optional): Refresh the display. Defaults to False.
  175. """
  176. with self._lock:
  177. self._renderable = renderable
  178. if refresh:
  179. self.refresh()
  180. def refresh(self) -> None:
  181. """Update the display of the Live Render."""
  182. with self._lock:
  183. self._live_render.set_renderable(self.renderable)
  184. if self.console.is_jupyter: # pragma: no cover
  185. try:
  186. from IPython.display import display
  187. from ipywidgets import Output
  188. except ImportError:
  189. import warnings
  190. warnings.warn('install "ipywidgets" for Jupyter support')
  191. else:
  192. if self.ipy_widget is None:
  193. self.ipy_widget = Output()
  194. display(self.ipy_widget)
  195. with self.ipy_widget:
  196. self.ipy_widget.clear_output(wait=True)
  197. self.console.print(self._live_render.renderable)
  198. elif self.console.is_terminal and not self.console.is_dumb_terminal:
  199. with self.console:
  200. self.console.print(Control())
  201. elif (
  202. not self._started and not self.transient
  203. ): # if it is finished allow files or dumb-terminals to see final result
  204. with self.console:
  205. self.console.print(Control())
  206. def process_renderables(
  207. self, renderables: List[ConsoleRenderable]
  208. ) -> List[ConsoleRenderable]:
  209. """Process renderables to restore cursor and display progress."""
  210. self._live_render.vertical_overflow = self.vertical_overflow
  211. if self.console.is_interactive:
  212. # lock needs acquiring as user can modify live_render renderable at any time unlike in Progress.
  213. with self._lock:
  214. reset = (
  215. Control.home()
  216. if self._alt_screen
  217. else self._live_render.position_cursor()
  218. )
  219. renderables = [reset, *renderables, self._live_render]
  220. elif (
  221. not self._started and not self.transient
  222. ): # if it is finished render the final output for files or dumb_terminals
  223. renderables = [*renderables, self._live_render]
  224. return renderables
  225. if __name__ == "__main__": # pragma: no cover
  226. import random
  227. import time
  228. from itertools import cycle
  229. from typing import Dict, List, Tuple
  230. from .align import Align
  231. from .console import Console
  232. from .live import Live as Live
  233. from .panel import Panel
  234. from .rule import Rule
  235. from .syntax import Syntax
  236. from .table import Table
  237. console = Console()
  238. syntax = Syntax(
  239. '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
  240. """Iterate and generate a tuple with a flag for last value."""
  241. iter_values = iter(values)
  242. try:
  243. previous_value = next(iter_values)
  244. except StopIteration:
  245. return
  246. for value in iter_values:
  247. yield False, previous_value
  248. previous_value = value
  249. yield True, previous_value''',
  250. "python",
  251. line_numbers=True,
  252. )
  253. table = Table("foo", "bar", "baz")
  254. table.add_row("1", "2", "3")
  255. progress_renderables = [
  256. "You can make the terminal shorter and taller to see the live table hide"
  257. "Text may be printed while the progress bars are rendering.",
  258. Panel("In fact, [i]any[/i] renderable will work"),
  259. "Such as [magenta]tables[/]...",
  260. table,
  261. "Pretty printed structures...",
  262. {"type": "example", "text": "Pretty printed"},
  263. "Syntax...",
  264. syntax,
  265. Rule("Give it a try!"),
  266. ]
  267. examples = cycle(progress_renderables)
  268. exchanges = [
  269. "SGD",
  270. "MYR",
  271. "EUR",
  272. "USD",
  273. "AUD",
  274. "JPY",
  275. "CNH",
  276. "HKD",
  277. "CAD",
  278. "INR",
  279. "DKK",
  280. "GBP",
  281. "RUB",
  282. "NZD",
  283. "MXN",
  284. "IDR",
  285. "TWD",
  286. "THB",
  287. "VND",
  288. ]
  289. with Live(console=console) as live_table:
  290. exchange_rate_dict: Dict[Tuple[str, str], float] = {}
  291. for index in range(100):
  292. select_exchange = exchanges[index % len(exchanges)]
  293. for exchange in exchanges:
  294. if exchange == select_exchange:
  295. continue
  296. time.sleep(0.4)
  297. if random.randint(0, 10) < 1:
  298. console.log(next(examples))
  299. exchange_rate_dict[(select_exchange, exchange)] = 200 / (
  300. (random.random() * 320) + 1
  301. )
  302. if len(exchange_rate_dict) > len(exchanges) - 1:
  303. exchange_rate_dict.pop(list(exchange_rate_dict.keys())[0])
  304. table = Table(title="Exchange Rates")
  305. table.add_column("Source Currency")
  306. table.add_column("Destination Currency")
  307. table.add_column("Exchange Rate")
  308. for ((source, dest), exchange_rate) in exchange_rate_dict.items():
  309. table.add_row(
  310. source,
  311. dest,
  312. Text(
  313. f"{exchange_rate:.4f}",
  314. style="red" if exchange_rate < 1.0 else "green",
  315. ),
  316. )
  317. live_table.update(Align.center(table))