console.py 79 KB

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