You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

808 lines
28KB

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