console.py 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661
  1. import inspect
  2. import os
  3. import sys
  4. import threading
  5. import zlib
  6. from abc import ABC, abstractmethod
  7. from dataclasses import dataclass, field
  8. from datetime import datetime
  9. from functools import wraps
  10. from getpass import getpass
  11. from html import escape
  12. from inspect import isclass
  13. from itertools import islice
  14. from math import ceil
  15. from time import monotonic
  16. from types import FrameType, ModuleType, TracebackType
  17. from typing import (
  18. IO,
  19. TYPE_CHECKING,
  20. Any,
  21. Callable,
  22. Dict,
  23. Iterable,
  24. List,
  25. Mapping,
  26. NamedTuple,
  27. Optional,
  28. TextIO,
  29. Tuple,
  30. Type,
  31. Union,
  32. cast,
  33. )
  34. from rich._null_file import NULL_FILE
  35. if sys.version_info >= (3, 8):
  36. from typing import Literal, Protocol, runtime_checkable
  37. else:
  38. from typing_extensions import (
  39. Literal,
  40. Protocol,
  41. runtime_checkable,
  42. ) # pragma: no cover
  43. from . import errors, themes
  44. from ._emoji_replace import _emoji_replace
  45. from ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT
  46. from ._fileno import get_fileno
  47. from ._log_render import FormatTimeCallable, LogRender
  48. from .align import Align, AlignMethod
  49. from .color import ColorSystem, blend_rgb
  50. from .control import Control
  51. from .emoji import EmojiVariant
  52. from .highlighter import NullHighlighter, ReprHighlighter
  53. from .markup import render as render_markup
  54. from .measure import Measurement, measure_renderables
  55. from .pager import Pager, SystemPager
  56. from .pretty import Pretty, is_expandable
  57. from .protocol import rich_cast
  58. from .region import Region
  59. from .scope import render_scope
  60. from .screen import Screen
  61. from .segment import Segment
  62. from .style import Style, StyleType
  63. from .styled import Styled
  64. from .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme
  65. from .text import Text, TextType
  66. from .theme import Theme, ThemeStack
  67. if TYPE_CHECKING:
  68. from ._windows import WindowsConsoleFeatures
  69. from .live import Live
  70. from .status import Status
  71. JUPYTER_DEFAULT_COLUMNS = 115
  72. JUPYTER_DEFAULT_LINES = 100
  73. WINDOWS = sys.platform == "win32"
  74. HighlighterType = Callable[[Union[str, "Text"]], "Text"]
  75. JustifyMethod = Literal["default", "left", "center", "right", "full"]
  76. OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"]
  77. class NoChange:
  78. pass
  79. NO_CHANGE = NoChange()
  80. try:
  81. _STDIN_FILENO = sys.__stdin__.fileno() # type: ignore[union-attr]
  82. except Exception:
  83. _STDIN_FILENO = 0
  84. try:
  85. _STDOUT_FILENO = sys.__stdout__.fileno() # type: ignore[union-attr]
  86. except Exception:
  87. _STDOUT_FILENO = 1
  88. try:
  89. _STDERR_FILENO = sys.__stderr__.fileno() # type: ignore[union-attr]
  90. except Exception:
  91. _STDERR_FILENO = 2
  92. _STD_STREAMS = (_STDIN_FILENO, _STDOUT_FILENO, _STDERR_FILENO)
  93. _STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO)
  94. _TERM_COLORS = {
  95. "kitty": ColorSystem.EIGHT_BIT,
  96. "256color": ColorSystem.EIGHT_BIT,
  97. "16color": ColorSystem.STANDARD,
  98. }
  99. class ConsoleDimensions(NamedTuple):
  100. """Size of the terminal."""
  101. width: int
  102. """The width of the console in 'cells'."""
  103. height: int
  104. """The height of the console in lines."""
  105. @dataclass
  106. class ConsoleOptions:
  107. """Options for __rich_console__ method."""
  108. size: ConsoleDimensions
  109. """Size of console."""
  110. legacy_windows: bool
  111. """legacy_windows: flag for legacy windows."""
  112. min_width: int
  113. """Minimum width of renderable."""
  114. max_width: int
  115. """Maximum width of renderable."""
  116. is_terminal: bool
  117. """True if the target is a terminal, otherwise False."""
  118. encoding: str
  119. """Encoding of terminal."""
  120. max_height: int
  121. """Height of container (starts as terminal)"""
  122. justify: Optional[JustifyMethod] = None
  123. """Justify value override for renderable."""
  124. overflow: Optional[OverflowMethod] = None
  125. """Overflow value override for renderable."""
  126. no_wrap: Optional[bool] = False
  127. """Disable wrapping for text."""
  128. highlight: Optional[bool] = None
  129. """Highlight override for render_str."""
  130. markup: Optional[bool] = None
  131. """Enable markup when rendering strings."""
  132. height: Optional[int] = None
  133. @property
  134. def ascii_only(self) -> bool:
  135. """Check if renderables should use ascii only."""
  136. return not self.encoding.startswith("utf")
  137. def copy(self) -> "ConsoleOptions":
  138. """Return a copy of the options.
  139. Returns:
  140. ConsoleOptions: a copy of self.
  141. """
  142. options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions)
  143. options.__dict__ = self.__dict__.copy()
  144. return options
  145. def update(
  146. self,
  147. *,
  148. width: Union[int, NoChange] = NO_CHANGE,
  149. min_width: Union[int, NoChange] = NO_CHANGE,
  150. max_width: Union[int, NoChange] = NO_CHANGE,
  151. justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE,
  152. overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE,
  153. no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE,
  154. highlight: Union[Optional[bool], NoChange] = NO_CHANGE,
  155. markup: Union[Optional[bool], NoChange] = NO_CHANGE,
  156. height: Union[Optional[int], NoChange] = NO_CHANGE,
  157. ) -> "ConsoleOptions":
  158. """Update values, return a copy."""
  159. options = self.copy()
  160. if not isinstance(width, NoChange):
  161. options.min_width = options.max_width = max(0, width)
  162. if not isinstance(min_width, NoChange):
  163. options.min_width = min_width
  164. if not isinstance(max_width, NoChange):
  165. options.max_width = max_width
  166. if not isinstance(justify, NoChange):
  167. options.justify = justify
  168. if not isinstance(overflow, NoChange):
  169. options.overflow = overflow
  170. if not isinstance(no_wrap, NoChange):
  171. options.no_wrap = no_wrap
  172. if not isinstance(highlight, NoChange):
  173. options.highlight = highlight
  174. if not isinstance(markup, NoChange):
  175. options.markup = markup
  176. if not isinstance(height, NoChange):
  177. if height is not None:
  178. options.max_height = height
  179. options.height = None if height is None else max(0, height)
  180. return options
  181. def update_width(self, width: int) -> "ConsoleOptions":
  182. """Update just the width, return a copy.
  183. Args:
  184. width (int): New width (sets both min_width and max_width)
  185. Returns:
  186. ~ConsoleOptions: New console options instance.
  187. """
  188. options = self.copy()
  189. options.min_width = options.max_width = max(0, width)
  190. return options
  191. def update_height(self, height: int) -> "ConsoleOptions":
  192. """Update the height, and return a copy.
  193. Args:
  194. height (int): New height
  195. Returns:
  196. ~ConsoleOptions: New Console options instance.
  197. """
  198. options = self.copy()
  199. options.max_height = options.height = height
  200. return options
  201. def reset_height(self) -> "ConsoleOptions":
  202. """Return a copy of the options with height set to ``None``.
  203. Returns:
  204. ~ConsoleOptions: New console options instance.
  205. """
  206. options = self.copy()
  207. options.height = None
  208. return options
  209. def update_dimensions(self, width: int, height: int) -> "ConsoleOptions":
  210. """Update the width and height, and return a copy.
  211. Args:
  212. width (int): New width (sets both min_width and max_width).
  213. height (int): New height.
  214. Returns:
  215. ~ConsoleOptions: New console options instance.
  216. """
  217. options = self.copy()
  218. options.min_width = options.max_width = max(0, width)
  219. options.height = options.max_height = height
  220. return options
  221. @runtime_checkable
  222. class RichCast(Protocol):
  223. """An object that may be 'cast' to a console renderable."""
  224. def __rich__(
  225. self,
  226. ) -> Union["ConsoleRenderable", "RichCast", str]: # pragma: no cover
  227. ...
  228. @runtime_checkable
  229. class ConsoleRenderable(Protocol):
  230. """An object that supports the console protocol."""
  231. def __rich_console__(
  232. self, console: "Console", options: "ConsoleOptions"
  233. ) -> "RenderResult": # pragma: no cover
  234. ...
  235. # A type that may be rendered by Console.
  236. RenderableType = Union[ConsoleRenderable, RichCast, str]
  237. """A string or any object that may be rendered by Rich."""
  238. # The result of calling a __rich_console__ method.
  239. RenderResult = Iterable[Union[RenderableType, Segment]]
  240. _null_highlighter = NullHighlighter()
  241. class CaptureError(Exception):
  242. """An error in the Capture context manager."""
  243. class NewLine:
  244. """A renderable to generate new line(s)"""
  245. def __init__(self, count: int = 1) -> None:
  246. self.count = count
  247. def __rich_console__(
  248. self, console: "Console", options: "ConsoleOptions"
  249. ) -> Iterable[Segment]:
  250. yield Segment("\n" * self.count)
  251. class ScreenUpdate:
  252. """Render a list of lines at a given offset."""
  253. def __init__(self, lines: List[List[Segment]], x: int, y: int) -> None:
  254. self._lines = lines
  255. self.x = x
  256. self.y = y
  257. def __rich_console__(
  258. self, console: "Console", options: ConsoleOptions
  259. ) -> RenderResult:
  260. x = self.x
  261. move_to = Control.move_to
  262. for offset, line in enumerate(self._lines, self.y):
  263. yield move_to(x, offset)
  264. yield from line
  265. class Capture:
  266. """Context manager to capture the result of printing to the console.
  267. See :meth:`~rich.console.Console.capture` for how to use.
  268. Args:
  269. console (Console): A console instance to capture output.
  270. """
  271. def __init__(self, console: "Console") -> None:
  272. self._console = console
  273. self._result: Optional[str] = None
  274. def __enter__(self) -> "Capture":
  275. self._console.begin_capture()
  276. return self
  277. def __exit__(
  278. self,
  279. exc_type: Optional[Type[BaseException]],
  280. exc_val: Optional[BaseException],
  281. exc_tb: Optional[TracebackType],
  282. ) -> None:
  283. self._result = self._console.end_capture()
  284. def get(self) -> str:
  285. """Get the result of the capture."""
  286. if self._result is None:
  287. raise CaptureError(
  288. "Capture result is not available until context manager exits."
  289. )
  290. return self._result
  291. class ThemeContext:
  292. """A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage."""
  293. def __init__(self, console: "Console", theme: Theme, inherit: bool = True) -> None:
  294. self.console = console
  295. self.theme = theme
  296. self.inherit = inherit
  297. def __enter__(self) -> "ThemeContext":
  298. self.console.push_theme(self.theme)
  299. return self
  300. def __exit__(
  301. self,
  302. exc_type: Optional[Type[BaseException]],
  303. exc_val: Optional[BaseException],
  304. exc_tb: Optional[TracebackType],
  305. ) -> None:
  306. self.console.pop_theme()
  307. class PagerContext:
  308. """A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage."""
  309. def __init__(
  310. self,
  311. console: "Console",
  312. pager: Optional[Pager] = None,
  313. styles: bool = False,
  314. links: bool = False,
  315. ) -> None:
  316. self._console = console
  317. self.pager = SystemPager() if pager is None else pager
  318. self.styles = styles
  319. self.links = links
  320. def __enter__(self) -> "PagerContext":
  321. self._console._enter_buffer()
  322. return self
  323. def __exit__(
  324. self,
  325. exc_type: Optional[Type[BaseException]],
  326. exc_val: Optional[BaseException],
  327. exc_tb: Optional[TracebackType],
  328. ) -> None:
  329. if exc_type is None:
  330. with self._console._lock:
  331. buffer: List[Segment] = self._console._buffer[:]
  332. del self._console._buffer[:]
  333. segments: Iterable[Segment] = buffer
  334. if not self.styles:
  335. segments = Segment.strip_styles(segments)
  336. elif not self.links:
  337. segments = Segment.strip_links(segments)
  338. content = self._console._render_buffer(segments)
  339. self.pager.show(content)
  340. self._console._exit_buffer()
  341. class ScreenContext:
  342. """A context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage."""
  343. def __init__(
  344. self, console: "Console", hide_cursor: bool, style: StyleType = ""
  345. ) -> None:
  346. self.console = console
  347. self.hide_cursor = hide_cursor
  348. self.screen = Screen(style=style)
  349. self._changed = False
  350. def update(
  351. self, *renderables: RenderableType, style: Optional[StyleType] = None
  352. ) -> None:
  353. """Update the screen.
  354. Args:
  355. renderable (RenderableType, optional): Optional renderable to replace current renderable,
  356. or None for no change. Defaults to None.
  357. style: (Style, optional): Replacement style, or None for no change. Defaults to None.
  358. """
  359. if renderables:
  360. self.screen.renderable = (
  361. Group(*renderables) if len(renderables) > 1 else renderables[0]
  362. )
  363. if style is not None:
  364. self.screen.style = style
  365. self.console.print(self.screen, end="")
  366. def __enter__(self) -> "ScreenContext":
  367. self._changed = self.console.set_alt_screen(True)
  368. if self._changed and self.hide_cursor:
  369. self.console.show_cursor(False)
  370. return self
  371. def __exit__(
  372. self,
  373. exc_type: Optional[Type[BaseException]],
  374. exc_val: Optional[BaseException],
  375. exc_tb: Optional[TracebackType],
  376. ) -> None:
  377. if self._changed:
  378. self.console.set_alt_screen(False)
  379. if self.hide_cursor:
  380. self.console.show_cursor(True)
  381. class Group:
  382. """Takes a group of renderables and returns a renderable object that renders the group.
  383. Args:
  384. renderables (Iterable[RenderableType]): An iterable of renderable objects.
  385. fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
  386. """
  387. def __init__(self, *renderables: "RenderableType", fit: bool = True) -> None:
  388. self._renderables = renderables
  389. self.fit = fit
  390. self._render: Optional[List[RenderableType]] = None
  391. @property
  392. def renderables(self) -> List["RenderableType"]:
  393. if self._render is None:
  394. self._render = list(self._renderables)
  395. return self._render
  396. def __rich_measure__(
  397. self, console: "Console", options: "ConsoleOptions"
  398. ) -> "Measurement":
  399. if self.fit:
  400. return measure_renderables(console, options, self.renderables)
  401. else:
  402. return Measurement(options.max_width, options.max_width)
  403. def __rich_console__(
  404. self, console: "Console", options: "ConsoleOptions"
  405. ) -> RenderResult:
  406. yield from self.renderables
  407. def group(fit: bool = True) -> Callable[..., Callable[..., Group]]:
  408. """A decorator that turns an iterable of renderables in to a group.
  409. Args:
  410. fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
  411. """
  412. def decorator(
  413. method: Callable[..., Iterable[RenderableType]]
  414. ) -> Callable[..., Group]:
  415. """Convert a method that returns an iterable of renderables in to a Group."""
  416. @wraps(method)
  417. def _replace(*args: Any, **kwargs: Any) -> Group:
  418. renderables = method(*args, **kwargs)
  419. return Group(*renderables, fit=fit)
  420. return _replace
  421. return decorator
  422. def _is_jupyter() -> bool: # pragma: no cover
  423. """Check if we're running in a Jupyter notebook."""
  424. try:
  425. get_ipython # type: ignore[name-defined]
  426. except NameError:
  427. return False
  428. ipython = get_ipython() # type: ignore[name-defined]
  429. shell = ipython.__class__.__name__
  430. if (
  431. "google.colab" in str(ipython.__class__)
  432. or os.getenv("DATABRICKS_RUNTIME_VERSION")
  433. or shell == "ZMQInteractiveShell"
  434. ):
  435. return True # Jupyter notebook or qtconsole
  436. elif shell == "TerminalInteractiveShell":
  437. return False # Terminal running IPython
  438. else:
  439. return False # Other type (?)
  440. COLOR_SYSTEMS = {
  441. "standard": ColorSystem.STANDARD,
  442. "256": ColorSystem.EIGHT_BIT,
  443. "truecolor": ColorSystem.TRUECOLOR,
  444. "windows": ColorSystem.WINDOWS,
  445. }
  446. _COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()}
  447. @dataclass
  448. class ConsoleThreadLocals(threading.local):
  449. """Thread local values for Console context."""
  450. theme_stack: ThemeStack
  451. buffer: List[Segment] = field(default_factory=list)
  452. buffer_index: int = 0
  453. class RenderHook(ABC):
  454. """Provides hooks in to the render process."""
  455. @abstractmethod
  456. def process_renderables(
  457. self, renderables: List[ConsoleRenderable]
  458. ) -> List[ConsoleRenderable]:
  459. """Called with a list of objects to render.
  460. This method can return a new list of renderables, or modify and return the same list.
  461. Args:
  462. renderables (List[ConsoleRenderable]): A number of renderable objects.
  463. Returns:
  464. List[ConsoleRenderable]: A replacement list of renderables.
  465. """
  466. _windows_console_features: Optional["WindowsConsoleFeatures"] = None
  467. def get_windows_console_features() -> "WindowsConsoleFeatures": # pragma: no cover
  468. global _windows_console_features
  469. if _windows_console_features is not None:
  470. return _windows_console_features
  471. from ._windows import get_windows_console_features
  472. _windows_console_features = get_windows_console_features()
  473. return _windows_console_features
  474. def detect_legacy_windows() -> bool:
  475. """Detect legacy Windows."""
  476. return WINDOWS and not get_windows_console_features().vt
  477. class Console:
  478. """A high level console interface.
  479. Args:
  480. color_system (str, optional): The color system supported by your terminal,
  481. either ``"standard"``, ``"256"`` or ``"truecolor"``. Leave as ``"auto"`` to autodetect.
  482. force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.
  483. force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.
  484. force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None.
  485. soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False.
  486. theme (Theme, optional): An optional style theme object, or ``None`` for default theme.
  487. stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False.
  488. file (IO, optional): A file object where the console should write to. Defaults to stdout.
  489. quiet (bool, Optional): Boolean to suppress all output. Defaults to False.
  490. width (int, optional): The width of the terminal. Leave as default to auto-detect width.
  491. height (int, optional): The height of the terminal. Leave as default to auto-detect height.
  492. style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None.
  493. no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None.
  494. tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8.
  495. record (bool, optional): Boolean to enable recording of terminal output,
  496. required to call :meth:`export_html`, :meth:`export_svg`, and :meth:`export_text`. Defaults to False.
  497. markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.
  498. emoji (bool, optional): Enable emoji code. Defaults to True.
  499. emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None.
  500. highlight (bool, optional): Enable automatic highlighting. Defaults to True.
  501. log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True.
  502. log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True.
  503. log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%X] ".
  504. highlighter (HighlighterType, optional): Default highlighter.
  505. legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``.
  506. safe_box (bool, optional): Restrict box options that don't render on legacy Windows.
  507. get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log),
  508. or None for datetime.now.
  509. get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic.
  510. """
  511. _environ: Mapping[str, str] = os.environ
  512. def __init__(
  513. self,
  514. *,
  515. color_system: Optional[
  516. Literal["auto", "standard", "256", "truecolor", "windows"]
  517. ] = "auto",
  518. force_terminal: Optional[bool] = None,
  519. force_jupyter: Optional[bool] = None,
  520. force_interactive: Optional[bool] = None,
  521. soft_wrap: bool = False,
  522. theme: Optional[Theme] = None,
  523. stderr: bool = False,
  524. file: Optional[IO[str]] = None,
  525. quiet: bool = False,
  526. width: Optional[int] = None,
  527. height: Optional[int] = None,
  528. style: Optional[StyleType] = None,
  529. no_color: Optional[bool] = None,
  530. tab_size: int = 8,
  531. record: bool = False,
  532. markup: bool = True,
  533. emoji: bool = True,
  534. emoji_variant: Optional[EmojiVariant] = None,
  535. highlight: bool = True,
  536. log_time: bool = True,
  537. log_path: bool = True,
  538. log_time_format: Union[str, FormatTimeCallable] = "[%X]",
  539. highlighter: Optional["HighlighterType"] = ReprHighlighter(),
  540. legacy_windows: Optional[bool] = None,
  541. safe_box: bool = True,
  542. get_datetime: Optional[Callable[[], datetime]] = None,
  543. get_time: Optional[Callable[[], float]] = None,
  544. _environ: Optional[Mapping[str, str]] = None,
  545. ):
  546. # Copy of os.environ allows us to replace it for testing
  547. if _environ is not None:
  548. self._environ = _environ
  549. self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter
  550. if self.is_jupyter:
  551. if width is None:
  552. jupyter_columns = self._environ.get("JUPYTER_COLUMNS")
  553. if jupyter_columns is not None and jupyter_columns.isdigit():
  554. width = int(jupyter_columns)
  555. else:
  556. width = JUPYTER_DEFAULT_COLUMNS
  557. if height is None:
  558. jupyter_lines = self._environ.get("JUPYTER_LINES")
  559. if jupyter_lines is not None and jupyter_lines.isdigit():
  560. height = int(jupyter_lines)
  561. else:
  562. height = JUPYTER_DEFAULT_LINES
  563. self.tab_size = tab_size
  564. self.record = record
  565. self._markup = markup
  566. self._emoji = emoji
  567. self._emoji_variant: Optional[EmojiVariant] = emoji_variant
  568. self._highlight = highlight
  569. self.legacy_windows: bool = (
  570. (detect_legacy_windows() and not self.is_jupyter)
  571. if legacy_windows is None
  572. else legacy_windows
  573. )
  574. if width is None:
  575. columns = self._environ.get("COLUMNS")
  576. if columns is not None and columns.isdigit():
  577. width = int(columns) - self.legacy_windows
  578. if height is None:
  579. lines = self._environ.get("LINES")
  580. if lines is not None and lines.isdigit():
  581. height = int(lines)
  582. self.soft_wrap = soft_wrap
  583. self._width = width
  584. self._height = height
  585. self._color_system: Optional[ColorSystem]
  586. self._force_terminal = None
  587. if force_terminal is not None:
  588. self._force_terminal = force_terminal
  589. self._file = file
  590. self.quiet = quiet
  591. self.stderr = stderr
  592. if color_system is None:
  593. self._color_system = None
  594. elif color_system == "auto":
  595. self._color_system = self._detect_color_system()
  596. else:
  597. self._color_system = COLOR_SYSTEMS[color_system]
  598. self._lock = threading.RLock()
  599. self._log_render = LogRender(
  600. show_time=log_time,
  601. show_path=log_path,
  602. time_format=log_time_format,
  603. )
  604. self.highlighter: HighlighterType = highlighter or _null_highlighter
  605. self.safe_box = safe_box
  606. self.get_datetime = get_datetime or datetime.now
  607. self.get_time = get_time or monotonic
  608. self.style = style
  609. self.no_color = (
  610. no_color if no_color is not None else "NO_COLOR" in self._environ
  611. )
  612. self.is_interactive = (
  613. (self.is_terminal and not self.is_dumb_terminal)
  614. if force_interactive is None
  615. else force_interactive
  616. )
  617. self._record_buffer_lock = threading.RLock()
  618. self._thread_locals = ConsoleThreadLocals(
  619. theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme)
  620. )
  621. self._record_buffer: List[Segment] = []
  622. self._render_hooks: List[RenderHook] = []
  623. self._live: Optional["Live"] = None
  624. self._is_alt_screen = False
  625. def __repr__(self) -> str:
  626. return f"<console width={self.width} {self._color_system!s}>"
  627. @property
  628. def file(self) -> IO[str]:
  629. """Get the file object to write to."""
  630. file = self._file or (sys.stderr if self.stderr else sys.stdout)
  631. file = getattr(file, "rich_proxied_file", file)
  632. if file is None:
  633. file = NULL_FILE
  634. return file
  635. @file.setter
  636. def file(self, new_file: IO[str]) -> None:
  637. """Set a new file object."""
  638. self._file = new_file
  639. @property
  640. def _buffer(self) -> List[Segment]:
  641. """Get a thread local buffer."""
  642. return self._thread_locals.buffer
  643. @property
  644. def _buffer_index(self) -> int:
  645. """Get a thread local buffer."""
  646. return self._thread_locals.buffer_index
  647. @_buffer_index.setter
  648. def _buffer_index(self, value: int) -> None:
  649. self._thread_locals.buffer_index = value
  650. @property
  651. def _theme_stack(self) -> ThemeStack:
  652. """Get the thread local theme stack."""
  653. return self._thread_locals.theme_stack
  654. def _detect_color_system(self) -> Optional[ColorSystem]:
  655. """Detect color system from env vars."""
  656. if self.is_jupyter:
  657. return ColorSystem.TRUECOLOR
  658. if not self.is_terminal or self.is_dumb_terminal:
  659. return None
  660. if WINDOWS: # pragma: no cover
  661. if self.legacy_windows: # pragma: no cover
  662. return ColorSystem.WINDOWS
  663. windows_console_features = get_windows_console_features()
  664. return (
  665. ColorSystem.TRUECOLOR
  666. if windows_console_features.truecolor
  667. else ColorSystem.EIGHT_BIT
  668. )
  669. else:
  670. color_term = self._environ.get("COLORTERM", "").strip().lower()
  671. if color_term in ("truecolor", "24bit"):
  672. return ColorSystem.TRUECOLOR
  673. term = self._environ.get("TERM", "").strip().lower()
  674. _term_name, _hyphen, colors = term.rpartition("-")
  675. color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD)
  676. return color_system
  677. def _enter_buffer(self) -> None:
  678. """Enter in to a buffer context, and buffer all output."""
  679. self._buffer_index += 1
  680. def _exit_buffer(self) -> None:
  681. """Leave buffer context, and render content if required."""
  682. self._buffer_index -= 1
  683. self._check_buffer()
  684. def set_live(self, live: "Live") -> None:
  685. """Set Live instance. Used by Live context manager.
  686. Args:
  687. live (Live): Live instance using this Console.
  688. Raises:
  689. errors.LiveError: If this Console has a Live context currently active.
  690. """
  691. with self._lock:
  692. if self._live is not None:
  693. raise errors.LiveError("Only one live display may be active at once")
  694. self._live = live
  695. def clear_live(self) -> None:
  696. """Clear the Live instance."""
  697. with self._lock:
  698. self._live = None
  699. def push_render_hook(self, hook: RenderHook) -> None:
  700. """Add a new render hook to the stack.
  701. Args:
  702. hook (RenderHook): Render hook instance.
  703. """
  704. with self._lock:
  705. self._render_hooks.append(hook)
  706. def pop_render_hook(self) -> None:
  707. """Pop the last renderhook from the stack."""
  708. with self._lock:
  709. self._render_hooks.pop()
  710. def __enter__(self) -> "Console":
  711. """Own context manager to enter buffer context."""
  712. self._enter_buffer()
  713. return self
  714. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
  715. """Exit buffer context."""
  716. self._exit_buffer()
  717. def begin_capture(self) -> None:
  718. """Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output."""
  719. self._enter_buffer()
  720. def end_capture(self) -> str:
  721. """End capture mode and return captured string.
  722. Returns:
  723. str: Console output.
  724. """
  725. render_result = self._render_buffer(self._buffer)
  726. del self._buffer[:]
  727. self._exit_buffer()
  728. return render_result
  729. def push_theme(self, theme: Theme, *, inherit: bool = True) -> None:
  730. """Push a new theme on to the top of the stack, replacing the styles from the previous theme.
  731. Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather
  732. than calling this method directly.
  733. Args:
  734. theme (Theme): A theme instance.
  735. inherit (bool, optional): Inherit existing styles. Defaults to True.
  736. """
  737. self._theme_stack.push_theme(theme, inherit=inherit)
  738. def pop_theme(self) -> None:
  739. """Remove theme from top of stack, restoring previous theme."""
  740. self._theme_stack.pop_theme()
  741. def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext:
  742. """Use a different theme for the duration of the context manager.
  743. Args:
  744. theme (Theme): Theme instance to user.
  745. inherit (bool, optional): Inherit existing console styles. Defaults to True.
  746. Returns:
  747. ThemeContext: [description]
  748. """
  749. return ThemeContext(self, theme, inherit)
  750. @property
  751. def color_system(self) -> Optional[str]:
  752. """Get color system string.
  753. Returns:
  754. Optional[str]: "standard", "256" or "truecolor".
  755. """
  756. if self._color_system is not None:
  757. return _COLOR_SYSTEMS_NAMES[self._color_system]
  758. else:
  759. return None
  760. @property
  761. def encoding(self) -> str:
  762. """Get the encoding of the console file, e.g. ``"utf-8"``.
  763. Returns:
  764. str: A standard encoding string.
  765. """
  766. return (getattr(self.file, "encoding", "utf-8") or "utf-8").lower()
  767. @property
  768. def is_terminal(self) -> bool:
  769. """Check if the console is writing to a terminal.
  770. Returns:
  771. bool: True if the console writing to a device capable of
  772. understanding terminal codes, otherwise False.
  773. """
  774. if self._force_terminal is not None:
  775. return self._force_terminal
  776. if hasattr(sys.stdin, "__module__") and sys.stdin.__module__.startswith(
  777. "idlelib"
  778. ):
  779. # Return False for Idle which claims to be a tty but can't handle ansi codes
  780. return False
  781. if self.is_jupyter:
  782. # return False for Jupyter, which may have FORCE_COLOR set
  783. return False
  784. # If FORCE_COLOR env var has any value at all, we assume a terminal.
  785. force_color = self._environ.get("FORCE_COLOR")
  786. if force_color is not None:
  787. self._force_terminal = True
  788. return True
  789. isatty: Optional[Callable[[], bool]] = getattr(self.file, "isatty", None)
  790. try:
  791. return False if isatty is None else isatty()
  792. except ValueError:
  793. # in some situation (at the end of a pytest run for example) isatty() can raise
  794. # ValueError: I/O operation on closed file
  795. # return False because we aren't in a terminal anymore
  796. return False
  797. @property
  798. def is_dumb_terminal(self) -> bool:
  799. """Detect dumb terminal.
  800. Returns:
  801. bool: True if writing to a dumb terminal, otherwise False.
  802. """
  803. _term = self._environ.get("TERM", "")
  804. is_dumb = _term.lower() in ("dumb", "unknown")
  805. return self.is_terminal and is_dumb
  806. @property
  807. def options(self) -> ConsoleOptions:
  808. """Get default console options."""
  809. return ConsoleOptions(
  810. max_height=self.size.height,
  811. size=self.size,
  812. legacy_windows=self.legacy_windows,
  813. min_width=1,
  814. max_width=self.width,
  815. encoding=self.encoding,
  816. is_terminal=self.is_terminal,
  817. )
  818. @property
  819. def size(self) -> ConsoleDimensions:
  820. """Get the size of the console.
  821. Returns:
  822. ConsoleDimensions: A named tuple containing the dimensions.
  823. """
  824. if self._width is not None and self._height is not None:
  825. return ConsoleDimensions(self._width - self.legacy_windows, self._height)
  826. if self.is_dumb_terminal:
  827. return ConsoleDimensions(80, 25)
  828. width: Optional[int] = None
  829. height: Optional[int] = None
  830. streams = _STD_STREAMS_OUTPUT if WINDOWS else _STD_STREAMS
  831. for file_descriptor in streams:
  832. try:
  833. width, height = os.get_terminal_size(file_descriptor)
  834. except (AttributeError, ValueError, OSError): # Probably not a terminal
  835. pass
  836. else:
  837. break
  838. columns = self._environ.get("COLUMNS")
  839. if columns is not None and columns.isdigit():
  840. width = int(columns)
  841. lines = self._environ.get("LINES")
  842. if lines is not None and lines.isdigit():
  843. height = int(lines)
  844. # get_terminal_size can report 0, 0 if run from pseudo-terminal
  845. width = width or 80
  846. height = height or 25
  847. return ConsoleDimensions(
  848. width - self.legacy_windows if self._width is None else self._width,
  849. height if self._height is None else self._height,
  850. )
  851. @size.setter
  852. def size(self, new_size: Tuple[int, int]) -> None:
  853. """Set a new size for the terminal.
  854. Args:
  855. new_size (Tuple[int, int]): New width and height.
  856. """
  857. width, height = new_size
  858. self._width = width
  859. self._height = height
  860. @property
  861. def width(self) -> int:
  862. """Get the width of the console.
  863. Returns:
  864. int: The width (in characters) of the console.
  865. """
  866. return self.size.width
  867. @width.setter
  868. def width(self, width: int) -> None:
  869. """Set width.
  870. Args:
  871. width (int): New width.
  872. """
  873. self._width = width
  874. @property
  875. def height(self) -> int:
  876. """Get the height of the console.
  877. Returns:
  878. int: The height (in lines) of the console.
  879. """
  880. return self.size.height
  881. @height.setter
  882. def height(self, height: int) -> None:
  883. """Set height.
  884. Args:
  885. height (int): new height.
  886. """
  887. self._height = height
  888. def bell(self) -> None:
  889. """Play a 'bell' sound (if supported by the terminal)."""
  890. self.control(Control.bell())
  891. def capture(self) -> Capture:
  892. """A context manager to *capture* the result of print() or log() in a string,
  893. rather than writing it to the console.
  894. Example:
  895. >>> from rich.console import Console
  896. >>> console = Console()
  897. >>> with console.capture() as capture:
  898. ... console.print("[bold magenta]Hello World[/]")
  899. >>> print(capture.get())
  900. Returns:
  901. Capture: Context manager with disables writing to the terminal.
  902. """
  903. capture = Capture(self)
  904. return capture
  905. def pager(
  906. self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False
  907. ) -> PagerContext:
  908. """A context manager to display anything printed within a "pager". The pager application
  909. is defined by the system and will typically support at least pressing a key to scroll.
  910. Args:
  911. pager (Pager, optional): A pager object, or None to use :class:`~rich.pager.SystemPager`. Defaults to None.
  912. styles (bool, optional): Show styles in pager. Defaults to False.
  913. links (bool, optional): Show links in pager. Defaults to False.
  914. Example:
  915. >>> from rich.console import Console
  916. >>> from rich.__main__ import make_test_card
  917. >>> console = Console()
  918. >>> with console.pager():
  919. console.print(make_test_card())
  920. Returns:
  921. PagerContext: A context manager.
  922. """
  923. return PagerContext(self, pager=pager, styles=styles, links=links)
  924. def line(self, count: int = 1) -> None:
  925. """Write new line(s).
  926. Args:
  927. count (int, optional): Number of new lines. Defaults to 1.
  928. """
  929. assert count >= 0, "count must be >= 0"
  930. self.print(NewLine(count))
  931. def clear(self, home: bool = True) -> None:
  932. """Clear the screen.
  933. Args:
  934. home (bool, optional): Also move the cursor to 'home' position. Defaults to True.
  935. """
  936. if home:
  937. self.control(Control.clear(), Control.home())
  938. else:
  939. self.control(Control.clear())
  940. def status(
  941. self,
  942. status: RenderableType,
  943. *,
  944. spinner: str = "dots",
  945. spinner_style: StyleType = "status.spinner",
  946. speed: float = 1.0,
  947. refresh_per_second: float = 12.5,
  948. ) -> "Status":
  949. """Display a status and spinner.
  950. Args:
  951. status (RenderableType): A status renderable (str or Text typically).
  952. spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots".
  953. spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner".
  954. speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.
  955. refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.
  956. Returns:
  957. Status: A Status object that may be used as a context manager.
  958. """
  959. from .status import Status
  960. status_renderable = Status(
  961. status,
  962. console=self,
  963. spinner=spinner,
  964. spinner_style=spinner_style,
  965. speed=speed,
  966. refresh_per_second=refresh_per_second,
  967. )
  968. return status_renderable
  969. def show_cursor(self, show: bool = True) -> bool:
  970. """Show or hide the cursor.
  971. Args:
  972. show (bool, optional): Set visibility of the cursor.
  973. """
  974. if self.is_terminal:
  975. self.control(Control.show_cursor(show))
  976. return True
  977. return False
  978. def set_alt_screen(self, enable: bool = True) -> bool:
  979. """Enables alternative screen mode.
  980. Note, if you enable this mode, you should ensure that is disabled before
  981. the application exits. See :meth:`~rich.Console.screen` for a context manager
  982. that handles this for you.
  983. Args:
  984. enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True.
  985. Returns:
  986. bool: True if the control codes were written.
  987. """
  988. changed = False
  989. if self.is_terminal and not self.legacy_windows:
  990. self.control(Control.alt_screen(enable))
  991. changed = True
  992. self._is_alt_screen = enable
  993. return changed
  994. @property
  995. def is_alt_screen(self) -> bool:
  996. """Check if the alt screen was enabled.
  997. Returns:
  998. bool: True if the alt screen was enabled, otherwise False.
  999. """
  1000. return self._is_alt_screen
  1001. def set_window_title(self, title: str) -> bool:
  1002. """Set the title of the console terminal window.
  1003. Warning: There is no means within Rich of "resetting" the window title to its
  1004. previous value, meaning the title you set will persist even after your application
  1005. exits.
  1006. ``fish`` shell resets the window title before and after each command by default,
  1007. negating this issue. Windows Terminal and command prompt will also reset the title for you.
  1008. Most other shells and terminals, however, do not do this.
  1009. Some terminals may require configuration changes before you can set the title.
  1010. Some terminals may not support setting the title at all.
  1011. Other software (including the terminal itself, the shell, custom prompts, plugins, etc.)
  1012. may also set the terminal window title. This could result in whatever value you write
  1013. using this method being overwritten.
  1014. Args:
  1015. title (str): The new title of the terminal window.
  1016. Returns:
  1017. bool: True if the control code to change the terminal title was
  1018. written, otherwise False. Note that a return value of True
  1019. does not guarantee that the window title has actually changed,
  1020. since the feature may be unsupported/disabled in some terminals.
  1021. """
  1022. if self.is_terminal:
  1023. self.control(Control.title(title))
  1024. return True
  1025. return False
  1026. def screen(
  1027. self, hide_cursor: bool = True, style: Optional[StyleType] = None
  1028. ) -> "ScreenContext":
  1029. """Context manager to enable and disable 'alternative screen' mode.
  1030. Args:
  1031. hide_cursor (bool, optional): Also hide the cursor. Defaults to False.
  1032. style (Style, optional): Optional style for screen. Defaults to None.
  1033. Returns:
  1034. ~ScreenContext: Context which enables alternate screen on enter, and disables it on exit.
  1035. """
  1036. return ScreenContext(self, hide_cursor=hide_cursor, style=style or "")
  1037. def measure(
  1038. self, renderable: RenderableType, *, options: Optional[ConsoleOptions] = None
  1039. ) -> Measurement:
  1040. """Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains
  1041. information regarding the number of characters required to print the renderable.
  1042. Args:
  1043. renderable (RenderableType): Any renderable or string.
  1044. options (Optional[ConsoleOptions], optional): Options to use when measuring, or None
  1045. to use default options. Defaults to None.
  1046. Returns:
  1047. Measurement: A measurement of the renderable.
  1048. """
  1049. measurement = Measurement.get(self, options or self.options, renderable)
  1050. return measurement
  1051. def render(
  1052. self, renderable: RenderableType, options: Optional[ConsoleOptions] = None
  1053. ) -> Iterable[Segment]:
  1054. """Render an object in to an iterable of `Segment` instances.
  1055. This method contains the logic for rendering objects with the console protocol.
  1056. You are unlikely to need to use it directly, unless you are extending the library.
  1057. Args:
  1058. renderable (RenderableType): An object supporting the console protocol, or
  1059. an object that may be converted to a string.
  1060. options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None.
  1061. Returns:
  1062. Iterable[Segment]: An iterable of segments that may be rendered.
  1063. """
  1064. _options = options or self.options
  1065. if _options.max_width < 1:
  1066. # No space to render anything. This prevents potential recursion errors.
  1067. return
  1068. render_iterable: RenderResult
  1069. renderable = rich_cast(renderable)
  1070. if hasattr(renderable, "__rich_console__") and not isclass(renderable):
  1071. render_iterable = renderable.__rich_console__(self, _options)
  1072. elif isinstance(renderable, str):
  1073. text_renderable = self.render_str(
  1074. renderable, highlight=_options.highlight, markup=_options.markup
  1075. )
  1076. render_iterable = text_renderable.__rich_console__(self, _options)
  1077. else:
  1078. raise errors.NotRenderableError(
  1079. f"Unable to render {renderable!r}; "
  1080. "A str, Segment or object with __rich_console__ method is required"
  1081. )
  1082. try:
  1083. iter_render = iter(render_iterable)
  1084. except TypeError:
  1085. raise errors.NotRenderableError(
  1086. f"object {render_iterable!r} is not renderable"
  1087. )
  1088. _Segment = Segment
  1089. _options = _options.reset_height()
  1090. for render_output in iter_render:
  1091. if isinstance(render_output, _Segment):
  1092. yield render_output
  1093. else:
  1094. yield from self.render(render_output, _options)
  1095. def render_lines(
  1096. self,
  1097. renderable: RenderableType,
  1098. options: Optional[ConsoleOptions] = None,
  1099. *,
  1100. style: Optional[Style] = None,
  1101. pad: bool = True,
  1102. new_lines: bool = False,
  1103. ) -> List[List[Segment]]:
  1104. """Render objects in to a list of lines.
  1105. The output of render_lines is useful when further formatting of rendered console text
  1106. is required, such as the Panel class which draws a border around any renderable object.
  1107. Args:
  1108. renderable (RenderableType): Any object renderable in the console.
  1109. options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``.
  1110. style (Style, optional): Optional style to apply to renderables. Defaults to ``None``.
  1111. pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``.
  1112. new_lines (bool, optional): Include "\n" characters at end of lines.
  1113. Returns:
  1114. List[List[Segment]]: A list of lines, where a line is a list of Segment objects.
  1115. """
  1116. with self._lock:
  1117. render_options = options or self.options
  1118. _rendered = self.render(renderable, render_options)
  1119. if style:
  1120. _rendered = Segment.apply_style(_rendered, style)
  1121. render_height = render_options.height
  1122. if render_height is not None:
  1123. render_height = max(0, render_height)
  1124. lines = list(
  1125. islice(
  1126. Segment.split_and_crop_lines(
  1127. _rendered,
  1128. render_options.max_width,
  1129. include_new_lines=new_lines,
  1130. pad=pad,
  1131. style=style,
  1132. ),
  1133. None,
  1134. render_height,
  1135. )
  1136. )
  1137. if render_options.height is not None:
  1138. extra_lines = render_options.height - len(lines)
  1139. if extra_lines > 0:
  1140. pad_line = [
  1141. (
  1142. [
  1143. Segment(" " * render_options.max_width, style),
  1144. Segment("\n"),
  1145. ]
  1146. if new_lines
  1147. else [Segment(" " * render_options.max_width, style)]
  1148. )
  1149. ]
  1150. lines.extend(pad_line * extra_lines)
  1151. return lines
  1152. def render_str(
  1153. self,
  1154. text: str,
  1155. *,
  1156. style: Union[str, Style] = "",
  1157. justify: Optional[JustifyMethod] = None,
  1158. overflow: Optional[OverflowMethod] = None,
  1159. emoji: Optional[bool] = None,
  1160. markup: Optional[bool] = None,
  1161. highlight: Optional[bool] = None,
  1162. highlighter: Optional[HighlighterType] = None,
  1163. ) -> "Text":
  1164. """Convert a string to a Text instance. This is called automatically if
  1165. you print or log a string.
  1166. Args:
  1167. text (str): Text to render.
  1168. style (Union[str, Style], optional): Style to apply to rendered text.
  1169. justify (str, optional): Justify method: "default", "left", "center", "full", or "right". Defaults to ``None``.
  1170. overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to ``None``.
  1171. emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default.
  1172. markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default.
  1173. highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default.
  1174. highlighter (HighlighterType, optional): Optional highlighter to apply.
  1175. Returns:
  1176. ConsoleRenderable: Renderable object.
  1177. """
  1178. emoji_enabled = emoji or (emoji is None and self._emoji)
  1179. markup_enabled = markup or (markup is None and self._markup)
  1180. highlight_enabled = highlight or (highlight is None and self._highlight)
  1181. if markup_enabled:
  1182. rich_text = render_markup(
  1183. text,
  1184. style=style,
  1185. emoji=emoji_enabled,
  1186. emoji_variant=self._emoji_variant,
  1187. )
  1188. rich_text.justify = justify
  1189. rich_text.overflow = overflow
  1190. else:
  1191. rich_text = Text(
  1192. (
  1193. _emoji_replace(text, default_variant=self._emoji_variant)
  1194. if emoji_enabled
  1195. else text
  1196. ),
  1197. justify=justify,
  1198. overflow=overflow,
  1199. style=style,
  1200. )
  1201. _highlighter = (highlighter or self.highlighter) if highlight_enabled else None
  1202. if _highlighter is not None:
  1203. highlight_text = _highlighter(str(rich_text))
  1204. highlight_text.copy_styles(rich_text)
  1205. return highlight_text
  1206. return rich_text
  1207. def get_style(
  1208. self, name: Union[str, Style], *, default: Optional[Union[Style, str]] = None
  1209. ) -> Style:
  1210. """Get a Style instance by its theme name or parse a definition.
  1211. Args:
  1212. name (str): The name of a style or a style definition.
  1213. Returns:
  1214. Style: A Style object.
  1215. Raises:
  1216. MissingStyle: If no style could be parsed from name.
  1217. """
  1218. if isinstance(name, Style):
  1219. return name
  1220. try:
  1221. style = self._theme_stack.get(name)
  1222. if style is None:
  1223. style = Style.parse(name)
  1224. return style.copy() if style.link else style
  1225. except errors.StyleSyntaxError as error:
  1226. if default is not None:
  1227. return self.get_style(default)
  1228. raise errors.MissingStyle(
  1229. f"Failed to get style {name!r}; {error}"
  1230. ) from None
  1231. def _collect_renderables(
  1232. self,
  1233. objects: Iterable[Any],
  1234. sep: str,
  1235. end: str,
  1236. *,
  1237. justify: Optional[JustifyMethod] = None,
  1238. emoji: Optional[bool] = None,
  1239. markup: Optional[bool] = None,
  1240. highlight: Optional[bool] = None,
  1241. ) -> List[ConsoleRenderable]:
  1242. """Combine a number of renderables and text into one renderable.
  1243. Args:
  1244. objects (Iterable[Any]): Anything that Rich can render.
  1245. sep (str): String to write between print data.
  1246. end (str): String to write at end of print data.
  1247. justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
  1248. emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default.
  1249. markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.
  1250. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.
  1251. Returns:
  1252. List[ConsoleRenderable]: A list of things to render.
  1253. """
  1254. renderables: List[ConsoleRenderable] = []
  1255. _append = renderables.append
  1256. text: List[Text] = []
  1257. append_text = text.append
  1258. append = _append
  1259. if justify in ("left", "center", "right"):
  1260. def align_append(renderable: RenderableType) -> None:
  1261. _append(Align(renderable, cast(AlignMethod, justify)))
  1262. append = align_append
  1263. _highlighter: HighlighterType = _null_highlighter
  1264. if highlight or (highlight is None and self._highlight):
  1265. _highlighter = self.highlighter
  1266. def check_text() -> None:
  1267. if text:
  1268. sep_text = Text(sep, justify=justify, end=end)
  1269. append(sep_text.join(text))
  1270. text.clear()
  1271. for renderable in objects:
  1272. renderable = rich_cast(renderable)
  1273. if isinstance(renderable, str):
  1274. append_text(
  1275. self.render_str(
  1276. renderable,
  1277. emoji=emoji,
  1278. markup=markup,
  1279. highlight=highlight,
  1280. highlighter=_highlighter,
  1281. )
  1282. )
  1283. elif isinstance(renderable, Text):
  1284. append_text(renderable)
  1285. elif isinstance(renderable, ConsoleRenderable):
  1286. check_text()
  1287. append(renderable)
  1288. elif is_expandable(renderable):
  1289. check_text()
  1290. append(Pretty(renderable, highlighter=_highlighter))
  1291. else:
  1292. append_text(_highlighter(str(renderable)))
  1293. check_text()
  1294. if self.style is not None:
  1295. style = self.get_style(self.style)
  1296. renderables = [Styled(renderable, style) for renderable in renderables]
  1297. return renderables
  1298. def rule(
  1299. self,
  1300. title: TextType = "",
  1301. *,
  1302. characters: str = "─",
  1303. style: Union[str, Style] = "rule.line",
  1304. align: AlignMethod = "center",
  1305. ) -> None:
  1306. """Draw a line with optional centered title.
  1307. Args:
  1308. title (str, optional): Text to render over the rule. Defaults to "".
  1309. characters (str, optional): Character(s) to form the line. Defaults to "─".
  1310. style (str, optional): Style of line. Defaults to "rule.line".
  1311. align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center".
  1312. """
  1313. from .rule import Rule
  1314. rule = Rule(title=title, characters=characters, style=style, align=align)
  1315. self.print(rule)
  1316. def control(self, *control: Control) -> None:
  1317. """Insert non-printing control codes.
  1318. Args:
  1319. control_codes (str): Control codes, such as those that may move the cursor.
  1320. """
  1321. if not self.is_dumb_terminal:
  1322. with self:
  1323. self._buffer.extend(_control.segment for _control in control)
  1324. def out(
  1325. self,
  1326. *objects: Any,
  1327. sep: str = " ",
  1328. end: str = "\n",
  1329. style: Optional[Union[str, Style]] = None,
  1330. highlight: Optional[bool] = None,
  1331. ) -> None:
  1332. """Output to the terminal. This is a low-level way of writing to the terminal which unlike
  1333. :meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will
  1334. optionally apply highlighting and a basic style.
  1335. Args:
  1336. sep (str, optional): String to write between print data. Defaults to " ".
  1337. end (str, optional): String to write at end of print data. Defaults to "\\\\n".
  1338. style (Union[str, Style], optional): A style to apply to output. Defaults to None.
  1339. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use
  1340. console default. Defaults to ``None``.
  1341. """
  1342. raw_output: str = sep.join(str(_object) for _object in objects)
  1343. self.print(
  1344. raw_output,
  1345. style=style,
  1346. highlight=highlight,
  1347. emoji=False,
  1348. markup=False,
  1349. no_wrap=True,
  1350. overflow="ignore",
  1351. crop=False,
  1352. end=end,
  1353. )
  1354. def print(
  1355. self,
  1356. *objects: Any,
  1357. sep: str = " ",
  1358. end: str = "\n",
  1359. style: Optional[Union[str, Style]] = None,
  1360. justify: Optional[JustifyMethod] = None,
  1361. overflow: Optional[OverflowMethod] = None,
  1362. no_wrap: Optional[bool] = None,
  1363. emoji: Optional[bool] = None,
  1364. markup: Optional[bool] = None,
  1365. highlight: Optional[bool] = None,
  1366. width: Optional[int] = None,
  1367. height: Optional[int] = None,
  1368. crop: bool = True,
  1369. soft_wrap: Optional[bool] = None,
  1370. new_line_start: bool = False,
  1371. ) -> None:
  1372. """Print to the console.
  1373. Args:
  1374. objects (positional args): Objects to log to the terminal.
  1375. sep (str, optional): String to write between print data. Defaults to " ".
  1376. end (str, optional): String to write at end of print data. Defaults to "\\\\n".
  1377. style (Union[str, Style], optional): A style to apply to output. Defaults to None.
  1378. justify (str, optional): Justify method: "default", "left", "right", "center", or "full". Defaults to ``None``.
  1379. overflow (str, optional): Overflow method: "ignore", "crop", "fold", or "ellipsis". Defaults to None.
  1380. no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.
  1381. emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.
  1382. markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.
  1383. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.
  1384. width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.
  1385. crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.
  1386. soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for
  1387. Console default. Defaults to ``None``.
  1388. new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``.
  1389. """
  1390. if not objects:
  1391. objects = (NewLine(),)
  1392. if soft_wrap is None:
  1393. soft_wrap = self.soft_wrap
  1394. if soft_wrap:
  1395. if no_wrap is None:
  1396. no_wrap = True
  1397. if overflow is None:
  1398. overflow = "ignore"
  1399. crop = False
  1400. render_hooks = self._render_hooks[:]
  1401. with self:
  1402. renderables = self._collect_renderables(
  1403. objects,
  1404. sep,
  1405. end,
  1406. justify=justify,
  1407. emoji=emoji,
  1408. markup=markup,
  1409. highlight=highlight,
  1410. )
  1411. for hook in render_hooks:
  1412. renderables = hook.process_renderables(renderables)
  1413. render_options = self.options.update(
  1414. justify=justify,
  1415. overflow=overflow,
  1416. width=min(width, self.width) if width is not None else NO_CHANGE,
  1417. height=height,
  1418. no_wrap=no_wrap,
  1419. markup=markup,
  1420. highlight=highlight,
  1421. )
  1422. new_segments: List[Segment] = []
  1423. extend = new_segments.extend
  1424. render = self.render
  1425. if style is None:
  1426. for renderable in renderables:
  1427. extend(render(renderable, render_options))
  1428. else:
  1429. for renderable in renderables:
  1430. extend(
  1431. Segment.apply_style(
  1432. render(renderable, render_options), self.get_style(style)
  1433. )
  1434. )
  1435. if new_line_start:
  1436. if (
  1437. len("".join(segment.text for segment in new_segments).splitlines())
  1438. > 1
  1439. ):
  1440. new_segments.insert(0, Segment.line())
  1441. if crop:
  1442. buffer_extend = self._buffer.extend
  1443. for line in Segment.split_and_crop_lines(
  1444. new_segments, self.width, pad=False
  1445. ):
  1446. buffer_extend(line)
  1447. else:
  1448. self._buffer.extend(new_segments)
  1449. def print_json(
  1450. self,
  1451. json: Optional[str] = None,
  1452. *,
  1453. data: Any = None,
  1454. indent: Union[None, int, str] = 2,
  1455. highlight: bool = True,
  1456. skip_keys: bool = False,
  1457. ensure_ascii: bool = False,
  1458. check_circular: bool = True,
  1459. allow_nan: bool = True,
  1460. default: Optional[Callable[[Any], Any]] = None,
  1461. sort_keys: bool = False,
  1462. ) -> None:
  1463. """Pretty prints JSON. Output will be valid JSON.
  1464. Args:
  1465. json (Optional[str]): A string containing JSON.
  1466. data (Any): If json is not supplied, then encode this data.
  1467. indent (Union[None, int, str], optional): Number of spaces to indent. Defaults to 2.
  1468. highlight (bool, optional): Enable highlighting of output: Defaults to True.
  1469. skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
  1470. ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
  1471. check_circular (bool, optional): Check for circular references. Defaults to True.
  1472. allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
  1473. default (Callable, optional): A callable that converts values that can not be encoded
  1474. in to something that can be JSON encoded. Defaults to None.
  1475. sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
  1476. """
  1477. from rich.json import JSON
  1478. if json is None:
  1479. json_renderable = JSON.from_data(
  1480. data,
  1481. indent=indent,
  1482. highlight=highlight,
  1483. skip_keys=skip_keys,
  1484. ensure_ascii=ensure_ascii,
  1485. check_circular=check_circular,
  1486. allow_nan=allow_nan,
  1487. default=default,
  1488. sort_keys=sort_keys,
  1489. )
  1490. else:
  1491. if not isinstance(json, str):
  1492. raise TypeError(
  1493. f"json must be str. Did you mean print_json(data={json!r}) ?"
  1494. )
  1495. json_renderable = JSON(
  1496. json,
  1497. indent=indent,
  1498. highlight=highlight,
  1499. skip_keys=skip_keys,
  1500. ensure_ascii=ensure_ascii,
  1501. check_circular=check_circular,
  1502. allow_nan=allow_nan,
  1503. default=default,
  1504. sort_keys=sort_keys,
  1505. )
  1506. self.print(json_renderable, soft_wrap=True)
  1507. def update_screen(
  1508. self,
  1509. renderable: RenderableType,
  1510. *,
  1511. region: Optional[Region] = None,
  1512. options: Optional[ConsoleOptions] = None,
  1513. ) -> None:
  1514. """Update the screen at a given offset.
  1515. Args:
  1516. renderable (RenderableType): A Rich renderable.
  1517. region (Region, optional): Region of screen to update, or None for entire screen. Defaults to None.
  1518. x (int, optional): x offset. Defaults to 0.
  1519. y (int, optional): y offset. Defaults to 0.
  1520. Raises:
  1521. errors.NoAltScreen: If the Console isn't in alt screen mode.
  1522. """
  1523. if not self.is_alt_screen:
  1524. raise errors.NoAltScreen("Alt screen must be enabled to call update_screen")
  1525. render_options = options or self.options
  1526. if region is None:
  1527. x = y = 0
  1528. render_options = render_options.update_dimensions(
  1529. render_options.max_width, render_options.height or self.height
  1530. )
  1531. else:
  1532. x, y, width, height = region
  1533. render_options = render_options.update_dimensions(width, height)
  1534. lines = self.render_lines(renderable, options=render_options)
  1535. self.update_screen_lines(lines, x, y)
  1536. def update_screen_lines(
  1537. self, lines: List[List[Segment]], x: int = 0, y: int = 0
  1538. ) -> None:
  1539. """Update lines of the screen at a given offset.
  1540. Args:
  1541. lines (List[List[Segment]]): Rendered lines (as produced by :meth:`~rich.Console.render_lines`).
  1542. x (int, optional): x offset (column no). Defaults to 0.
  1543. y (int, optional): y offset (column no). Defaults to 0.
  1544. Raises:
  1545. errors.NoAltScreen: If the Console isn't in alt screen mode.
  1546. """
  1547. if not self.is_alt_screen:
  1548. raise errors.NoAltScreen("Alt screen must be enabled to call update_screen")
  1549. screen_update = ScreenUpdate(lines, x, y)
  1550. segments = self.render(screen_update)
  1551. self._buffer.extend(segments)
  1552. self._check_buffer()
  1553. def print_exception(
  1554. self,
  1555. *,
  1556. width: Optional[int] = 100,
  1557. extra_lines: int = 3,
  1558. theme: Optional[str] = None,
  1559. word_wrap: bool = False,
  1560. show_locals: bool = False,
  1561. suppress: Iterable[Union[str, ModuleType]] = (),
  1562. max_frames: int = 100,
  1563. ) -> None:
  1564. """Prints a rich render of the last exception and traceback.
  1565. Args:
  1566. width (Optional[int], optional): Number of characters used to render code. Defaults to 100.
  1567. extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
  1568. theme (str, optional): Override pygments theme used in traceback
  1569. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
  1570. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  1571. suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
  1572. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
  1573. """
  1574. from .traceback import Traceback
  1575. traceback = Traceback(
  1576. width=width,
  1577. extra_lines=extra_lines,
  1578. theme=theme,
  1579. word_wrap=word_wrap,
  1580. show_locals=show_locals,
  1581. suppress=suppress,
  1582. max_frames=max_frames,
  1583. )
  1584. self.print(traceback)
  1585. @staticmethod
  1586. def _caller_frame_info(
  1587. offset: int,
  1588. currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe,
  1589. ) -> Tuple[str, int, Dict[str, Any]]:
  1590. """Get caller frame information.
  1591. Args:
  1592. offset (int): the caller offset within the current frame stack.
  1593. currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to
  1594. retrieve the current frame. Defaults to ``inspect.currentframe``.
  1595. Returns:
  1596. Tuple[str, int, Dict[str, Any]]: A tuple containing the filename, the line number and
  1597. the dictionary of local variables associated with the caller frame.
  1598. Raises:
  1599. RuntimeError: If the stack offset is invalid.
  1600. """
  1601. # Ignore the frame of this local helper
  1602. offset += 1
  1603. frame = currentframe()
  1604. if frame is not None:
  1605. # Use the faster currentframe where implemented
  1606. while offset and frame is not None:
  1607. frame = frame.f_back
  1608. offset -= 1
  1609. assert frame is not None
  1610. return frame.f_code.co_filename, frame.f_lineno, frame.f_locals
  1611. else:
  1612. # Fallback to the slower stack
  1613. frame_info = inspect.stack()[offset]
  1614. return frame_info.filename, frame_info.lineno, frame_info.frame.f_locals
  1615. def log(
  1616. self,
  1617. *objects: Any,
  1618. sep: str = " ",
  1619. end: str = "\n",
  1620. style: Optional[Union[str, Style]] = None,
  1621. justify: Optional[JustifyMethod] = None,
  1622. emoji: Optional[bool] = None,
  1623. markup: Optional[bool] = None,
  1624. highlight: Optional[bool] = None,
  1625. log_locals: bool = False,
  1626. _stack_offset: int = 1,
  1627. ) -> None:
  1628. """Log rich content to the terminal.
  1629. Args:
  1630. objects (positional args): Objects to log to the terminal.
  1631. sep (str, optional): String to write between print data. Defaults to " ".
  1632. end (str, optional): String to write at end of print data. Defaults to "\\\\n".
  1633. style (Union[str, Style], optional): A style to apply to output. Defaults to None.
  1634. justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
  1635. emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None.
  1636. markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None.
  1637. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None.
  1638. log_locals (bool, optional): Boolean to enable logging of locals where ``log()``
  1639. was called. Defaults to False.
  1640. _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.
  1641. """
  1642. if not objects:
  1643. objects = (NewLine(),)
  1644. render_hooks = self._render_hooks[:]
  1645. with self:
  1646. renderables = self._collect_renderables(
  1647. objects,
  1648. sep,
  1649. end,
  1650. justify=justify,
  1651. emoji=emoji,
  1652. markup=markup,
  1653. highlight=highlight,
  1654. )
  1655. if style is not None:
  1656. renderables = [Styled(renderable, style) for renderable in renderables]
  1657. filename, line_no, locals = self._caller_frame_info(_stack_offset)
  1658. link_path = None if filename.startswith("<") else os.path.abspath(filename)
  1659. path = filename.rpartition(os.sep)[-1]
  1660. if log_locals:
  1661. locals_map = {
  1662. key: value
  1663. for key, value in locals.items()
  1664. if not key.startswith("__")
  1665. }
  1666. renderables.append(render_scope(locals_map, title="[i]locals"))
  1667. renderables = [
  1668. self._log_render(
  1669. self,
  1670. renderables,
  1671. log_time=self.get_datetime(),
  1672. path=path,
  1673. line_no=line_no,
  1674. link_path=link_path,
  1675. )
  1676. ]
  1677. for hook in render_hooks:
  1678. renderables = hook.process_renderables(renderables)
  1679. new_segments: List[Segment] = []
  1680. extend = new_segments.extend
  1681. render = self.render
  1682. render_options = self.options
  1683. for renderable in renderables:
  1684. extend(render(renderable, render_options))
  1685. buffer_extend = self._buffer.extend
  1686. for line in Segment.split_and_crop_lines(
  1687. new_segments, self.width, pad=False
  1688. ):
  1689. buffer_extend(line)
  1690. def on_broken_pipe(self) -> None:
  1691. """This function is called when a `BrokenPipeError` is raised.
  1692. This can occur when piping Textual output in Linux and macOS.
  1693. The default implementation is to exit the app, but you could implement
  1694. this method in a subclass to change the behavior.
  1695. See https://docs.python.org/3/library/signal.html#note-on-sigpipe for details.
  1696. """
  1697. self.quiet = True
  1698. devnull = os.open(os.devnull, os.O_WRONLY)
  1699. os.dup2(devnull, sys.stdout.fileno())
  1700. raise SystemExit(1)
  1701. def _check_buffer(self) -> None:
  1702. """Check if the buffer may be rendered. Render it if it can (e.g. Console.quiet is False)
  1703. Rendering is supported on Windows, Unix and Jupyter environments. For
  1704. legacy Windows consoles, the win32 API is called directly.
  1705. This method will also record what it renders if recording is enabled via Console.record.
  1706. """
  1707. if self.quiet:
  1708. del self._buffer[:]
  1709. return
  1710. try:
  1711. self._write_buffer()
  1712. except BrokenPipeError:
  1713. self.on_broken_pipe()
  1714. def _write_buffer(self) -> None:
  1715. """Write the buffer to the output file."""
  1716. with self._lock:
  1717. if self.record and not self._buffer_index:
  1718. with self._record_buffer_lock:
  1719. self._record_buffer.extend(self._buffer[:])
  1720. if self._buffer_index == 0:
  1721. if self.is_jupyter: # pragma: no cover
  1722. from .jupyter import display
  1723. display(self._buffer, self._render_buffer(self._buffer[:]))
  1724. del self._buffer[:]
  1725. else:
  1726. if WINDOWS:
  1727. use_legacy_windows_render = False
  1728. if self.legacy_windows:
  1729. fileno = get_fileno(self.file)
  1730. if fileno is not None:
  1731. use_legacy_windows_render = (
  1732. fileno in _STD_STREAMS_OUTPUT
  1733. )
  1734. if use_legacy_windows_render:
  1735. from rich._win32_console import LegacyWindowsTerm
  1736. from rich._windows_renderer import legacy_windows_render
  1737. buffer = self._buffer[:]
  1738. if self.no_color and self._color_system:
  1739. buffer = list(Segment.remove_color(buffer))
  1740. legacy_windows_render(buffer, LegacyWindowsTerm(self.file))
  1741. else:
  1742. # Either a non-std stream on legacy Windows, or modern Windows.
  1743. text = self._render_buffer(self._buffer[:])
  1744. # https://bugs.python.org/issue37871
  1745. # https://github.com/python/cpython/issues/82052
  1746. # We need to avoid writing more than 32Kb in a single write, due to the above bug
  1747. write = self.file.write
  1748. # Worse case scenario, every character is 4 bytes of utf-8
  1749. MAX_WRITE = 32 * 1024 // 4
  1750. try:
  1751. if len(text) <= MAX_WRITE:
  1752. write(text)
  1753. else:
  1754. batch: List[str] = []
  1755. batch_append = batch.append
  1756. size = 0
  1757. for line in text.splitlines(True):
  1758. if size + len(line) > MAX_WRITE and batch:
  1759. write("".join(batch))
  1760. batch.clear()
  1761. size = 0
  1762. batch_append(line)
  1763. size += len(line)
  1764. if batch:
  1765. write("".join(batch))
  1766. batch.clear()
  1767. except UnicodeEncodeError as error:
  1768. error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***"
  1769. raise
  1770. else:
  1771. text = self._render_buffer(self._buffer[:])
  1772. try:
  1773. self.file.write(text)
  1774. except UnicodeEncodeError as error:
  1775. error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***"
  1776. raise
  1777. self.file.flush()
  1778. del self._buffer[:]
  1779. def _render_buffer(self, buffer: Iterable[Segment]) -> str:
  1780. """Render buffered output, and clear buffer."""
  1781. output: List[str] = []
  1782. append = output.append
  1783. color_system = self._color_system
  1784. legacy_windows = self.legacy_windows
  1785. not_terminal = not self.is_terminal
  1786. if self.no_color and color_system:
  1787. buffer = Segment.remove_color(buffer)
  1788. for text, style, control in buffer:
  1789. if style:
  1790. append(
  1791. style.render(
  1792. text,
  1793. color_system=color_system,
  1794. legacy_windows=legacy_windows,
  1795. )
  1796. )
  1797. elif not (not_terminal and control):
  1798. append(text)
  1799. rendered = "".join(output)
  1800. return rendered
  1801. def input(
  1802. self,
  1803. prompt: TextType = "",
  1804. *,
  1805. markup: bool = True,
  1806. emoji: bool = True,
  1807. password: bool = False,
  1808. stream: Optional[TextIO] = None,
  1809. ) -> str:
  1810. """Displays a prompt and waits for input from the user. The prompt may contain color / style.
  1811. It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded.
  1812. Args:
  1813. prompt (Union[str, Text]): Text to render in the prompt.
  1814. markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.
  1815. emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.
  1816. password: (bool, optional): Hide typed text. Defaults to False.
  1817. stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.
  1818. Returns:
  1819. str: Text read from stdin.
  1820. """
  1821. if prompt:
  1822. self.print(prompt, markup=markup, emoji=emoji, end="")
  1823. if password:
  1824. result = getpass("", stream=stream)
  1825. else:
  1826. if stream:
  1827. result = stream.readline()
  1828. else:
  1829. result = input()
  1830. return result
  1831. def export_text(self, *, clear: bool = True, styles: bool = False) -> str:
  1832. """Generate text from console contents (requires record=True argument in constructor).
  1833. Args:
  1834. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1835. styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.
  1836. Defaults to ``False``.
  1837. Returns:
  1838. str: String containing console contents.
  1839. """
  1840. assert (
  1841. self.record
  1842. ), "To export console contents set record=True in the constructor or instance"
  1843. with self._record_buffer_lock:
  1844. if styles:
  1845. text = "".join(
  1846. (style.render(text) if style else text)
  1847. for text, style, _ in self._record_buffer
  1848. )
  1849. else:
  1850. text = "".join(
  1851. segment.text
  1852. for segment in self._record_buffer
  1853. if not segment.control
  1854. )
  1855. if clear:
  1856. del self._record_buffer[:]
  1857. return text
  1858. def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> None:
  1859. """Generate text from console and save to a given location (requires record=True argument in constructor).
  1860. Args:
  1861. path (str): Path to write text files.
  1862. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1863. styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.
  1864. Defaults to ``False``.
  1865. """
  1866. text = self.export_text(clear=clear, styles=styles)
  1867. with open(path, "w", encoding="utf-8") as write_file:
  1868. write_file.write(text)
  1869. def export_html(
  1870. self,
  1871. *,
  1872. theme: Optional[TerminalTheme] = None,
  1873. clear: bool = True,
  1874. code_format: Optional[str] = None,
  1875. inline_styles: bool = False,
  1876. ) -> str:
  1877. """Generate HTML from console contents (requires record=True argument in constructor).
  1878. Args:
  1879. theme (TerminalTheme, optional): TerminalTheme object containing console colors.
  1880. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1881. code_format (str, optional): Format string to render HTML. In addition to '{foreground}',
  1882. '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``.
  1883. inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
  1884. larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
  1885. Defaults to False.
  1886. Returns:
  1887. str: String containing console contents as HTML.
  1888. """
  1889. assert (
  1890. self.record
  1891. ), "To export console contents set record=True in the constructor or instance"
  1892. fragments: List[str] = []
  1893. append = fragments.append
  1894. _theme = theme or DEFAULT_TERMINAL_THEME
  1895. stylesheet = ""
  1896. render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format
  1897. with self._record_buffer_lock:
  1898. if inline_styles:
  1899. for text, style, _ in Segment.filter_control(
  1900. Segment.simplify(self._record_buffer)
  1901. ):
  1902. text = escape(text)
  1903. if style:
  1904. rule = style.get_html_style(_theme)
  1905. if style.link:
  1906. text = f'<a href="{style.link}">{text}</a>'
  1907. text = f'<span style="{rule}">{text}</span>' if rule else text
  1908. append(text)
  1909. else:
  1910. styles: Dict[str, int] = {}
  1911. for text, style, _ in Segment.filter_control(
  1912. Segment.simplify(self._record_buffer)
  1913. ):
  1914. text = escape(text)
  1915. if style:
  1916. rule = style.get_html_style(_theme)
  1917. style_number = styles.setdefault(rule, len(styles) + 1)
  1918. if style.link:
  1919. text = f'<a class="r{style_number}" href="{style.link}">{text}</a>'
  1920. else:
  1921. text = f'<span class="r{style_number}">{text}</span>'
  1922. append(text)
  1923. stylesheet_rules: List[str] = []
  1924. stylesheet_append = stylesheet_rules.append
  1925. for style_rule, style_number in styles.items():
  1926. if style_rule:
  1927. stylesheet_append(f".r{style_number} {{{style_rule}}}")
  1928. stylesheet = "\n".join(stylesheet_rules)
  1929. rendered_code = render_code_format.format(
  1930. code="".join(fragments),
  1931. stylesheet=stylesheet,
  1932. foreground=_theme.foreground_color.hex,
  1933. background=_theme.background_color.hex,
  1934. )
  1935. if clear:
  1936. del self._record_buffer[:]
  1937. return rendered_code
  1938. def save_html(
  1939. self,
  1940. path: str,
  1941. *,
  1942. theme: Optional[TerminalTheme] = None,
  1943. clear: bool = True,
  1944. code_format: str = CONSOLE_HTML_FORMAT,
  1945. inline_styles: bool = False,
  1946. ) -> None:
  1947. """Generate HTML from console contents and write to a file (requires record=True argument in constructor).
  1948. Args:
  1949. path (str): Path to write html file.
  1950. theme (TerminalTheme, optional): TerminalTheme object containing console colors.
  1951. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1952. code_format (str, optional): Format string to render HTML. In addition to '{foreground}',
  1953. '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``.
  1954. inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
  1955. larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
  1956. Defaults to False.
  1957. """
  1958. html = self.export_html(
  1959. theme=theme,
  1960. clear=clear,
  1961. code_format=code_format,
  1962. inline_styles=inline_styles,
  1963. )
  1964. with open(path, "w", encoding="utf-8") as write_file:
  1965. write_file.write(html)
  1966. def export_svg(
  1967. self,
  1968. *,
  1969. title: str = "Rich",
  1970. theme: Optional[TerminalTheme] = None,
  1971. clear: bool = True,
  1972. code_format: str = CONSOLE_SVG_FORMAT,
  1973. font_aspect_ratio: float = 0.61,
  1974. unique_id: Optional[str] = None,
  1975. ) -> str:
  1976. """
  1977. Generate an SVG from the console contents (requires record=True in Console constructor).
  1978. Args:
  1979. title (str, optional): The title of the tab in the output image
  1980. theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal
  1981. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``
  1982. code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables
  1983. into the string in order to form the final SVG output. The default template used and the variables
  1984. injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.
  1985. font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format``
  1986. string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font).
  1987. If you aren't specifying a different font inside ``code_format``, you probably don't need this.
  1988. unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node
  1989. ids). If not set, this defaults to a computed value based on the recorded content.
  1990. """
  1991. from rich.cells import cell_len
  1992. style_cache: Dict[Style, str] = {}
  1993. def get_svg_style(style: Style) -> str:
  1994. """Convert a Style to CSS rules for SVG."""
  1995. if style in style_cache:
  1996. return style_cache[style]
  1997. css_rules = []
  1998. color = (
  1999. _theme.foreground_color
  2000. if (style.color is None or style.color.is_default)
  2001. else style.color.get_truecolor(_theme)
  2002. )
  2003. bgcolor = (
  2004. _theme.background_color
  2005. if (style.bgcolor is None or style.bgcolor.is_default)
  2006. else style.bgcolor.get_truecolor(_theme)
  2007. )
  2008. if style.reverse:
  2009. color, bgcolor = bgcolor, color
  2010. if style.dim:
  2011. color = blend_rgb(color, bgcolor, 0.4)
  2012. css_rules.append(f"fill: {color.hex}")
  2013. if style.bold:
  2014. css_rules.append("font-weight: bold")
  2015. if style.italic:
  2016. css_rules.append("font-style: italic;")
  2017. if style.underline:
  2018. css_rules.append("text-decoration: underline;")
  2019. if style.strike:
  2020. css_rules.append("text-decoration: line-through;")
  2021. css = ";".join(css_rules)
  2022. style_cache[style] = css
  2023. return css
  2024. _theme = theme or SVG_EXPORT_THEME
  2025. width = self.width
  2026. char_height = 20
  2027. char_width = char_height * font_aspect_ratio
  2028. line_height = char_height * 1.22
  2029. margin_top = 1
  2030. margin_right = 1
  2031. margin_bottom = 1
  2032. margin_left = 1
  2033. padding_top = 40
  2034. padding_right = 8
  2035. padding_bottom = 8
  2036. padding_left = 8
  2037. padding_width = padding_left + padding_right
  2038. padding_height = padding_top + padding_bottom
  2039. margin_width = margin_left + margin_right
  2040. margin_height = margin_top + margin_bottom
  2041. text_backgrounds: List[str] = []
  2042. text_group: List[str] = []
  2043. classes: Dict[str, int] = {}
  2044. style_no = 1
  2045. def escape_text(text: str) -> str:
  2046. """HTML escape text and replace spaces with nbsp."""
  2047. return escape(text).replace(" ", "&#160;")
  2048. def make_tag(
  2049. name: str, content: Optional[str] = None, **attribs: object
  2050. ) -> str:
  2051. """Make a tag from name, content, and attributes."""
  2052. def stringify(value: object) -> str:
  2053. if isinstance(value, (float)):
  2054. return format(value, "g")
  2055. return str(value)
  2056. tag_attribs = " ".join(
  2057. f'{k.lstrip("_").replace("_", "-")}="{stringify(v)}"'
  2058. for k, v in attribs.items()
  2059. )
  2060. return (
  2061. f"<{name} {tag_attribs}>{content}</{name}>"
  2062. if content
  2063. else f"<{name} {tag_attribs}/>"
  2064. )
  2065. with self._record_buffer_lock:
  2066. segments = list(Segment.filter_control(self._record_buffer))
  2067. if clear:
  2068. self._record_buffer.clear()
  2069. if unique_id is None:
  2070. unique_id = "terminal-" + str(
  2071. zlib.adler32(
  2072. ("".join(repr(segment) for segment in segments)).encode(
  2073. "utf-8",
  2074. "ignore",
  2075. )
  2076. + title.encode("utf-8", "ignore")
  2077. )
  2078. )
  2079. y = 0
  2080. for y, line in enumerate(Segment.split_and_crop_lines(segments, length=width)):
  2081. x = 0
  2082. for text, style, _control in line:
  2083. style = style or Style()
  2084. rules = get_svg_style(style)
  2085. if rules not in classes:
  2086. classes[rules] = style_no
  2087. style_no += 1
  2088. class_name = f"r{classes[rules]}"
  2089. if style.reverse:
  2090. has_background = True
  2091. background = (
  2092. _theme.foreground_color.hex
  2093. if style.color is None
  2094. else style.color.get_truecolor(_theme).hex
  2095. )
  2096. else:
  2097. bgcolor = style.bgcolor
  2098. has_background = bgcolor is not None and not bgcolor.is_default
  2099. background = (
  2100. _theme.background_color.hex
  2101. if style.bgcolor is None
  2102. else style.bgcolor.get_truecolor(_theme).hex
  2103. )
  2104. text_length = cell_len(text)
  2105. if has_background:
  2106. text_backgrounds.append(
  2107. make_tag(
  2108. "rect",
  2109. fill=background,
  2110. x=x * char_width,
  2111. y=y * line_height + 1.5,
  2112. width=char_width * text_length,
  2113. height=line_height + 0.25,
  2114. shape_rendering="crispEdges",
  2115. )
  2116. )
  2117. if text != " " * len(text):
  2118. text_group.append(
  2119. make_tag(
  2120. "text",
  2121. escape_text(text),
  2122. _class=f"{unique_id}-{class_name}",
  2123. x=x * char_width,
  2124. y=y * line_height + char_height,
  2125. textLength=char_width * len(text),
  2126. clip_path=f"url(#{unique_id}-line-{y})",
  2127. )
  2128. )
  2129. x += cell_len(text)
  2130. line_offsets = [line_no * line_height + 1.5 for line_no in range(y)]
  2131. lines = "\n".join(
  2132. f"""<clipPath id="{unique_id}-line-{line_no}">
  2133. {make_tag("rect", x=0, y=offset, width=char_width * width, height=line_height + 0.25)}
  2134. </clipPath>"""
  2135. for line_no, offset in enumerate(line_offsets)
  2136. )
  2137. styles = "\n".join(
  2138. f".{unique_id}-r{rule_no} {{ {css} }}" for css, rule_no in classes.items()
  2139. )
  2140. backgrounds = "".join(text_backgrounds)
  2141. matrix = "".join(text_group)
  2142. terminal_width = ceil(width * char_width + padding_width)
  2143. terminal_height = (y + 1) * line_height + padding_height
  2144. chrome = make_tag(
  2145. "rect",
  2146. fill=_theme.background_color.hex,
  2147. stroke="rgba(255,255,255,0.35)",
  2148. stroke_width="1",
  2149. x=margin_left,
  2150. y=margin_top,
  2151. width=terminal_width,
  2152. height=terminal_height,
  2153. rx=8,
  2154. )
  2155. title_color = _theme.foreground_color.hex
  2156. if title:
  2157. chrome += make_tag(
  2158. "text",
  2159. escape_text(title),
  2160. _class=f"{unique_id}-title",
  2161. fill=title_color,
  2162. text_anchor="middle",
  2163. x=terminal_width // 2,
  2164. y=margin_top + char_height + 6,
  2165. )
  2166. chrome += f"""
  2167. <g transform="translate(26,22)">
  2168. <circle cx="0" cy="0" r="7" fill="#ff5f57"/>
  2169. <circle cx="22" cy="0" r="7" fill="#febc2e"/>
  2170. <circle cx="44" cy="0" r="7" fill="#28c840"/>
  2171. </g>
  2172. """
  2173. svg = code_format.format(
  2174. unique_id=unique_id,
  2175. char_width=char_width,
  2176. char_height=char_height,
  2177. line_height=line_height,
  2178. terminal_width=char_width * width - 1,
  2179. terminal_height=(y + 1) * line_height - 1,
  2180. width=terminal_width + margin_width,
  2181. height=terminal_height + margin_height,
  2182. terminal_x=margin_left + padding_left,
  2183. terminal_y=margin_top + padding_top,
  2184. styles=styles,
  2185. chrome=chrome,
  2186. backgrounds=backgrounds,
  2187. matrix=matrix,
  2188. lines=lines,
  2189. )
  2190. return svg
  2191. def save_svg(
  2192. self,
  2193. path: str,
  2194. *,
  2195. title: str = "Rich",
  2196. theme: Optional[TerminalTheme] = None,
  2197. clear: bool = True,
  2198. code_format: str = CONSOLE_SVG_FORMAT,
  2199. font_aspect_ratio: float = 0.61,
  2200. unique_id: Optional[str] = None,
  2201. ) -> None:
  2202. """Generate an SVG file from the console contents (requires record=True in Console constructor).
  2203. Args:
  2204. path (str): The path to write the SVG to.
  2205. title (str, optional): The title of the tab in the output image
  2206. theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal
  2207. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``
  2208. code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables
  2209. into the string in order to form the final SVG output. The default template used and the variables
  2210. injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.
  2211. font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format``
  2212. string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font).
  2213. If you aren't specifying a different font inside ``code_format``, you probably don't need this.
  2214. unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node
  2215. ids). If not set, this defaults to a computed value based on the recorded content.
  2216. """
  2217. svg = self.export_svg(
  2218. title=title,
  2219. theme=theme,
  2220. clear=clear,
  2221. code_format=code_format,
  2222. font_aspect_ratio=font_aspect_ratio,
  2223. unique_id=unique_id,
  2224. )
  2225. with open(path, "w", encoding="utf-8") as write_file:
  2226. write_file.write(svg)
  2227. def _svg_hash(svg_main_code: str) -> str:
  2228. """Returns a unique hash for the given SVG main code.
  2229. Args:
  2230. svg_main_code (str): The content we're going to inject in the SVG envelope.
  2231. Returns:
  2232. str: a hash of the given content
  2233. """
  2234. return str(zlib.adler32(svg_main_code.encode()))
  2235. if __name__ == "__main__": # pragma: no cover
  2236. console = Console(record=True)
  2237. console.log(
  2238. "JSONRPC [i]request[/i]",
  2239. 5,
  2240. 1.3,
  2241. True,
  2242. False,
  2243. None,
  2244. {
  2245. "jsonrpc": "2.0",
  2246. "method": "subtract",
  2247. "params": {"minuend": 42, "subtrahend": 23},
  2248. "id": 3,
  2249. },
  2250. )
  2251. console.log("Hello, World!", "{'a': 1}", repr(console))
  2252. console.print(
  2253. {
  2254. "name": None,
  2255. "empty": [],
  2256. "quiz": {
  2257. "sport": {
  2258. "answered": True,
  2259. "q1": {
  2260. "question": "Which one is correct team name in NBA?",
  2261. "options": [
  2262. "New York Bulls",
  2263. "Los Angeles Kings",
  2264. "Golden State Warriors",
  2265. "Huston Rocket",
  2266. ],
  2267. "answer": "Huston Rocket",
  2268. },
  2269. },
  2270. "maths": {
  2271. "answered": False,
  2272. "q1": {
  2273. "question": "5 + 7 = ?",
  2274. "options": [10, 11, 12, 13],
  2275. "answer": 12,
  2276. },
  2277. "q2": {
  2278. "question": "12 - 8 = ?",
  2279. "options": [1, 2, 3, 4],
  2280. "answer": 4,
  2281. },
  2282. },
  2283. },
  2284. }
  2285. )