console.py 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633
  1. import inspect
  2. import os
  3. import platform
  4. import sys
  5. import threading
  6. import zlib
  7. from abc import ABC, abstractmethod
  8. from dataclasses import dataclass, field
  9. from datetime import datetime
  10. from functools import wraps
  11. from getpass import getpass
  12. from html import escape
  13. from inspect import isclass
  14. from itertools import islice
  15. from math import ceil
  16. from time import monotonic
  17. from types import FrameType, ModuleType, TracebackType
  18. from typing import (
  19. IO,
  20. TYPE_CHECKING,
  21. Any,
  22. Callable,
  23. Dict,
  24. Iterable,
  25. List,
  26. Mapping,
  27. NamedTuple,
  28. Optional,
  29. TextIO,
  30. Tuple,
  31. Type,
  32. Union,
  33. cast,
  34. )
  35. from pip._vendor.rich._null_file import NULL_FILE
  36. if sys.version_info >= (3, 8):
  37. from typing import Literal, Protocol, runtime_checkable
  38. else:
  39. from pip._vendor.typing_extensions import (
  40. Literal,
  41. Protocol,
  42. runtime_checkable,
  43. ) # pragma: no cover
  44. from . import errors, themes
  45. from ._emoji_replace import _emoji_replace
  46. from ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT
  47. from ._fileno import get_fileno
  48. from ._log_render import FormatTimeCallable, LogRender
  49. from .align import Align, AlignMethod
  50. from .color import ColorSystem, blend_rgb
  51. from .control import Control
  52. from .emoji import EmojiVariant
  53. from .highlighter import NullHighlighter, ReprHighlighter
  54. from .markup import render as render_markup
  55. from .measure import Measurement, measure_renderables
  56. from .pager import Pager, SystemPager
  57. from .pretty import Pretty, is_expandable
  58. from .protocol import rich_cast
  59. from .region import Region
  60. from .scope import render_scope
  61. from .screen import Screen
  62. from .segment import Segment
  63. from .style import Style, StyleType
  64. from .styled import Styled
  65. from .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme
  66. from .text import Text, TextType
  67. from .theme import Theme, ThemeStack
  68. if TYPE_CHECKING:
  69. from ._windows import WindowsConsoleFeatures
  70. from .live import Live
  71. from .status import Status
  72. JUPYTER_DEFAULT_COLUMNS = 115
  73. JUPYTER_DEFAULT_LINES = 100
  74. WINDOWS = platform.system() == "Windows"
  75. HighlighterType = Callable[[Union[str, "Text"]], "Text"]
  76. JustifyMethod = Literal["default", "left", "center", "right", "full"]
  77. OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"]
  78. class NoChange:
  79. pass
  80. NO_CHANGE = NoChange()
  81. try:
  82. _STDIN_FILENO = sys.__stdin__.fileno()
  83. except Exception:
  84. _STDIN_FILENO = 0
  85. try:
  86. _STDOUT_FILENO = sys.__stdout__.fileno()
  87. except Exception:
  88. _STDOUT_FILENO = 1
  89. try:
  90. _STDERR_FILENO = sys.__stderr__.fileno()
  91. except Exception:
  92. _STDERR_FILENO = 2
  93. _STD_STREAMS = (_STDIN_FILENO, _STDOUT_FILENO, _STDERR_FILENO)
  94. _STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO)
  95. _TERM_COLORS = {
  96. "kitty": ColorSystem.EIGHT_BIT,
  97. "256color": ColorSystem.EIGHT_BIT,
  98. "16color": ColorSystem.STANDARD,
  99. }
  100. class ConsoleDimensions(NamedTuple):
  101. """Size of the terminal."""
  102. width: int
  103. """The width of the console in 'cells'."""
  104. height: int
  105. """The height of the console in lines."""
  106. @dataclass
  107. class ConsoleOptions:
  108. """Options for __rich_console__ method."""
  109. size: ConsoleDimensions
  110. """Size of console."""
  111. legacy_windows: bool
  112. """legacy_windows: flag for legacy windows."""
  113. min_width: int
  114. """Minimum width of renderable."""
  115. max_width: int
  116. """Maximum width of renderable."""
  117. is_terminal: bool
  118. """True if the target is a terminal, otherwise False."""
  119. encoding: str
  120. """Encoding of terminal."""
  121. max_height: int
  122. """Height of container (starts as terminal)"""
  123. justify: Optional[JustifyMethod] = None
  124. """Justify value override for renderable."""
  125. overflow: Optional[OverflowMethod] = None
  126. """Overflow value override for renderable."""
  127. no_wrap: Optional[bool] = False
  128. """Disable wrapping for text."""
  129. highlight: Optional[bool] = None
  130. """Highlight override for render_str."""
  131. markup: Optional[bool] = None
  132. """Enable markup when rendering strings."""
  133. height: Optional[int] = None
  134. @property
  135. def ascii_only(self) -> bool:
  136. """Check if renderables should use ascii only."""
  137. return not self.encoding.startswith("utf")
  138. def copy(self) -> "ConsoleOptions":
  139. """Return a copy of the options.
  140. Returns:
  141. ConsoleOptions: a copy of self.
  142. """
  143. options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions)
  144. options.__dict__ = self.__dict__.copy()
  145. return options
  146. def update(
  147. self,
  148. *,
  149. width: Union[int, NoChange] = NO_CHANGE,
  150. min_width: Union[int, NoChange] = NO_CHANGE,
  151. max_width: Union[int, NoChange] = NO_CHANGE,
  152. justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE,
  153. overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE,
  154. no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE,
  155. highlight: Union[Optional[bool], NoChange] = NO_CHANGE,
  156. markup: Union[Optional[bool], NoChange] = NO_CHANGE,
  157. height: Union[Optional[int], NoChange] = NO_CHANGE,
  158. ) -> "ConsoleOptions":
  159. """Update values, return a copy."""
  160. options = self.copy()
  161. if not isinstance(width, NoChange):
  162. options.min_width = options.max_width = max(0, width)
  163. if not isinstance(min_width, NoChange):
  164. options.min_width = min_width
  165. if not isinstance(max_width, NoChange):
  166. options.max_width = max_width
  167. if not isinstance(justify, NoChange):
  168. options.justify = justify
  169. if not isinstance(overflow, NoChange):
  170. options.overflow = overflow
  171. if not isinstance(no_wrap, NoChange):
  172. options.no_wrap = no_wrap
  173. if not isinstance(highlight, NoChange):
  174. options.highlight = highlight
  175. if not isinstance(markup, NoChange):
  176. options.markup = markup
  177. if not isinstance(height, NoChange):
  178. if height is not None:
  179. options.max_height = height
  180. options.height = None if height is None else max(0, height)
  181. return options
  182. def update_width(self, width: int) -> "ConsoleOptions":
  183. """Update just the width, return a copy.
  184. Args:
  185. width (int): New width (sets both min_width and max_width)
  186. Returns:
  187. ~ConsoleOptions: New console options instance.
  188. """
  189. options = self.copy()
  190. options.min_width = options.max_width = max(0, width)
  191. return options
  192. def update_height(self, height: int) -> "ConsoleOptions":
  193. """Update the height, and return a copy.
  194. Args:
  195. height (int): New height
  196. Returns:
  197. ~ConsoleOptions: New Console options instance.
  198. """
  199. options = self.copy()
  200. options.max_height = options.height = height
  201. return options
  202. def reset_height(self) -> "ConsoleOptions":
  203. """Return a copy of the options with height set to ``None``.
  204. Returns:
  205. ~ConsoleOptions: New console options instance.
  206. """
  207. options = self.copy()
  208. options.height = None
  209. return options
  210. def update_dimensions(self, width: int, height: int) -> "ConsoleOptions":
  211. """Update the width and height, and return a copy.
  212. Args:
  213. width (int): New width (sets both min_width and max_width).
  214. height (int): New height.
  215. Returns:
  216. ~ConsoleOptions: New console options instance.
  217. """
  218. options = self.copy()
  219. options.min_width = options.max_width = max(0, width)
  220. options.height = options.max_height = height
  221. return options
  222. @runtime_checkable
  223. class RichCast(Protocol):
  224. """An object that may be 'cast' to a console renderable."""
  225. def __rich__(
  226. self,
  227. ) -> Union["ConsoleRenderable", "RichCast", str]: # pragma: no cover
  228. ...
  229. @runtime_checkable
  230. class ConsoleRenderable(Protocol):
  231. """An object that supports the console protocol."""
  232. def __rich_console__(
  233. self, console: "Console", options: "ConsoleOptions"
  234. ) -> "RenderResult": # pragma: no cover
  235. ...
  236. # A type that may be rendered by Console.
  237. RenderableType = Union[ConsoleRenderable, RichCast, str]
  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. isatty: Optional[Callable[[], bool]] = getattr(self.file, "isatty", None)
  789. try:
  790. return False if isatty is None else isatty()
  791. except ValueError:
  792. # in some situation (at the end of a pytest run for example) isatty() can raise
  793. # ValueError: I/O operation on closed file
  794. # return False because we aren't in a terminal anymore
  795. return False
  796. @property
  797. def is_dumb_terminal(self) -> bool:
  798. """Detect dumb terminal.
  799. Returns:
  800. bool: True if writing to a dumb terminal, otherwise False.
  801. """
  802. _term = self._environ.get("TERM", "")
  803. is_dumb = _term.lower() in ("dumb", "unknown")
  804. return self.is_terminal and is_dumb
  805. @property
  806. def options(self) -> ConsoleOptions:
  807. """Get default console options."""
  808. return ConsoleOptions(
  809. max_height=self.size.height,
  810. size=self.size,
  811. legacy_windows=self.legacy_windows,
  812. min_width=1,
  813. max_width=self.width,
  814. encoding=self.encoding,
  815. is_terminal=self.is_terminal,
  816. )
  817. @property
  818. def size(self) -> ConsoleDimensions:
  819. """Get the size of the console.
  820. Returns:
  821. ConsoleDimensions: A named tuple containing the dimensions.
  822. """
  823. if self._width is not None and self._height is not None:
  824. return ConsoleDimensions(self._width - self.legacy_windows, self._height)
  825. if self.is_dumb_terminal:
  826. return ConsoleDimensions(80, 25)
  827. width: Optional[int] = None
  828. height: Optional[int] = None
  829. if WINDOWS: # pragma: no cover
  830. try:
  831. width, height = os.get_terminal_size()
  832. except (AttributeError, ValueError, OSError): # Probably not a terminal
  833. pass
  834. else:
  835. for file_descriptor in _STD_STREAMS:
  836. try:
  837. width, height = os.get_terminal_size(file_descriptor)
  838. except (AttributeError, ValueError, OSError):
  839. pass
  840. else:
  841. break
  842. columns = self._environ.get("COLUMNS")
  843. if columns is not None and columns.isdigit():
  844. width = int(columns)
  845. lines = self._environ.get("LINES")
  846. if lines is not None and lines.isdigit():
  847. height = int(lines)
  848. # get_terminal_size can report 0, 0 if run from pseudo-terminal
  849. width = width or 80
  850. height = height or 25
  851. return ConsoleDimensions(
  852. width - self.legacy_windows if self._width is None else self._width,
  853. height if self._height is None else self._height,
  854. )
  855. @size.setter
  856. def size(self, new_size: Tuple[int, int]) -> None:
  857. """Set a new size for the terminal.
  858. Args:
  859. new_size (Tuple[int, int]): New width and height.
  860. """
  861. width, height = new_size
  862. self._width = width
  863. self._height = height
  864. @property
  865. def width(self) -> int:
  866. """Get the width of the console.
  867. Returns:
  868. int: The width (in characters) of the console.
  869. """
  870. return self.size.width
  871. @width.setter
  872. def width(self, width: int) -> None:
  873. """Set width.
  874. Args:
  875. width (int): New width.
  876. """
  877. self._width = width
  878. @property
  879. def height(self) -> int:
  880. """Get the height of the console.
  881. Returns:
  882. int: The height (in lines) of the console.
  883. """
  884. return self.size.height
  885. @height.setter
  886. def height(self, height: int) -> None:
  887. """Set height.
  888. Args:
  889. height (int): new height.
  890. """
  891. self._height = height
  892. def bell(self) -> None:
  893. """Play a 'bell' sound (if supported by the terminal)."""
  894. self.control(Control.bell())
  895. def capture(self) -> Capture:
  896. """A context manager to *capture* the result of print() or log() in a string,
  897. rather than writing it to the console.
  898. Example:
  899. >>> from rich.console import Console
  900. >>> console = Console()
  901. >>> with console.capture() as capture:
  902. ... console.print("[bold magenta]Hello World[/]")
  903. >>> print(capture.get())
  904. Returns:
  905. Capture: Context manager with disables writing to the terminal.
  906. """
  907. capture = Capture(self)
  908. return capture
  909. def pager(
  910. self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False
  911. ) -> PagerContext:
  912. """A context manager to display anything printed within a "pager". The pager application
  913. is defined by the system and will typically support at least pressing a key to scroll.
  914. Args:
  915. pager (Pager, optional): A pager object, or None to use :class:`~rich.pager.SystemPager`. Defaults to None.
  916. styles (bool, optional): Show styles in pager. Defaults to False.
  917. links (bool, optional): Show links in pager. Defaults to False.
  918. Example:
  919. >>> from rich.console import Console
  920. >>> from rich.__main__ import make_test_card
  921. >>> console = Console()
  922. >>> with console.pager():
  923. console.print(make_test_card())
  924. Returns:
  925. PagerContext: A context manager.
  926. """
  927. return PagerContext(self, pager=pager, styles=styles, links=links)
  928. def line(self, count: int = 1) -> None:
  929. """Write new line(s).
  930. Args:
  931. count (int, optional): Number of new lines. Defaults to 1.
  932. """
  933. assert count >= 0, "count must be >= 0"
  934. self.print(NewLine(count))
  935. def clear(self, home: bool = True) -> None:
  936. """Clear the screen.
  937. Args:
  938. home (bool, optional): Also move the cursor to 'home' position. Defaults to True.
  939. """
  940. if home:
  941. self.control(Control.clear(), Control.home())
  942. else:
  943. self.control(Control.clear())
  944. def status(
  945. self,
  946. status: RenderableType,
  947. *,
  948. spinner: str = "dots",
  949. spinner_style: StyleType = "status.spinner",
  950. speed: float = 1.0,
  951. refresh_per_second: float = 12.5,
  952. ) -> "Status":
  953. """Display a status and spinner.
  954. Args:
  955. status (RenderableType): A status renderable (str or Text typically).
  956. spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots".
  957. spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner".
  958. speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.
  959. refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.
  960. Returns:
  961. Status: A Status object that may be used as a context manager.
  962. """
  963. from .status import Status
  964. status_renderable = Status(
  965. status,
  966. console=self,
  967. spinner=spinner,
  968. spinner_style=spinner_style,
  969. speed=speed,
  970. refresh_per_second=refresh_per_second,
  971. )
  972. return status_renderable
  973. def show_cursor(self, show: bool = True) -> bool:
  974. """Show or hide the cursor.
  975. Args:
  976. show (bool, optional): Set visibility of the cursor.
  977. """
  978. if self.is_terminal:
  979. self.control(Control.show_cursor(show))
  980. return True
  981. return False
  982. def set_alt_screen(self, enable: bool = True) -> bool:
  983. """Enables alternative screen mode.
  984. Note, if you enable this mode, you should ensure that is disabled before
  985. the application exits. See :meth:`~rich.Console.screen` for a context manager
  986. that handles this for you.
  987. Args:
  988. enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True.
  989. Returns:
  990. bool: True if the control codes were written.
  991. """
  992. changed = False
  993. if self.is_terminal and not self.legacy_windows:
  994. self.control(Control.alt_screen(enable))
  995. changed = True
  996. self._is_alt_screen = enable
  997. return changed
  998. @property
  999. def is_alt_screen(self) -> bool:
  1000. """Check if the alt screen was enabled.
  1001. Returns:
  1002. bool: True if the alt screen was enabled, otherwise False.
  1003. """
  1004. return self._is_alt_screen
  1005. def set_window_title(self, title: str) -> bool:
  1006. """Set the title of the console terminal window.
  1007. Warning: There is no means within Rich of "resetting" the window title to its
  1008. previous value, meaning the title you set will persist even after your application
  1009. exits.
  1010. ``fish`` shell resets the window title before and after each command by default,
  1011. negating this issue. Windows Terminal and command prompt will also reset the title for you.
  1012. Most other shells and terminals, however, do not do this.
  1013. Some terminals may require configuration changes before you can set the title.
  1014. Some terminals may not support setting the title at all.
  1015. Other software (including the terminal itself, the shell, custom prompts, plugins, etc.)
  1016. may also set the terminal window title. This could result in whatever value you write
  1017. using this method being overwritten.
  1018. Args:
  1019. title (str): The new title of the terminal window.
  1020. Returns:
  1021. bool: True if the control code to change the terminal title was
  1022. written, otherwise False. Note that a return value of True
  1023. does not guarantee that the window title has actually changed,
  1024. since the feature may be unsupported/disabled in some terminals.
  1025. """
  1026. if self.is_terminal:
  1027. self.control(Control.title(title))
  1028. return True
  1029. return False
  1030. def screen(
  1031. self, hide_cursor: bool = True, style: Optional[StyleType] = None
  1032. ) -> "ScreenContext":
  1033. """Context manager to enable and disable 'alternative screen' mode.
  1034. Args:
  1035. hide_cursor (bool, optional): Also hide the cursor. Defaults to False.
  1036. style (Style, optional): Optional style for screen. Defaults to None.
  1037. Returns:
  1038. ~ScreenContext: Context which enables alternate screen on enter, and disables it on exit.
  1039. """
  1040. return ScreenContext(self, hide_cursor=hide_cursor, style=style or "")
  1041. def measure(
  1042. self, renderable: RenderableType, *, options: Optional[ConsoleOptions] = None
  1043. ) -> Measurement:
  1044. """Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains
  1045. information regarding the number of characters required to print the renderable.
  1046. Args:
  1047. renderable (RenderableType): Any renderable or string.
  1048. options (Optional[ConsoleOptions], optional): Options to use when measuring, or None
  1049. to use default options. Defaults to None.
  1050. Returns:
  1051. Measurement: A measurement of the renderable.
  1052. """
  1053. measurement = Measurement.get(self, options or self.options, renderable)
  1054. return measurement
  1055. def render(
  1056. self, renderable: RenderableType, options: Optional[ConsoleOptions] = None
  1057. ) -> Iterable[Segment]:
  1058. """Render an object in to an iterable of `Segment` instances.
  1059. This method contains the logic for rendering objects with the console protocol.
  1060. You are unlikely to need to use it directly, unless you are extending the library.
  1061. Args:
  1062. renderable (RenderableType): An object supporting the console protocol, or
  1063. an object that may be converted to a string.
  1064. options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None.
  1065. Returns:
  1066. Iterable[Segment]: An iterable of segments that may be rendered.
  1067. """
  1068. _options = options or self.options
  1069. if _options.max_width < 1:
  1070. # No space to render anything. This prevents potential recursion errors.
  1071. return
  1072. render_iterable: RenderResult
  1073. renderable = rich_cast(renderable)
  1074. if hasattr(renderable, "__rich_console__") and not isclass(renderable):
  1075. render_iterable = renderable.__rich_console__(self, _options) # type: ignore[union-attr]
  1076. elif isinstance(renderable, str):
  1077. text_renderable = self.render_str(
  1078. renderable, highlight=_options.highlight, markup=_options.markup
  1079. )
  1080. render_iterable = text_renderable.__rich_console__(self, _options)
  1081. else:
  1082. raise errors.NotRenderableError(
  1083. f"Unable to render {renderable!r}; "
  1084. "A str, Segment or object with __rich_console__ method is required"
  1085. )
  1086. try:
  1087. iter_render = iter(render_iterable)
  1088. except TypeError:
  1089. raise errors.NotRenderableError(
  1090. f"object {render_iterable!r} is not renderable"
  1091. )
  1092. _Segment = Segment
  1093. _options = _options.reset_height()
  1094. for render_output in iter_render:
  1095. if isinstance(render_output, _Segment):
  1096. yield render_output
  1097. else:
  1098. yield from self.render(render_output, _options)
  1099. def render_lines(
  1100. self,
  1101. renderable: RenderableType,
  1102. options: Optional[ConsoleOptions] = None,
  1103. *,
  1104. style: Optional[Style] = None,
  1105. pad: bool = True,
  1106. new_lines: bool = False,
  1107. ) -> List[List[Segment]]:
  1108. """Render objects in to a list of lines.
  1109. The output of render_lines is useful when further formatting of rendered console text
  1110. is required, such as the Panel class which draws a border around any renderable object.
  1111. Args:
  1112. renderable (RenderableType): Any object renderable in the console.
  1113. options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``.
  1114. style (Style, optional): Optional style to apply to renderables. Defaults to ``None``.
  1115. pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``.
  1116. new_lines (bool, optional): Include "\n" characters at end of lines.
  1117. Returns:
  1118. List[List[Segment]]: A list of lines, where a line is a list of Segment objects.
  1119. """
  1120. with self._lock:
  1121. render_options = options or self.options
  1122. _rendered = self.render(renderable, render_options)
  1123. if style:
  1124. _rendered = Segment.apply_style(_rendered, style)
  1125. render_height = render_options.height
  1126. if render_height is not None:
  1127. render_height = max(0, render_height)
  1128. lines = list(
  1129. islice(
  1130. Segment.split_and_crop_lines(
  1131. _rendered,
  1132. render_options.max_width,
  1133. include_new_lines=new_lines,
  1134. pad=pad,
  1135. style=style,
  1136. ),
  1137. None,
  1138. render_height,
  1139. )
  1140. )
  1141. if render_options.height is not None:
  1142. extra_lines = render_options.height - len(lines)
  1143. if extra_lines > 0:
  1144. pad_line = [
  1145. [Segment(" " * render_options.max_width, style), Segment("\n")]
  1146. if new_lines
  1147. else [Segment(" " * render_options.max_width, style)]
  1148. ]
  1149. lines.extend(pad_line * extra_lines)
  1150. return lines
  1151. def render_str(
  1152. self,
  1153. text: str,
  1154. *,
  1155. style: Union[str, Style] = "",
  1156. justify: Optional[JustifyMethod] = None,
  1157. overflow: Optional[OverflowMethod] = None,
  1158. emoji: Optional[bool] = None,
  1159. markup: Optional[bool] = None,
  1160. highlight: Optional[bool] = None,
  1161. highlighter: Optional[HighlighterType] = None,
  1162. ) -> "Text":
  1163. """Convert a string to a Text instance. This is called automatically if
  1164. you print or log a string.
  1165. Args:
  1166. text (str): Text to render.
  1167. style (Union[str, Style], optional): Style to apply to rendered text.
  1168. justify (str, optional): Justify method: "default", "left", "center", "full", or "right". Defaults to ``None``.
  1169. overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to ``None``.
  1170. emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default.
  1171. markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default.
  1172. highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default.
  1173. highlighter (HighlighterType, optional): Optional highlighter to apply.
  1174. Returns:
  1175. ConsoleRenderable: Renderable object.
  1176. """
  1177. emoji_enabled = emoji or (emoji is None and self._emoji)
  1178. markup_enabled = markup or (markup is None and self._markup)
  1179. highlight_enabled = highlight or (highlight is None and self._highlight)
  1180. if markup_enabled:
  1181. rich_text = render_markup(
  1182. text,
  1183. style=style,
  1184. emoji=emoji_enabled,
  1185. emoji_variant=self._emoji_variant,
  1186. )
  1187. rich_text.justify = justify
  1188. rich_text.overflow = overflow
  1189. else:
  1190. rich_text = Text(
  1191. _emoji_replace(text, default_variant=self._emoji_variant)
  1192. if emoji_enabled
  1193. else text,
  1194. justify=justify,
  1195. overflow=overflow,
  1196. style=style,
  1197. )
  1198. _highlighter = (highlighter or self.highlighter) if highlight_enabled else None
  1199. if _highlighter is not None:
  1200. highlight_text = _highlighter(str(rich_text))
  1201. highlight_text.copy_styles(rich_text)
  1202. return highlight_text
  1203. return rich_text
  1204. def get_style(
  1205. self, name: Union[str, Style], *, default: Optional[Union[Style, str]] = None
  1206. ) -> Style:
  1207. """Get a Style instance by its theme name or parse a definition.
  1208. Args:
  1209. name (str): The name of a style or a style definition.
  1210. Returns:
  1211. Style: A Style object.
  1212. Raises:
  1213. MissingStyle: If no style could be parsed from name.
  1214. """
  1215. if isinstance(name, Style):
  1216. return name
  1217. try:
  1218. style = self._theme_stack.get(name)
  1219. if style is None:
  1220. style = Style.parse(name)
  1221. return style.copy() if style.link else style
  1222. except errors.StyleSyntaxError as error:
  1223. if default is not None:
  1224. return self.get_style(default)
  1225. raise errors.MissingStyle(
  1226. f"Failed to get style {name!r}; {error}"
  1227. ) from None
  1228. def _collect_renderables(
  1229. self,
  1230. objects: Iterable[Any],
  1231. sep: str,
  1232. end: str,
  1233. *,
  1234. justify: Optional[JustifyMethod] = None,
  1235. emoji: Optional[bool] = None,
  1236. markup: Optional[bool] = None,
  1237. highlight: Optional[bool] = None,
  1238. ) -> List[ConsoleRenderable]:
  1239. """Combine a number of renderables and text into one renderable.
  1240. Args:
  1241. objects (Iterable[Any]): Anything that Rich can render.
  1242. sep (str): String to write between print data.
  1243. end (str): String to write at end of print data.
  1244. justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
  1245. emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default.
  1246. markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.
  1247. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.
  1248. Returns:
  1249. List[ConsoleRenderable]: A list of things to render.
  1250. """
  1251. renderables: List[ConsoleRenderable] = []
  1252. _append = renderables.append
  1253. text: List[Text] = []
  1254. append_text = text.append
  1255. append = _append
  1256. if justify in ("left", "center", "right"):
  1257. def align_append(renderable: RenderableType) -> None:
  1258. _append(Align(renderable, cast(AlignMethod, justify)))
  1259. append = align_append
  1260. _highlighter: HighlighterType = _null_highlighter
  1261. if highlight or (highlight is None and self._highlight):
  1262. _highlighter = self.highlighter
  1263. def check_text() -> None:
  1264. if text:
  1265. sep_text = Text(sep, justify=justify, end=end)
  1266. append(sep_text.join(text))
  1267. text.clear()
  1268. for renderable in objects:
  1269. renderable = rich_cast(renderable)
  1270. if isinstance(renderable, str):
  1271. append_text(
  1272. self.render_str(
  1273. renderable, emoji=emoji, markup=markup, highlighter=_highlighter
  1274. )
  1275. )
  1276. elif isinstance(renderable, Text):
  1277. append_text(renderable)
  1278. elif isinstance(renderable, ConsoleRenderable):
  1279. check_text()
  1280. append(renderable)
  1281. elif is_expandable(renderable):
  1282. check_text()
  1283. append(Pretty(renderable, highlighter=_highlighter))
  1284. else:
  1285. append_text(_highlighter(str(renderable)))
  1286. check_text()
  1287. if self.style is not None:
  1288. style = self.get_style(self.style)
  1289. renderables = [Styled(renderable, style) for renderable in renderables]
  1290. return renderables
  1291. def rule(
  1292. self,
  1293. title: TextType = "",
  1294. *,
  1295. characters: str = "─",
  1296. style: Union[str, Style] = "rule.line",
  1297. align: AlignMethod = "center",
  1298. ) -> None:
  1299. """Draw a line with optional centered title.
  1300. Args:
  1301. title (str, optional): Text to render over the rule. Defaults to "".
  1302. characters (str, optional): Character(s) to form the line. Defaults to "─".
  1303. style (str, optional): Style of line. Defaults to "rule.line".
  1304. align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center".
  1305. """
  1306. from .rule import Rule
  1307. rule = Rule(title=title, characters=characters, style=style, align=align)
  1308. self.print(rule)
  1309. def control(self, *control: Control) -> None:
  1310. """Insert non-printing control codes.
  1311. Args:
  1312. control_codes (str): Control codes, such as those that may move the cursor.
  1313. """
  1314. if not self.is_dumb_terminal:
  1315. with self:
  1316. self._buffer.extend(_control.segment for _control in control)
  1317. def out(
  1318. self,
  1319. *objects: Any,
  1320. sep: str = " ",
  1321. end: str = "\n",
  1322. style: Optional[Union[str, Style]] = None,
  1323. highlight: Optional[bool] = None,
  1324. ) -> None:
  1325. """Output to the terminal. This is a low-level way of writing to the terminal which unlike
  1326. :meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will
  1327. optionally apply highlighting and a basic style.
  1328. Args:
  1329. sep (str, optional): String to write between print data. Defaults to " ".
  1330. end (str, optional): String to write at end of print data. Defaults to "\\\\n".
  1331. style (Union[str, Style], optional): A style to apply to output. Defaults to None.
  1332. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use
  1333. console default. Defaults to ``None``.
  1334. """
  1335. raw_output: str = sep.join(str(_object) for _object in objects)
  1336. self.print(
  1337. raw_output,
  1338. style=style,
  1339. highlight=highlight,
  1340. emoji=False,
  1341. markup=False,
  1342. no_wrap=True,
  1343. overflow="ignore",
  1344. crop=False,
  1345. end=end,
  1346. )
  1347. def print(
  1348. self,
  1349. *objects: Any,
  1350. sep: str = " ",
  1351. end: str = "\n",
  1352. style: Optional[Union[str, Style]] = None,
  1353. justify: Optional[JustifyMethod] = None,
  1354. overflow: Optional[OverflowMethod] = None,
  1355. no_wrap: Optional[bool] = None,
  1356. emoji: Optional[bool] = None,
  1357. markup: Optional[bool] = None,
  1358. highlight: Optional[bool] = None,
  1359. width: Optional[int] = None,
  1360. height: Optional[int] = None,
  1361. crop: bool = True,
  1362. soft_wrap: Optional[bool] = None,
  1363. new_line_start: bool = False,
  1364. ) -> None:
  1365. """Print to the console.
  1366. Args:
  1367. objects (positional args): Objects to log to the terminal.
  1368. sep (str, optional): String to write between print data. Defaults to " ".
  1369. end (str, optional): String to write at end of print data. Defaults to "\\\\n".
  1370. style (Union[str, Style], optional): A style to apply to output. Defaults to None.
  1371. justify (str, optional): Justify method: "default", "left", "right", "center", or "full". Defaults to ``None``.
  1372. overflow (str, optional): Overflow method: "ignore", "crop", "fold", or "ellipsis". Defaults to None.
  1373. no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.
  1374. emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.
  1375. markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.
  1376. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.
  1377. width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.
  1378. crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.
  1379. soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for
  1380. Console default. Defaults to ``None``.
  1381. new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``.
  1382. """
  1383. if not objects:
  1384. objects = (NewLine(),)
  1385. if soft_wrap is None:
  1386. soft_wrap = self.soft_wrap
  1387. if soft_wrap:
  1388. if no_wrap is None:
  1389. no_wrap = True
  1390. if overflow is None:
  1391. overflow = "ignore"
  1392. crop = False
  1393. render_hooks = self._render_hooks[:]
  1394. with self:
  1395. renderables = self._collect_renderables(
  1396. objects,
  1397. sep,
  1398. end,
  1399. justify=justify,
  1400. emoji=emoji,
  1401. markup=markup,
  1402. highlight=highlight,
  1403. )
  1404. for hook in render_hooks:
  1405. renderables = hook.process_renderables(renderables)
  1406. render_options = self.options.update(
  1407. justify=justify,
  1408. overflow=overflow,
  1409. width=min(width, self.width) if width is not None else NO_CHANGE,
  1410. height=height,
  1411. no_wrap=no_wrap,
  1412. markup=markup,
  1413. highlight=highlight,
  1414. )
  1415. new_segments: List[Segment] = []
  1416. extend = new_segments.extend
  1417. render = self.render
  1418. if style is None:
  1419. for renderable in renderables:
  1420. extend(render(renderable, render_options))
  1421. else:
  1422. for renderable in renderables:
  1423. extend(
  1424. Segment.apply_style(
  1425. render(renderable, render_options), self.get_style(style)
  1426. )
  1427. )
  1428. if new_line_start:
  1429. if (
  1430. len("".join(segment.text for segment in new_segments).splitlines())
  1431. > 1
  1432. ):
  1433. new_segments.insert(0, Segment.line())
  1434. if crop:
  1435. buffer_extend = self._buffer.extend
  1436. for line in Segment.split_and_crop_lines(
  1437. new_segments, self.width, pad=False
  1438. ):
  1439. buffer_extend(line)
  1440. else:
  1441. self._buffer.extend(new_segments)
  1442. def print_json(
  1443. self,
  1444. json: Optional[str] = None,
  1445. *,
  1446. data: Any = None,
  1447. indent: Union[None, int, str] = 2,
  1448. highlight: bool = True,
  1449. skip_keys: bool = False,
  1450. ensure_ascii: bool = False,
  1451. check_circular: bool = True,
  1452. allow_nan: bool = True,
  1453. default: Optional[Callable[[Any], Any]] = None,
  1454. sort_keys: bool = False,
  1455. ) -> None:
  1456. """Pretty prints JSON. Output will be valid JSON.
  1457. Args:
  1458. json (Optional[str]): A string containing JSON.
  1459. data (Any): If json is not supplied, then encode this data.
  1460. indent (Union[None, int, str], optional): Number of spaces to indent. Defaults to 2.
  1461. highlight (bool, optional): Enable highlighting of output: Defaults to True.
  1462. skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
  1463. ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
  1464. check_circular (bool, optional): Check for circular references. Defaults to True.
  1465. allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
  1466. default (Callable, optional): A callable that converts values that can not be encoded
  1467. in to something that can be JSON encoded. Defaults to None.
  1468. sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
  1469. """
  1470. from pip._vendor.rich.json import JSON
  1471. if json is None:
  1472. json_renderable = JSON.from_data(
  1473. data,
  1474. indent=indent,
  1475. highlight=highlight,
  1476. skip_keys=skip_keys,
  1477. ensure_ascii=ensure_ascii,
  1478. check_circular=check_circular,
  1479. allow_nan=allow_nan,
  1480. default=default,
  1481. sort_keys=sort_keys,
  1482. )
  1483. else:
  1484. if not isinstance(json, str):
  1485. raise TypeError(
  1486. f"json must be str. Did you mean print_json(data={json!r}) ?"
  1487. )
  1488. json_renderable = JSON(
  1489. json,
  1490. indent=indent,
  1491. highlight=highlight,
  1492. skip_keys=skip_keys,
  1493. ensure_ascii=ensure_ascii,
  1494. check_circular=check_circular,
  1495. allow_nan=allow_nan,
  1496. default=default,
  1497. sort_keys=sort_keys,
  1498. )
  1499. self.print(json_renderable, soft_wrap=True)
  1500. def update_screen(
  1501. self,
  1502. renderable: RenderableType,
  1503. *,
  1504. region: Optional[Region] = None,
  1505. options: Optional[ConsoleOptions] = None,
  1506. ) -> None:
  1507. """Update the screen at a given offset.
  1508. Args:
  1509. renderable (RenderableType): A Rich renderable.
  1510. region (Region, optional): Region of screen to update, or None for entire screen. Defaults to None.
  1511. x (int, optional): x offset. Defaults to 0.
  1512. y (int, optional): y offset. Defaults to 0.
  1513. Raises:
  1514. errors.NoAltScreen: If the Console isn't in alt screen mode.
  1515. """
  1516. if not self.is_alt_screen:
  1517. raise errors.NoAltScreen("Alt screen must be enabled to call update_screen")
  1518. render_options = options or self.options
  1519. if region is None:
  1520. x = y = 0
  1521. render_options = render_options.update_dimensions(
  1522. render_options.max_width, render_options.height or self.height
  1523. )
  1524. else:
  1525. x, y, width, height = region
  1526. render_options = render_options.update_dimensions(width, height)
  1527. lines = self.render_lines(renderable, options=render_options)
  1528. self.update_screen_lines(lines, x, y)
  1529. def update_screen_lines(
  1530. self, lines: List[List[Segment]], x: int = 0, y: int = 0
  1531. ) -> None:
  1532. """Update lines of the screen at a given offset.
  1533. Args:
  1534. lines (List[List[Segment]]): Rendered lines (as produced by :meth:`~rich.Console.render_lines`).
  1535. x (int, optional): x offset (column no). Defaults to 0.
  1536. y (int, optional): y offset (column no). Defaults to 0.
  1537. Raises:
  1538. errors.NoAltScreen: If the Console isn't in alt screen mode.
  1539. """
  1540. if not self.is_alt_screen:
  1541. raise errors.NoAltScreen("Alt screen must be enabled to call update_screen")
  1542. screen_update = ScreenUpdate(lines, x, y)
  1543. segments = self.render(screen_update)
  1544. self._buffer.extend(segments)
  1545. self._check_buffer()
  1546. def print_exception(
  1547. self,
  1548. *,
  1549. width: Optional[int] = 100,
  1550. extra_lines: int = 3,
  1551. theme: Optional[str] = None,
  1552. word_wrap: bool = False,
  1553. show_locals: bool = False,
  1554. suppress: Iterable[Union[str, ModuleType]] = (),
  1555. max_frames: int = 100,
  1556. ) -> None:
  1557. """Prints a rich render of the last exception and traceback.
  1558. Args:
  1559. width (Optional[int], optional): Number of characters used to render code. Defaults to 100.
  1560. extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
  1561. theme (str, optional): Override pygments theme used in traceback
  1562. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
  1563. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  1564. suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
  1565. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
  1566. """
  1567. from .traceback import Traceback
  1568. traceback = Traceback(
  1569. width=width,
  1570. extra_lines=extra_lines,
  1571. theme=theme,
  1572. word_wrap=word_wrap,
  1573. show_locals=show_locals,
  1574. suppress=suppress,
  1575. max_frames=max_frames,
  1576. )
  1577. self.print(traceback)
  1578. @staticmethod
  1579. def _caller_frame_info(
  1580. offset: int,
  1581. currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe,
  1582. ) -> Tuple[str, int, Dict[str, Any]]:
  1583. """Get caller frame information.
  1584. Args:
  1585. offset (int): the caller offset within the current frame stack.
  1586. currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to
  1587. retrieve the current frame. Defaults to ``inspect.currentframe``.
  1588. Returns:
  1589. Tuple[str, int, Dict[str, Any]]: A tuple containing the filename, the line number and
  1590. the dictionary of local variables associated with the caller frame.
  1591. Raises:
  1592. RuntimeError: If the stack offset is invalid.
  1593. """
  1594. # Ignore the frame of this local helper
  1595. offset += 1
  1596. frame = currentframe()
  1597. if frame is not None:
  1598. # Use the faster currentframe where implemented
  1599. while offset and frame is not None:
  1600. frame = frame.f_back
  1601. offset -= 1
  1602. assert frame is not None
  1603. return frame.f_code.co_filename, frame.f_lineno, frame.f_locals
  1604. else:
  1605. # Fallback to the slower stack
  1606. frame_info = inspect.stack()[offset]
  1607. return frame_info.filename, frame_info.lineno, frame_info.frame.f_locals
  1608. def log(
  1609. self,
  1610. *objects: Any,
  1611. sep: str = " ",
  1612. end: str = "\n",
  1613. style: Optional[Union[str, Style]] = None,
  1614. justify: Optional[JustifyMethod] = None,
  1615. emoji: Optional[bool] = None,
  1616. markup: Optional[bool] = None,
  1617. highlight: Optional[bool] = None,
  1618. log_locals: bool = False,
  1619. _stack_offset: int = 1,
  1620. ) -> None:
  1621. """Log rich content to the terminal.
  1622. Args:
  1623. objects (positional args): Objects to log to the terminal.
  1624. sep (str, optional): String to write between print data. Defaults to " ".
  1625. end (str, optional): String to write at end of print data. Defaults to "\\\\n".
  1626. style (Union[str, Style], optional): A style to apply to output. Defaults to None.
  1627. justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
  1628. overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None.
  1629. emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None.
  1630. markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None.
  1631. highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None.
  1632. log_locals (bool, optional): Boolean to enable logging of locals where ``log()``
  1633. was called. Defaults to False.
  1634. _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.
  1635. """
  1636. if not objects:
  1637. objects = (NewLine(),)
  1638. render_hooks = self._render_hooks[:]
  1639. with self:
  1640. renderables = self._collect_renderables(
  1641. objects,
  1642. sep,
  1643. end,
  1644. justify=justify,
  1645. emoji=emoji,
  1646. markup=markup,
  1647. highlight=highlight,
  1648. )
  1649. if style is not None:
  1650. renderables = [Styled(renderable, style) for renderable in renderables]
  1651. filename, line_no, locals = self._caller_frame_info(_stack_offset)
  1652. link_path = None if filename.startswith("<") else os.path.abspath(filename)
  1653. path = filename.rpartition(os.sep)[-1]
  1654. if log_locals:
  1655. locals_map = {
  1656. key: value
  1657. for key, value in locals.items()
  1658. if not key.startswith("__")
  1659. }
  1660. renderables.append(render_scope(locals_map, title="[i]locals"))
  1661. renderables = [
  1662. self._log_render(
  1663. self,
  1664. renderables,
  1665. log_time=self.get_datetime(),
  1666. path=path,
  1667. line_no=line_no,
  1668. link_path=link_path,
  1669. )
  1670. ]
  1671. for hook in render_hooks:
  1672. renderables = hook.process_renderables(renderables)
  1673. new_segments: List[Segment] = []
  1674. extend = new_segments.extend
  1675. render = self.render
  1676. render_options = self.options
  1677. for renderable in renderables:
  1678. extend(render(renderable, render_options))
  1679. buffer_extend = self._buffer.extend
  1680. for line in Segment.split_and_crop_lines(
  1681. new_segments, self.width, pad=False
  1682. ):
  1683. buffer_extend(line)
  1684. def _check_buffer(self) -> None:
  1685. """Check if the buffer may be rendered. Render it if it can (e.g. Console.quiet is False)
  1686. Rendering is supported on Windows, Unix and Jupyter environments. For
  1687. legacy Windows consoles, the win32 API is called directly.
  1688. This method will also record what it renders if recording is enabled via Console.record.
  1689. """
  1690. if self.quiet:
  1691. del self._buffer[:]
  1692. return
  1693. with self._lock:
  1694. if self.record:
  1695. with self._record_buffer_lock:
  1696. self._record_buffer.extend(self._buffer[:])
  1697. if self._buffer_index == 0:
  1698. if self.is_jupyter: # pragma: no cover
  1699. from .jupyter import display
  1700. display(self._buffer, self._render_buffer(self._buffer[:]))
  1701. del self._buffer[:]
  1702. else:
  1703. if WINDOWS:
  1704. use_legacy_windows_render = False
  1705. if self.legacy_windows:
  1706. fileno = get_fileno(self.file)
  1707. if fileno is not None:
  1708. use_legacy_windows_render = (
  1709. fileno in _STD_STREAMS_OUTPUT
  1710. )
  1711. if use_legacy_windows_render:
  1712. from pip._vendor.rich._win32_console import LegacyWindowsTerm
  1713. from pip._vendor.rich._windows_renderer import legacy_windows_render
  1714. buffer = self._buffer[:]
  1715. if self.no_color and self._color_system:
  1716. buffer = list(Segment.remove_color(buffer))
  1717. legacy_windows_render(buffer, LegacyWindowsTerm(self.file))
  1718. else:
  1719. # Either a non-std stream on legacy Windows, or modern Windows.
  1720. text = self._render_buffer(self._buffer[:])
  1721. # https://bugs.python.org/issue37871
  1722. # https://github.com/python/cpython/issues/82052
  1723. # We need to avoid writing more than 32Kb in a single write, due to the above bug
  1724. write = self.file.write
  1725. # Worse case scenario, every character is 4 bytes of utf-8
  1726. MAX_WRITE = 32 * 1024 // 4
  1727. try:
  1728. if len(text) <= MAX_WRITE:
  1729. write(text)
  1730. else:
  1731. batch: List[str] = []
  1732. batch_append = batch.append
  1733. size = 0
  1734. for line in text.splitlines(True):
  1735. if size + len(line) > MAX_WRITE and batch:
  1736. write("".join(batch))
  1737. batch.clear()
  1738. size = 0
  1739. batch_append(line)
  1740. size += len(line)
  1741. if batch:
  1742. write("".join(batch))
  1743. batch.clear()
  1744. except UnicodeEncodeError as error:
  1745. error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***"
  1746. raise
  1747. else:
  1748. text = self._render_buffer(self._buffer[:])
  1749. try:
  1750. self.file.write(text)
  1751. except UnicodeEncodeError as error:
  1752. error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***"
  1753. raise
  1754. self.file.flush()
  1755. del self._buffer[:]
  1756. def _render_buffer(self, buffer: Iterable[Segment]) -> str:
  1757. """Render buffered output, and clear buffer."""
  1758. output: List[str] = []
  1759. append = output.append
  1760. color_system = self._color_system
  1761. legacy_windows = self.legacy_windows
  1762. not_terminal = not self.is_terminal
  1763. if self.no_color and color_system:
  1764. buffer = Segment.remove_color(buffer)
  1765. for text, style, control in buffer:
  1766. if style:
  1767. append(
  1768. style.render(
  1769. text,
  1770. color_system=color_system,
  1771. legacy_windows=legacy_windows,
  1772. )
  1773. )
  1774. elif not (not_terminal and control):
  1775. append(text)
  1776. rendered = "".join(output)
  1777. return rendered
  1778. def input(
  1779. self,
  1780. prompt: TextType = "",
  1781. *,
  1782. markup: bool = True,
  1783. emoji: bool = True,
  1784. password: bool = False,
  1785. stream: Optional[TextIO] = None,
  1786. ) -> str:
  1787. """Displays a prompt and waits for input from the user. The prompt may contain color / style.
  1788. 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.
  1789. Args:
  1790. prompt (Union[str, Text]): Text to render in the prompt.
  1791. markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.
  1792. emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.
  1793. password: (bool, optional): Hide typed text. Defaults to False.
  1794. stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.
  1795. Returns:
  1796. str: Text read from stdin.
  1797. """
  1798. if prompt:
  1799. self.print(prompt, markup=markup, emoji=emoji, end="")
  1800. if password:
  1801. result = getpass("", stream=stream)
  1802. else:
  1803. if stream:
  1804. result = stream.readline()
  1805. else:
  1806. result = input()
  1807. return result
  1808. def export_text(self, *, clear: bool = True, styles: bool = False) -> str:
  1809. """Generate text from console contents (requires record=True argument in constructor).
  1810. Args:
  1811. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1812. styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.
  1813. Defaults to ``False``.
  1814. Returns:
  1815. str: String containing console contents.
  1816. """
  1817. assert (
  1818. self.record
  1819. ), "To export console contents set record=True in the constructor or instance"
  1820. with self._record_buffer_lock:
  1821. if styles:
  1822. text = "".join(
  1823. (style.render(text) if style else text)
  1824. for text, style, _ in self._record_buffer
  1825. )
  1826. else:
  1827. text = "".join(
  1828. segment.text
  1829. for segment in self._record_buffer
  1830. if not segment.control
  1831. )
  1832. if clear:
  1833. del self._record_buffer[:]
  1834. return text
  1835. def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> None:
  1836. """Generate text from console and save to a given location (requires record=True argument in constructor).
  1837. Args:
  1838. path (str): Path to write text files.
  1839. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1840. styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.
  1841. Defaults to ``False``.
  1842. """
  1843. text = self.export_text(clear=clear, styles=styles)
  1844. with open(path, "wt", encoding="utf-8") as write_file:
  1845. write_file.write(text)
  1846. def export_html(
  1847. self,
  1848. *,
  1849. theme: Optional[TerminalTheme] = None,
  1850. clear: bool = True,
  1851. code_format: Optional[str] = None,
  1852. inline_styles: bool = False,
  1853. ) -> str:
  1854. """Generate HTML from console contents (requires record=True argument in constructor).
  1855. Args:
  1856. theme (TerminalTheme, optional): TerminalTheme object containing console colors.
  1857. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1858. code_format (str, optional): Format string to render HTML. In addition to '{foreground}',
  1859. '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``.
  1860. inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
  1861. larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
  1862. Defaults to False.
  1863. Returns:
  1864. str: String containing console contents as HTML.
  1865. """
  1866. assert (
  1867. self.record
  1868. ), "To export console contents set record=True in the constructor or instance"
  1869. fragments: List[str] = []
  1870. append = fragments.append
  1871. _theme = theme or DEFAULT_TERMINAL_THEME
  1872. stylesheet = ""
  1873. render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format
  1874. with self._record_buffer_lock:
  1875. if inline_styles:
  1876. for text, style, _ in Segment.filter_control(
  1877. Segment.simplify(self._record_buffer)
  1878. ):
  1879. text = escape(text)
  1880. if style:
  1881. rule = style.get_html_style(_theme)
  1882. if style.link:
  1883. text = f'<a href="{style.link}">{text}</a>'
  1884. text = f'<span style="{rule}">{text}</span>' if rule else text
  1885. append(text)
  1886. else:
  1887. styles: Dict[str, int] = {}
  1888. for text, style, _ in Segment.filter_control(
  1889. Segment.simplify(self._record_buffer)
  1890. ):
  1891. text = escape(text)
  1892. if style:
  1893. rule = style.get_html_style(_theme)
  1894. style_number = styles.setdefault(rule, len(styles) + 1)
  1895. if style.link:
  1896. text = f'<a class="r{style_number}" href="{style.link}">{text}</a>'
  1897. else:
  1898. text = f'<span class="r{style_number}">{text}</span>'
  1899. append(text)
  1900. stylesheet_rules: List[str] = []
  1901. stylesheet_append = stylesheet_rules.append
  1902. for style_rule, style_number in styles.items():
  1903. if style_rule:
  1904. stylesheet_append(f".r{style_number} {{{style_rule}}}")
  1905. stylesheet = "\n".join(stylesheet_rules)
  1906. rendered_code = render_code_format.format(
  1907. code="".join(fragments),
  1908. stylesheet=stylesheet,
  1909. foreground=_theme.foreground_color.hex,
  1910. background=_theme.background_color.hex,
  1911. )
  1912. if clear:
  1913. del self._record_buffer[:]
  1914. return rendered_code
  1915. def save_html(
  1916. self,
  1917. path: str,
  1918. *,
  1919. theme: Optional[TerminalTheme] = None,
  1920. clear: bool = True,
  1921. code_format: str = CONSOLE_HTML_FORMAT,
  1922. inline_styles: bool = False,
  1923. ) -> None:
  1924. """Generate HTML from console contents and write to a file (requires record=True argument in constructor).
  1925. Args:
  1926. path (str): Path to write html file.
  1927. theme (TerminalTheme, optional): TerminalTheme object containing console colors.
  1928. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
  1929. code_format (str, optional): Format string to render HTML. In addition to '{foreground}',
  1930. '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``.
  1931. inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
  1932. larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
  1933. Defaults to False.
  1934. """
  1935. html = self.export_html(
  1936. theme=theme,
  1937. clear=clear,
  1938. code_format=code_format,
  1939. inline_styles=inline_styles,
  1940. )
  1941. with open(path, "wt", encoding="utf-8") as write_file:
  1942. write_file.write(html)
  1943. def export_svg(
  1944. self,
  1945. *,
  1946. title: str = "Rich",
  1947. theme: Optional[TerminalTheme] = None,
  1948. clear: bool = True,
  1949. code_format: str = CONSOLE_SVG_FORMAT,
  1950. font_aspect_ratio: float = 0.61,
  1951. unique_id: Optional[str] = None,
  1952. ) -> str:
  1953. """
  1954. Generate an SVG from the console contents (requires record=True in Console constructor).
  1955. Args:
  1956. title (str, optional): The title of the tab in the output image
  1957. theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal
  1958. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``
  1959. code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables
  1960. into the string in order to form the final SVG output. The default template used and the variables
  1961. injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.
  1962. font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format``
  1963. string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font).
  1964. If you aren't specifying a different font inside ``code_format``, you probably don't need this.
  1965. unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node
  1966. ids). If not set, this defaults to a computed value based on the recorded content.
  1967. """
  1968. from pip._vendor.rich.cells import cell_len
  1969. style_cache: Dict[Style, str] = {}
  1970. def get_svg_style(style: Style) -> str:
  1971. """Convert a Style to CSS rules for SVG."""
  1972. if style in style_cache:
  1973. return style_cache[style]
  1974. css_rules = []
  1975. color = (
  1976. _theme.foreground_color
  1977. if (style.color is None or style.color.is_default)
  1978. else style.color.get_truecolor(_theme)
  1979. )
  1980. bgcolor = (
  1981. _theme.background_color
  1982. if (style.bgcolor is None or style.bgcolor.is_default)
  1983. else style.bgcolor.get_truecolor(_theme)
  1984. )
  1985. if style.reverse:
  1986. color, bgcolor = bgcolor, color
  1987. if style.dim:
  1988. color = blend_rgb(color, bgcolor, 0.4)
  1989. css_rules.append(f"fill: {color.hex}")
  1990. if style.bold:
  1991. css_rules.append("font-weight: bold")
  1992. if style.italic:
  1993. css_rules.append("font-style: italic;")
  1994. if style.underline:
  1995. css_rules.append("text-decoration: underline;")
  1996. if style.strike:
  1997. css_rules.append("text-decoration: line-through;")
  1998. css = ";".join(css_rules)
  1999. style_cache[style] = css
  2000. return css
  2001. _theme = theme or SVG_EXPORT_THEME
  2002. width = self.width
  2003. char_height = 20
  2004. char_width = char_height * font_aspect_ratio
  2005. line_height = char_height * 1.22
  2006. margin_top = 1
  2007. margin_right = 1
  2008. margin_bottom = 1
  2009. margin_left = 1
  2010. padding_top = 40
  2011. padding_right = 8
  2012. padding_bottom = 8
  2013. padding_left = 8
  2014. padding_width = padding_left + padding_right
  2015. padding_height = padding_top + padding_bottom
  2016. margin_width = margin_left + margin_right
  2017. margin_height = margin_top + margin_bottom
  2018. text_backgrounds: List[str] = []
  2019. text_group: List[str] = []
  2020. classes: Dict[str, int] = {}
  2021. style_no = 1
  2022. def escape_text(text: str) -> str:
  2023. """HTML escape text and replace spaces with nbsp."""
  2024. return escape(text).replace(" ", "&#160;")
  2025. def make_tag(
  2026. name: str, content: Optional[str] = None, **attribs: object
  2027. ) -> str:
  2028. """Make a tag from name, content, and attributes."""
  2029. def stringify(value: object) -> str:
  2030. if isinstance(value, (float)):
  2031. return format(value, "g")
  2032. return str(value)
  2033. tag_attribs = " ".join(
  2034. f'{k.lstrip("_").replace("_", "-")}="{stringify(v)}"'
  2035. for k, v in attribs.items()
  2036. )
  2037. return (
  2038. f"<{name} {tag_attribs}>{content}</{name}>"
  2039. if content
  2040. else f"<{name} {tag_attribs}/>"
  2041. )
  2042. with self._record_buffer_lock:
  2043. segments = list(Segment.filter_control(self._record_buffer))
  2044. if clear:
  2045. self._record_buffer.clear()
  2046. if unique_id is None:
  2047. unique_id = "terminal-" + str(
  2048. zlib.adler32(
  2049. ("".join(repr(segment) for segment in segments)).encode(
  2050. "utf-8",
  2051. "ignore",
  2052. )
  2053. + title.encode("utf-8", "ignore")
  2054. )
  2055. )
  2056. y = 0
  2057. for y, line in enumerate(Segment.split_and_crop_lines(segments, length=width)):
  2058. x = 0
  2059. for text, style, _control in line:
  2060. style = style or Style()
  2061. rules = get_svg_style(style)
  2062. if rules not in classes:
  2063. classes[rules] = style_no
  2064. style_no += 1
  2065. class_name = f"r{classes[rules]}"
  2066. if style.reverse:
  2067. has_background = True
  2068. background = (
  2069. _theme.foreground_color.hex
  2070. if style.color is None
  2071. else style.color.get_truecolor(_theme).hex
  2072. )
  2073. else:
  2074. bgcolor = style.bgcolor
  2075. has_background = bgcolor is not None and not bgcolor.is_default
  2076. background = (
  2077. _theme.background_color.hex
  2078. if style.bgcolor is None
  2079. else style.bgcolor.get_truecolor(_theme).hex
  2080. )
  2081. text_length = cell_len(text)
  2082. if has_background:
  2083. text_backgrounds.append(
  2084. make_tag(
  2085. "rect",
  2086. fill=background,
  2087. x=x * char_width,
  2088. y=y * line_height + 1.5,
  2089. width=char_width * text_length,
  2090. height=line_height + 0.25,
  2091. shape_rendering="crispEdges",
  2092. )
  2093. )
  2094. if text != " " * len(text):
  2095. text_group.append(
  2096. make_tag(
  2097. "text",
  2098. escape_text(text),
  2099. _class=f"{unique_id}-{class_name}",
  2100. x=x * char_width,
  2101. y=y * line_height + char_height,
  2102. textLength=char_width * len(text),
  2103. clip_path=f"url(#{unique_id}-line-{y})",
  2104. )
  2105. )
  2106. x += cell_len(text)
  2107. line_offsets = [line_no * line_height + 1.5 for line_no in range(y)]
  2108. lines = "\n".join(
  2109. f"""<clipPath id="{unique_id}-line-{line_no}">
  2110. {make_tag("rect", x=0, y=offset, width=char_width * width, height=line_height + 0.25)}
  2111. </clipPath>"""
  2112. for line_no, offset in enumerate(line_offsets)
  2113. )
  2114. styles = "\n".join(
  2115. f".{unique_id}-r{rule_no} {{ {css} }}" for css, rule_no in classes.items()
  2116. )
  2117. backgrounds = "".join(text_backgrounds)
  2118. matrix = "".join(text_group)
  2119. terminal_width = ceil(width * char_width + padding_width)
  2120. terminal_height = (y + 1) * line_height + padding_height
  2121. chrome = make_tag(
  2122. "rect",
  2123. fill=_theme.background_color.hex,
  2124. stroke="rgba(255,255,255,0.35)",
  2125. stroke_width="1",
  2126. x=margin_left,
  2127. y=margin_top,
  2128. width=terminal_width,
  2129. height=terminal_height,
  2130. rx=8,
  2131. )
  2132. title_color = _theme.foreground_color.hex
  2133. if title:
  2134. chrome += make_tag(
  2135. "text",
  2136. escape_text(title),
  2137. _class=f"{unique_id}-title",
  2138. fill=title_color,
  2139. text_anchor="middle",
  2140. x=terminal_width // 2,
  2141. y=margin_top + char_height + 6,
  2142. )
  2143. chrome += f"""
  2144. <g transform="translate(26,22)">
  2145. <circle cx="0" cy="0" r="7" fill="#ff5f57"/>
  2146. <circle cx="22" cy="0" r="7" fill="#febc2e"/>
  2147. <circle cx="44" cy="0" r="7" fill="#28c840"/>
  2148. </g>
  2149. """
  2150. svg = code_format.format(
  2151. unique_id=unique_id,
  2152. char_width=char_width,
  2153. char_height=char_height,
  2154. line_height=line_height,
  2155. terminal_width=char_width * width - 1,
  2156. terminal_height=(y + 1) * line_height - 1,
  2157. width=terminal_width + margin_width,
  2158. height=terminal_height + margin_height,
  2159. terminal_x=margin_left + padding_left,
  2160. terminal_y=margin_top + padding_top,
  2161. styles=styles,
  2162. chrome=chrome,
  2163. backgrounds=backgrounds,
  2164. matrix=matrix,
  2165. lines=lines,
  2166. )
  2167. return svg
  2168. def save_svg(
  2169. self,
  2170. path: str,
  2171. *,
  2172. title: str = "Rich",
  2173. theme: Optional[TerminalTheme] = None,
  2174. clear: bool = True,
  2175. code_format: str = CONSOLE_SVG_FORMAT,
  2176. font_aspect_ratio: float = 0.61,
  2177. unique_id: Optional[str] = None,
  2178. ) -> None:
  2179. """Generate an SVG file from the console contents (requires record=True in Console constructor).
  2180. Args:
  2181. path (str): The path to write the SVG to.
  2182. title (str, optional): The title of the tab in the output image
  2183. theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal
  2184. clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``
  2185. code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables
  2186. into the string in order to form the final SVG output. The default template used and the variables
  2187. injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.
  2188. font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format``
  2189. string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font).
  2190. If you aren't specifying a different font inside ``code_format``, you probably don't need this.
  2191. unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node
  2192. ids). If not set, this defaults to a computed value based on the recorded content.
  2193. """
  2194. svg = self.export_svg(
  2195. title=title,
  2196. theme=theme,
  2197. clear=clear,
  2198. code_format=code_format,
  2199. font_aspect_ratio=font_aspect_ratio,
  2200. unique_id=unique_id,
  2201. )
  2202. with open(path, "wt", encoding="utf-8") as write_file:
  2203. write_file.write(svg)
  2204. def _svg_hash(svg_main_code: str) -> str:
  2205. """Returns a unique hash for the given SVG main code.
  2206. Args:
  2207. svg_main_code (str): The content we're going to inject in the SVG envelope.
  2208. Returns:
  2209. str: a hash of the given content
  2210. """
  2211. return str(zlib.adler32(svg_main_code.encode()))
  2212. if __name__ == "__main__": # pragma: no cover
  2213. console = Console(record=True)
  2214. console.log(
  2215. "JSONRPC [i]request[/i]",
  2216. 5,
  2217. 1.3,
  2218. True,
  2219. False,
  2220. None,
  2221. {
  2222. "jsonrpc": "2.0",
  2223. "method": "subtract",
  2224. "params": {"minuend": 42, "subtrahend": 23},
  2225. "id": 3,
  2226. },
  2227. )
  2228. console.log("Hello, World!", "{'a': 1}", repr(console))
  2229. console.print(
  2230. {
  2231. "name": None,
  2232. "empty": [],
  2233. "quiz": {
  2234. "sport": {
  2235. "answered": True,
  2236. "q1": {
  2237. "question": "Which one is correct team name in NBA?",
  2238. "options": [
  2239. "New York Bulls",
  2240. "Los Angeles Kings",
  2241. "Golden State Warriors",
  2242. "Huston Rocket",
  2243. ],
  2244. "answer": "Huston Rocket",
  2245. },
  2246. },
  2247. "maths": {
  2248. "answered": False,
  2249. "q1": {
  2250. "question": "5 + 7 = ?",
  2251. "options": [10, 11, 12, 13],
  2252. "answer": 12,
  2253. },
  2254. "q2": {
  2255. "question": "12 - 8 = ?",
  2256. "options": [1, 2, 3, 4],
  2257. "answer": 4,
  2258. },
  2259. },
  2260. },
  2261. }
  2262. )