termui.py 28 KB

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