termui.py 28 KB

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