termui.py 28 KB

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