termui.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. from __future__ import annotations
  2. import collections.abc as cabc
  3. import inspect
  4. import io
  5. import itertools
  6. import sys
  7. import typing as t
  8. from contextlib import AbstractContextManager
  9. from gettext import gettext as _
  10. from ._compat import isatty
  11. from ._compat import strip_ansi
  12. from .exceptions import Abort
  13. from .exceptions import UsageError
  14. from .globals import resolve_color_default
  15. from .types import Choice
  16. from .types import convert_type
  17. from .types import ParamType
  18. from .utils import echo
  19. from .utils import LazyFile
  20. if t.TYPE_CHECKING:
  21. from ._termui_impl import ProgressBar
  22. V = t.TypeVar("V")
  23. # The prompt functions to use. The doc tools currently override these
  24. # functions to customize how they work.
  25. visible_prompt_func: t.Callable[[str], str] = input
  26. _ansi_colors = {
  27. "black": 30,
  28. "red": 31,
  29. "green": 32,
  30. "yellow": 33,
  31. "blue": 34,
  32. "magenta": 35,
  33. "cyan": 36,
  34. "white": 37,
  35. "reset": 39,
  36. "bright_black": 90,
  37. "bright_red": 91,
  38. "bright_green": 92,
  39. "bright_yellow": 93,
  40. "bright_blue": 94,
  41. "bright_magenta": 95,
  42. "bright_cyan": 96,
  43. "bright_white": 97,
  44. }
  45. _ansi_reset_all = "\033[0m"
  46. def hidden_prompt_func(prompt: str) -> str:
  47. import getpass
  48. return getpass.getpass(prompt)
  49. def _build_prompt(
  50. text: str,
  51. suffix: str,
  52. show_default: bool | str = False,
  53. default: t.Any | None = None,
  54. show_choices: bool = True,
  55. type: ParamType | None = None,
  56. ) -> str:
  57. prompt = text
  58. if type is not None and show_choices and isinstance(type, Choice):
  59. prompt += f" ({', '.join(map(str, type.choices))})"
  60. if isinstance(show_default, str):
  61. default = f"({show_default})"
  62. if default is not None and show_default:
  63. prompt = f"{prompt} [{_format_default(default)}]"
  64. return f"{prompt}{suffix}"
  65. def _format_default(default: t.Any) -> t.Any:
  66. if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):
  67. return default.name
  68. return default
  69. def prompt(
  70. text: str,
  71. default: t.Any | None = None,
  72. hide_input: bool = False,
  73. confirmation_prompt: bool | str = False,
  74. type: ParamType | t.Any | None = None,
  75. value_proc: t.Callable[[str], t.Any] | None = None,
  76. prompt_suffix: str = ": ",
  77. show_default: bool | str = True,
  78. err: bool = False,
  79. show_choices: bool = True,
  80. ) -> t.Any:
  81. """Prompts a user for input. This is a convenience function that can
  82. be used to prompt a user for input later.
  83. If the user aborts the input by sending an interrupt signal, this
  84. function will catch it and raise a :exc:`Abort` exception.
  85. :param text: the text to show for the prompt.
  86. :param default: the default value to use if no input happens. If this
  87. is not given it will prompt until it's aborted.
  88. :param hide_input: if this is set to true then the input value will
  89. be hidden.
  90. :param confirmation_prompt: Prompt a second time to confirm the
  91. value. Can be set to a string instead of ``True`` to customize
  92. the message.
  93. :param type: the type to use to check the value against.
  94. :param value_proc: if this parameter is provided it's a function that
  95. is invoked instead of the type conversion to
  96. convert a value.
  97. :param prompt_suffix: a suffix that should be added to the prompt.
  98. :param show_default: shows or hides the default value in the prompt.
  99. If this value is a string, it shows that string
  100. in parentheses instead of the actual value.
  101. :param err: if set to true the file defaults to ``stderr`` instead of
  102. ``stdout``, the same as with echo.
  103. :param show_choices: Show or hide choices if the passed type is a Choice.
  104. For example if type is a Choice of either day or week,
  105. show_choices is true and text is "Group by" then the
  106. prompt will be "Group by (day, week): ".
  107. .. versionchanged:: 8.3.3
  108. ``show_default`` can be a string to show a custom value instead
  109. of the actual default, matching the help text behavior.
  110. .. versionchanged:: 8.3.1
  111. A space is no longer appended to the prompt.
  112. .. versionadded:: 8.0
  113. ``confirmation_prompt`` can be a custom string.
  114. .. versionadded:: 7.0
  115. Added the ``show_choices`` parameter.
  116. .. versionadded:: 6.0
  117. Added unicode support for cmd.exe on Windows.
  118. .. versionadded:: 4.0
  119. Added the `err` parameter.
  120. """
  121. def prompt_func(text: str) -> str:
  122. f = hidden_prompt_func if hide_input else visible_prompt_func
  123. try:
  124. # Write the prompt separately so that we get nice
  125. # coloring through colorama on Windows
  126. echo(text[:-1], nl=False, err=err)
  127. # Echo the last character to stdout to work around an issue where
  128. # readline causes backspace to clear the whole line.
  129. return f(text[-1:])
  130. except (KeyboardInterrupt, EOFError):
  131. # getpass doesn't print a newline if the user aborts input with ^C.
  132. # Allegedly this behavior is inherited from getpass(3).
  133. # A doc bug has been filed at https://bugs.python.org/issue24711
  134. if hide_input:
  135. echo(None, err=err)
  136. raise Abort() from None
  137. if value_proc is None:
  138. value_proc = convert_type(type, default)
  139. prompt = _build_prompt(
  140. text, prompt_suffix, show_default, default, show_choices, type
  141. )
  142. if confirmation_prompt:
  143. if confirmation_prompt is True:
  144. confirmation_prompt = _("Repeat for confirmation")
  145. confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
  146. while True:
  147. while True:
  148. value = prompt_func(prompt)
  149. if value:
  150. break
  151. elif default is not None:
  152. value = default
  153. break
  154. try:
  155. result = value_proc(value)
  156. except UsageError as e:
  157. if hide_input:
  158. echo(_("Error: The value you entered was invalid."), err=err)
  159. else:
  160. echo(_("Error: {e.message}").format(e=e), err=err)
  161. continue
  162. if not confirmation_prompt:
  163. return result
  164. while True:
  165. value2 = prompt_func(confirmation_prompt)
  166. is_empty = not value and not value2
  167. if value2 or is_empty:
  168. break
  169. if value == value2:
  170. return result
  171. echo(_("Error: The two entered values do not match."), err=err)
  172. def confirm(
  173. text: str,
  174. default: bool | None = False,
  175. abort: bool = False,
  176. prompt_suffix: str = ": ",
  177. show_default: bool = True,
  178. err: bool = False,
  179. ) -> bool:
  180. """Prompts for confirmation (yes/no question).
  181. If the user aborts the input by sending a interrupt signal this
  182. function will catch it and raise a :exc:`Abort` exception.
  183. :param text: the question to ask.
  184. :param default: The default value to use when no input is given. If
  185. ``None``, repeat until input is given.
  186. :param abort: if this is set to `True` a negative answer aborts the
  187. exception by raising :exc:`Abort`.
  188. :param prompt_suffix: a suffix that should be added to the prompt.
  189. :param show_default: shows or hides the default value in the prompt.
  190. :param err: if set to true the file defaults to ``stderr`` instead of
  191. ``stdout``, the same as with echo.
  192. .. versionchanged:: 8.3.1
  193. A space is no longer appended to the prompt.
  194. .. versionchanged:: 8.0
  195. Repeat until input is given if ``default`` is ``None``.
  196. .. versionadded:: 4.0
  197. Added the ``err`` parameter.
  198. """
  199. prompt = _build_prompt(
  200. text,
  201. prompt_suffix,
  202. show_default,
  203. "y/n" if default is None else ("Y/n" if default else "y/N"),
  204. )
  205. while True:
  206. try:
  207. # Write the prompt separately so that we get nice
  208. # coloring through colorama on Windows
  209. echo(prompt[:-1], nl=False, err=err)
  210. # Echo the last character to stdout to work around an issue where
  211. # readline causes backspace to clear the whole line.
  212. value = visible_prompt_func(prompt[-1:]).lower().strip()
  213. except (KeyboardInterrupt, EOFError):
  214. raise Abort() from None
  215. if value in ("y", "yes"):
  216. rv = True
  217. elif value in ("n", "no"):
  218. rv = False
  219. elif default is not None and value == "":
  220. rv = default
  221. else:
  222. echo(_("Error: invalid input"), err=err)
  223. continue
  224. break
  225. if abort and not rv:
  226. raise Abort()
  227. return rv
  228. def echo_via_pager(
  229. text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,
  230. color: bool | None = None,
  231. ) -> None:
  232. """This function takes a text and shows it via an environment specific
  233. pager on stdout.
  234. .. versionchanged:: 3.0
  235. Added the `color` flag.
  236. :param text_or_generator: the text to page, or alternatively, a
  237. generator emitting the text to page.
  238. :param color: controls if the pager supports ANSI colors or not. The
  239. default is autodetection.
  240. """
  241. color = resolve_color_default(color)
  242. if inspect.isgeneratorfunction(text_or_generator):
  243. i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()
  244. elif isinstance(text_or_generator, str):
  245. i = [text_or_generator]
  246. else:
  247. i = iter(t.cast("cabc.Iterable[str]", text_or_generator))
  248. # convert every element of i to a text type if necessary
  249. text_generator = (el if isinstance(el, str) else str(el) for el in i)
  250. from ._termui_impl import pager
  251. return pager(itertools.chain(text_generator, "\n"), color)
  252. @t.overload
  253. def progressbar(
  254. *,
  255. length: int,
  256. label: str | None = None,
  257. hidden: bool = False,
  258. show_eta: bool = True,
  259. show_percent: bool | None = None,
  260. show_pos: bool = False,
  261. fill_char: str = "#",
  262. empty_char: str = "-",
  263. bar_template: str = "%(label)s [%(bar)s] %(info)s",
  264. info_sep: str = " ",
  265. width: int = 36,
  266. file: t.TextIO | None = None,
  267. color: bool | None = None,
  268. update_min_steps: int = 1,
  269. ) -> ProgressBar[int]: ...
  270. @t.overload
  271. def progressbar(
  272. iterable: cabc.Iterable[V] | None = None,
  273. length: int | None = None,
  274. label: str | None = None,
  275. hidden: bool = False,
  276. show_eta: bool = True,
  277. show_percent: bool | None = None,
  278. show_pos: bool = False,
  279. item_show_func: t.Callable[[V | None], str | None] | None = None,
  280. fill_char: str = "#",
  281. empty_char: str = "-",
  282. bar_template: str = "%(label)s [%(bar)s] %(info)s",
  283. info_sep: str = " ",
  284. width: int = 36,
  285. file: t.TextIO | None = None,
  286. color: bool | None = None,
  287. update_min_steps: int = 1,
  288. ) -> ProgressBar[V]: ...
  289. def progressbar(
  290. iterable: cabc.Iterable[V] | None = None,
  291. length: int | None = None,
  292. label: str | None = None,
  293. hidden: bool = False,
  294. show_eta: bool = True,
  295. show_percent: bool | None = None,
  296. show_pos: bool = False,
  297. item_show_func: t.Callable[[V | None], str | None] | None = None,
  298. fill_char: str = "#",
  299. empty_char: str = "-",
  300. bar_template: str = "%(label)s [%(bar)s] %(info)s",
  301. info_sep: str = " ",
  302. width: int = 36,
  303. file: t.TextIO | None = None,
  304. color: bool | None = None,
  305. update_min_steps: int = 1,
  306. ) -> ProgressBar[V]:
  307. """This function creates an iterable context manager that can be used
  308. to iterate over something while showing a progress bar. It will
  309. either iterate over the `iterable` or `length` items (that are counted
  310. up). While iteration happens, this function will print a rendered
  311. progress bar to the given `file` (defaults to stdout) and will attempt
  312. to calculate remaining time and more. By default, this progress bar
  313. will not be rendered if the file is not a terminal.
  314. The context manager creates the progress bar. When the context
  315. manager is entered the progress bar is already created. With every
  316. iteration over the progress bar, the iterable passed to the bar is
  317. advanced and the bar is updated. When the context manager exits,
  318. a newline is printed and the progress bar is finalized on screen.
  319. Note: The progress bar is currently designed for use cases where the
  320. total progress can be expected to take at least several seconds.
  321. Because of this, the ProgressBar class object won't display
  322. progress that is considered too fast, and progress where the time
  323. between steps is less than a second.
  324. No printing must happen or the progress bar will be unintentionally
  325. destroyed.
  326. Example usage::
  327. with progressbar(items) as bar:
  328. for item in bar:
  329. do_something_with(item)
  330. Alternatively, if no iterable is specified, one can manually update the
  331. progress bar through the `update()` method instead of directly
  332. iterating over the progress bar. The update method accepts the number
  333. of steps to increment the bar with::
  334. with progressbar(length=chunks.total_bytes) as bar:
  335. for chunk in chunks:
  336. process_chunk(chunk)
  337. bar.update(chunks.bytes)
  338. The ``update()`` method also takes an optional value specifying the
  339. ``current_item`` at the new position. This is useful when used
  340. together with ``item_show_func`` to customize the output for each
  341. manual step::
  342. with click.progressbar(
  343. length=total_size,
  344. label='Unzipping archive',
  345. item_show_func=lambda a: a.filename
  346. ) as bar:
  347. for archive in zip_file:
  348. archive.extract()
  349. bar.update(archive.size, archive)
  350. :param iterable: an iterable to iterate over. If not provided the length
  351. is required.
  352. :param length: the number of items to iterate over. By default the
  353. progressbar will attempt to ask the iterator about its
  354. length, which might or might not work. If an iterable is
  355. also provided this parameter can be used to override the
  356. length. If an iterable is not provided the progress bar
  357. will iterate over a range of that length.
  358. :param label: the label to show next to the progress bar.
  359. :param hidden: hide the progressbar. Defaults to ``False``. When no tty is
  360. detected, it will only print the progressbar label. Setting this to
  361. ``False`` also disables that.
  362. :param show_eta: enables or disables the estimated time display. This is
  363. automatically disabled if the length cannot be
  364. determined.
  365. :param show_percent: enables or disables the percentage display. The
  366. default is `True` if the iterable has a length or
  367. `False` if not.
  368. :param show_pos: enables or disables the absolute position display. The
  369. default is `False`.
  370. :param item_show_func: A function called with the current item which
  371. can return a string to show next to the progress bar. If the
  372. function returns ``None`` nothing is shown. The current item can
  373. be ``None``, such as when entering and exiting the bar.
  374. :param fill_char: the character to use to show the filled part of the
  375. progress bar.
  376. :param empty_char: the character to use to show the non-filled part of
  377. the progress bar.
  378. :param bar_template: the format string to use as template for the bar.
  379. The parameters in it are ``label`` for the label,
  380. ``bar`` for the progress bar and ``info`` for the
  381. info section.
  382. :param info_sep: the separator between multiple info items (eta etc.)
  383. :param width: the width of the progress bar in characters, 0 means full
  384. terminal width
  385. :param file: The file to write to. If this is not a terminal then
  386. only the label is printed.
  387. :param color: controls if the terminal supports ANSI colors or not. The
  388. default is autodetection. This is only needed if ANSI
  389. codes are included anywhere in the progress bar output
  390. which is not the case by default.
  391. :param update_min_steps: Render only when this many updates have
  392. completed. This allows tuning for very fast iterators.
  393. .. versionadded:: 8.2
  394. The ``hidden`` argument.
  395. .. versionchanged:: 8.0
  396. Output is shown even if execution time is less than 0.5 seconds.
  397. .. versionchanged:: 8.0
  398. ``item_show_func`` shows the current item, not the previous one.
  399. .. versionchanged:: 8.0
  400. Labels are echoed if the output is not a TTY. Reverts a change
  401. in 7.0 that removed all output.
  402. .. versionadded:: 8.0
  403. The ``update_min_steps`` parameter.
  404. .. versionadded:: 4.0
  405. The ``color`` parameter and ``update`` method.
  406. .. versionadded:: 2.0
  407. """
  408. from ._termui_impl import ProgressBar
  409. color = resolve_color_default(color)
  410. return ProgressBar(
  411. iterable=iterable,
  412. length=length,
  413. hidden=hidden,
  414. show_eta=show_eta,
  415. show_percent=show_percent,
  416. show_pos=show_pos,
  417. item_show_func=item_show_func,
  418. fill_char=fill_char,
  419. empty_char=empty_char,
  420. bar_template=bar_template,
  421. info_sep=info_sep,
  422. file=file,
  423. label=label,
  424. width=width,
  425. color=color,
  426. update_min_steps=update_min_steps,
  427. )
  428. def clear() -> None:
  429. """Clears the terminal screen. This will have the effect of clearing
  430. the whole visible space of the terminal and moving the cursor to the
  431. top left. This does not do anything if not connected to a terminal.
  432. .. versionadded:: 2.0
  433. """
  434. if not isatty(sys.stdout):
  435. return
  436. # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor
  437. echo("\033[2J\033[1;1H", nl=False)
  438. def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str:
  439. if isinstance(color, int):
  440. return f"{38 + offset};5;{color:d}"
  441. if isinstance(color, (tuple, list)):
  442. r, g, b = color
  443. return f"{38 + offset};2;{r:d};{g:d};{b:d}"
  444. return str(_ansi_colors[color] + offset)
  445. def style(
  446. text: t.Any,
  447. fg: int | tuple[int, int, int] | str | None = None,
  448. bg: int | tuple[int, int, int] | str | None = None,
  449. bold: bool | None = None,
  450. dim: bool | None = None,
  451. underline: bool | None = None,
  452. overline: bool | None = None,
  453. italic: bool | None = None,
  454. blink: bool | None = None,
  455. reverse: bool | None = None,
  456. strikethrough: bool | None = None,
  457. reset: bool = True,
  458. ) -> str:
  459. """Styles a text with ANSI styles and returns the new string. By
  460. default the styling is self contained which means that at the end
  461. of the string a reset code is issued. This can be prevented by
  462. passing ``reset=False``.
  463. Examples::
  464. click.echo(click.style('Hello World!', fg='green'))
  465. click.echo(click.style('ATTENTION!', blink=True))
  466. click.echo(click.style('Some things', reverse=True, fg='cyan'))
  467. click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
  468. Supported color names:
  469. * ``black`` (might be a gray)
  470. * ``red``
  471. * ``green``
  472. * ``yellow`` (might be an orange)
  473. * ``blue``
  474. * ``magenta``
  475. * ``cyan``
  476. * ``white`` (might be light gray)
  477. * ``bright_black``
  478. * ``bright_red``
  479. * ``bright_green``
  480. * ``bright_yellow``
  481. * ``bright_blue``
  482. * ``bright_magenta``
  483. * ``bright_cyan``
  484. * ``bright_white``
  485. * ``reset`` (reset the color code only)
  486. If the terminal supports it, color may also be specified as:
  487. - An integer in the interval [0, 255]. The terminal must support
  488. 8-bit/256-color mode.
  489. - An RGB tuple of three integers in [0, 255]. The terminal must
  490. support 24-bit/true-color mode.
  491. See https://en.wikipedia.org/wiki/ANSI_color and
  492. https://gist.github.com/XVilka/8346728 for more information.
  493. :param text: the string to style with ansi codes.
  494. :param fg: if provided this will become the foreground color.
  495. :param bg: if provided this will become the background color.
  496. :param bold: if provided this will enable or disable bold mode.
  497. :param dim: if provided this will enable or disable dim mode. This is
  498. badly supported.
  499. :param underline: if provided this will enable or disable underline.
  500. :param overline: if provided this will enable or disable overline.
  501. :param italic: if provided this will enable or disable italic.
  502. :param blink: if provided this will enable or disable blinking.
  503. :param reverse: if provided this will enable or disable inverse
  504. rendering (foreground becomes background and the
  505. other way round).
  506. :param strikethrough: if provided this will enable or disable
  507. striking through text.
  508. :param reset: by default a reset-all code is added at the end of the
  509. string which means that styles do not carry over. This
  510. can be disabled to compose styles.
  511. .. versionchanged:: 8.0
  512. A non-string ``message`` is converted to a string.
  513. .. versionchanged:: 8.0
  514. Added support for 256 and RGB color codes.
  515. .. versionchanged:: 8.0
  516. Added the ``strikethrough``, ``italic``, and ``overline``
  517. parameters.
  518. .. versionchanged:: 7.0
  519. Added support for bright colors.
  520. .. versionadded:: 2.0
  521. """
  522. if not isinstance(text, str):
  523. text = str(text)
  524. bits = []
  525. if fg:
  526. try:
  527. bits.append(f"\033[{_interpret_color(fg)}m")
  528. except KeyError:
  529. raise TypeError(f"Unknown color {fg!r}") from None
  530. if bg:
  531. try:
  532. bits.append(f"\033[{_interpret_color(bg, 10)}m")
  533. except KeyError:
  534. raise TypeError(f"Unknown color {bg!r}") from None
  535. if bold is not None:
  536. bits.append(f"\033[{1 if bold else 22}m")
  537. if dim is not None:
  538. bits.append(f"\033[{2 if dim else 22}m")
  539. if underline is not None:
  540. bits.append(f"\033[{4 if underline else 24}m")
  541. if overline is not None:
  542. bits.append(f"\033[{53 if overline else 55}m")
  543. if italic is not None:
  544. bits.append(f"\033[{3 if italic else 23}m")
  545. if blink is not None:
  546. bits.append(f"\033[{5 if blink else 25}m")
  547. if reverse is not None:
  548. bits.append(f"\033[{7 if reverse else 27}m")
  549. if strikethrough is not None:
  550. bits.append(f"\033[{9 if strikethrough else 29}m")
  551. bits.append(text)
  552. if reset:
  553. bits.append(_ansi_reset_all)
  554. return "".join(bits)
  555. def unstyle(text: str) -> str:
  556. """Removes ANSI styling information from a string. Usually it's not
  557. necessary to use this function as Click's echo function will
  558. automatically remove styling if necessary.
  559. .. versionadded:: 2.0
  560. :param text: the text to remove style information from.
  561. """
  562. return strip_ansi(text)
  563. def secho(
  564. message: t.Any | None = None,
  565. file: t.IO[t.AnyStr] | None = None,
  566. nl: bool = True,
  567. err: bool = False,
  568. color: bool | None = None,
  569. **styles: t.Any,
  570. ) -> None:
  571. """This function combines :func:`echo` and :func:`style` into one
  572. call. As such the following two calls are the same::
  573. click.secho('Hello World!', fg='green')
  574. click.echo(click.style('Hello World!', fg='green'))
  575. All keyword arguments are forwarded to the underlying functions
  576. depending on which one they go with.
  577. Non-string types will be converted to :class:`str`. However,
  578. :class:`bytes` are passed directly to :meth:`echo` without applying
  579. style. If you want to style bytes that represent text, call
  580. :meth:`bytes.decode` first.
  581. .. versionchanged:: 8.0
  582. A non-string ``message`` is converted to a string. Bytes are
  583. passed through without style applied.
  584. .. versionadded:: 2.0
  585. """
  586. if message is not None and not isinstance(message, (bytes, bytearray)):
  587. message = style(message, **styles)
  588. return echo(message, file=file, nl=nl, err=err, color=color)
  589. @t.overload
  590. def edit(
  591. text: bytes | bytearray,
  592. editor: str | None = None,
  593. env: cabc.Mapping[str, str] | None = None,
  594. require_save: bool = False,
  595. extension: str = ".txt",
  596. ) -> bytes | None: ...
  597. @t.overload
  598. def edit(
  599. text: str,
  600. editor: str | None = None,
  601. env: cabc.Mapping[str, str] | None = None,
  602. require_save: bool = True,
  603. extension: str = ".txt",
  604. ) -> str | None: ...
  605. @t.overload
  606. def edit(
  607. text: None = None,
  608. editor: str | None = None,
  609. env: cabc.Mapping[str, str] | None = None,
  610. require_save: bool = True,
  611. extension: str = ".txt",
  612. filename: str | cabc.Iterable[str] | None = None,
  613. ) -> None: ...
  614. def edit(
  615. text: str | bytes | bytearray | None = None,
  616. editor: str | None = None,
  617. env: cabc.Mapping[str, str] | None = None,
  618. require_save: bool = True,
  619. extension: str = ".txt",
  620. filename: str | cabc.Iterable[str] | None = None,
  621. ) -> str | bytes | bytearray | None:
  622. r"""Edits the given text in the defined editor. If an editor is given
  623. (should be the full path to the executable but the regular operating
  624. system search path is used for finding the executable) it overrides
  625. the detected editor. Optionally, some environment variables can be
  626. used. If the editor is closed without changes, `None` is returned. In
  627. case a file is edited directly the return value is always `None` and
  628. `require_save` and `extension` are ignored.
  629. If the editor cannot be opened a :exc:`UsageError` is raised.
  630. Note for Windows: to simplify cross-platform usage, the newlines are
  631. automatically converted from POSIX to Windows and vice versa. As such,
  632. the message here will have ``\n`` as newline markers.
  633. :param text: the text to edit.
  634. :param editor: optionally the editor to use. Defaults to automatic
  635. detection.
  636. :param env: environment variables to forward to the editor.
  637. :param require_save: if this is true, then not saving in the editor
  638. will make the return value become `None`.
  639. :param extension: the extension to tell the editor about. This defaults
  640. to `.txt` but changing this might change syntax
  641. highlighting.
  642. :param filename: if provided it will edit this file instead of the
  643. provided text contents. It will not use a temporary
  644. file as an indirection in that case. If the editor supports
  645. editing multiple files at once, a sequence of files may be
  646. passed as well. Invoke `click.file` once per file instead
  647. if multiple files cannot be managed at once or editing the
  648. files serially is desired.
  649. .. versionchanged:: 8.2.0
  650. ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str``
  651. if the ``editor`` supports editing multiple files at once.
  652. """
  653. from ._termui_impl import Editor
  654. ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
  655. if filename is None:
  656. return ed.edit(text)
  657. if isinstance(filename, str):
  658. filename = (filename,)
  659. ed.edit_files(filenames=filename)
  660. return None
  661. def launch(url: str, wait: bool = False, locate: bool = False) -> int:
  662. """This function launches the given URL (or filename) in the default
  663. viewer application for this file type. If this is an executable, it
  664. might launch the executable in a new session. The return value is
  665. the exit code of the launched application. Usually, ``0`` indicates
  666. success.
  667. Examples::
  668. click.launch('https://click.palletsprojects.com/')
  669. click.launch('/my/downloaded/file', locate=True)
  670. .. versionadded:: 2.0
  671. :param url: URL or filename of the thing to launch.
  672. :param wait: Wait for the program to exit before returning. This
  673. only works if the launched program blocks. In particular,
  674. ``xdg-open`` on Linux does not block.
  675. :param locate: if this is set to `True` then instead of launching the
  676. application associated with the URL it will attempt to
  677. launch a file manager with the file located. This
  678. might have weird effects if the URL does not point to
  679. the filesystem.
  680. """
  681. from ._termui_impl import open_url
  682. return open_url(url, wait=wait, locate=locate)
  683. # If this is provided, getchar() calls into this instead. This is used
  684. # for unittesting purposes.
  685. _getchar: t.Callable[[bool], str] | None = None
  686. def getchar(echo: bool = False) -> str:
  687. """Fetches a single character from the terminal and returns it. This
  688. will always return a unicode character and under certain rare
  689. circumstances this might return more than one character. The
  690. situations which more than one character is returned is when for
  691. whatever reason multiple characters end up in the terminal buffer or
  692. standard input was not actually a terminal.
  693. Note that this will always read from the terminal, even if something
  694. is piped into the standard input.
  695. Note for Windows: in rare cases when typing non-ASCII characters, this
  696. function might wait for a second character and then return both at once.
  697. This is because certain Unicode characters look like special-key markers.
  698. .. versionadded:: 2.0
  699. :param echo: if set to `True`, the character read will also show up on
  700. the terminal. The default is to not show it.
  701. """
  702. global _getchar
  703. if _getchar is None:
  704. from ._termui_impl import getchar as f
  705. _getchar = f
  706. return _getchar(echo)
  707. def raw_terminal() -> AbstractContextManager[int]:
  708. from ._termui_impl import raw_terminal as f
  709. return f()
  710. def pause(info: str | None = None, err: bool = False) -> None:
  711. """This command stops execution and waits for the user to press any
  712. key to continue. This is similar to the Windows batch "pause"
  713. command. If the program is not run through a terminal, this command
  714. will instead do nothing.
  715. .. versionadded:: 2.0
  716. .. versionadded:: 4.0
  717. Added the `err` parameter.
  718. :param info: The message to print before pausing. Defaults to
  719. ``"Press any key to continue..."``.
  720. :param err: if set to message goes to ``stderr`` instead of
  721. ``stdout``, the same as with echo.
  722. """
  723. if not isatty(sys.stdin) or not isatty(sys.stdout):
  724. return
  725. if info is None:
  726. info = _("Press any key to continue...")
  727. try:
  728. if info:
  729. echo(info, nl=False, err=err)
  730. try:
  731. getchar()
  732. except (KeyboardInterrupt, EOFError):
  733. pass
  734. finally:
  735. if info:
  736. echo(err=err)