Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/click/termui.py: 27%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3import collections.abc as cabc
4import inspect
5import io
6import itertools
7import re
8import sys
9import typing as t
10from contextlib import AbstractContextManager
11from contextlib import redirect_stdout
12from gettext import gettext as _
14from . import _compat
15from ._compat import isatty
16from ._compat import strip_ansi
17from .exceptions import Abort
18from .exceptions import UsageError
19from .globals import resolve_color_default
20from .types import Choice
21from .types import convert_type
22from .types import ParamType
23from .utils import _LazyFile
24from .utils import echo
26if t.TYPE_CHECKING:
27 from ._termui_impl import ProgressBar
29V = t.TypeVar("V")
31# The prompt functions to use. The doc tools currently override these
32# functions to customize how they work.
33visible_prompt_func: t.Callable[[str], str] = input
35_ansi_colors = {
36 "black": 30,
37 "red": 31,
38 "green": 32,
39 "yellow": 33,
40 "blue": 34,
41 "magenta": 35,
42 "cyan": 36,
43 "white": 37,
44 "reset": 39,
45 "bright_black": 90,
46 "bright_red": 91,
47 "bright_green": 92,
48 "bright_yellow": 93,
49 "bright_blue": 94,
50 "bright_magenta": 95,
51 "bright_cyan": 96,
52 "bright_white": 97,
53}
54_ansi_reset_all = "\033[0m"
57_HIDDEN_INPUT_MASK = "'***'"
60def _mask_hidden_input(message: str, value: str) -> str:
61 """Replace occurrences of ``value`` in ``message`` with a fixed mask.
63 Both ``repr(value)`` (the form built-in :class:`ParamType` errors use
64 via ``{value!r}``) and the raw value are masked. The raw-value pass
65 uses word-boundary lookarounds so a substring like ``"1"`` does not
66 match inside ``"10"``, and ``"ent"`` does not match inside
67 ``"Authentication"``. The empty string is skipped to avoid matching
68 at every boundary.
69 """
70 message = message.replace(repr(value), _HIDDEN_INPUT_MASK)
71 if value:
72 message = re.sub(
73 rf"(?<!\w){re.escape(value)}(?!\w)", _HIDDEN_INPUT_MASK, message
74 )
75 return message
78def hidden_prompt_func(prompt: str) -> str:
79 import getpass
81 return getpass.getpass(prompt)
84def _readline_prompt(func: t.Callable[[str], str], text: str, err: bool) -> str:
85 """Call a prompt function, passing the full prompt so readline can
86 handle line editing and cursor positioning correctly.
88 The prompt is handed to *func* (such as :func:`input`) rather than
89 written through :func:`echo`, so it has to strip ANSI color and style
90 codes itself when the destination stream does not support them. Without
91 this the prompt would keep codes that :func:`echo` removes from the
92 rest of the output.
93 """
94 stream = sys.stderr if err else sys.stdout
96 # Look up ``should_strip_ansi`` on the module so that ``CliRunner``,
97 # which patches it there during test isolation, is honored.
98 if _compat.should_strip_ansi(stream, resolve_color_default()):
99 text = strip_ansi(text)
101 if err:
102 with redirect_stdout(sys.stderr):
103 return func(text)
104 return func(text)
107def _build_prompt(
108 text: str,
109 suffix: str,
110 show_default: bool | str = False,
111 default: object | None = None,
112 show_choices: bool = True,
113 type: object | None = None,
114) -> str:
115 prompt = text
116 if type is not None and show_choices and isinstance(type, Choice):
117 prompt += f" ({', '.join(map(str, type.choices))})"
118 default_preview = ""
119 if show_default:
120 if isinstance(show_default, str):
121 default_preview = f" [({show_default})]"
122 elif default is not None:
123 default_preview = f" [{_format_default(default)}]"
124 return f"{prompt}{default_preview}{suffix}"
127def _format_default(default: V) -> V | str:
128 if isinstance(default, (io.IOBase, _LazyFile)):
129 name = getattr(default, "name", None)
131 if name is not None:
132 return str(name)
134 return default
137@t.overload
138def prompt(
139 text: str,
140 default: str | None = None,
141 hide_input: bool = False,
142 confirmation_prompt: bool | str = False,
143 type: None = None,
144 value_proc: None = None,
145 prompt_suffix: str = ": ",
146 show_default: bool | str = True,
147 err: bool = False,
148 show_choices: bool = True,
149) -> str: ...
152@t.overload
153def prompt(
154 text: str,
155 default: V | str | None = None,
156 hide_input: bool = False,
157 confirmation_prompt: bool | str = False,
158 type: ParamType[V, str] | type[V] | None = None,
159 value_proc: t.Callable[[str], V] | None = None,
160 prompt_suffix: str = ": ",
161 show_default: bool | str = True,
162 err: bool = False,
163 show_choices: bool = True,
164) -> V: ...
167def prompt(
168 text: str,
169 default: V | str | None = None,
170 hide_input: bool = False,
171 confirmation_prompt: bool | str = False,
172 type: ParamType[V, str] | type[V] | None = None,
173 value_proc: t.Callable[[str], V] | None = None,
174 prompt_suffix: str = ": ",
175 show_default: bool | str = True,
176 err: bool = False,
177 show_choices: bool = True,
178) -> V:
179 """Prompts a user for input. This is a convenience function that can
180 be used to prompt a user for input later.
182 If the user aborts the input by sending an interrupt signal, this
183 function will catch it and raise a :exc:`Abort` exception.
185 :param text: the text to show for the prompt.
186 :param default: the default value to use if no input happens. If this
187 is not given it will prompt until it's aborted.
188 :param hide_input: if this is set to true then the input value will
189 be hidden.
190 :param confirmation_prompt: Prompt a second time to confirm the
191 value. Can be set to a string instead of ``True`` to customize
192 the message.
193 :param type: the type to use to check the value against.
194 :param value_proc: if this parameter is provided it's a function that
195 is invoked instead of the type conversion to
196 convert a value.
197 :param prompt_suffix: a suffix that should be added to the prompt.
198 :param show_default: shows or hides the default value in the prompt.
199 If this value is a string, it shows that string
200 in parentheses instead of the actual value.
201 :param err: if set to true the file defaults to ``stderr`` instead of
202 ``stdout``, the same as with echo.
203 :param show_choices: Show or hide choices if the passed type is a Choice.
204 For example if type is a Choice of either day or week,
205 show_choices is true and text is "Group by" then the
206 prompt will be "Group by (day, week): ".
208 .. versionchanged:: 8.5.0
209 Generically typed: the return type is narrowed by ``type``,
210 ``value_proc``, or ``default`` instead of being ``Any``. Runtime
211 behavior is unchanged.
213 .. versionchanged:: 8.3.3
214 ``show_default`` can be a string to show a custom value instead
215 of the actual default, matching the help text behavior.
217 .. versionchanged:: 8.3.1
218 A space is no longer appended to the prompt.
220 .. versionadded:: 8.0
221 ``confirmation_prompt`` can be a custom string.
223 .. versionadded:: 7.0
224 Added the ``show_choices`` parameter.
226 .. versionadded:: 6.0
227 Added unicode support for cmd.exe on Windows.
229 .. versionadded:: 4.0
230 Added the `err` parameter.
232 """
234 def prompt_func(text: str) -> str:
235 f = hidden_prompt_func if hide_input else visible_prompt_func
236 try:
237 return _readline_prompt(f, text, err)
238 except (KeyboardInterrupt, EOFError):
239 # getpass doesn't print a newline if the user aborts input with ^C.
240 # Allegedly this behavior is inherited from getpass(3).
241 # A doc bug has been filed at https://bugs.python.org/issue24711
242 if hide_input:
243 echo(None, err=err)
244 raise Abort() from None
246 if value_proc is None:
247 value_proc = convert_type(type, default)
249 prompt = _build_prompt(
250 text, prompt_suffix, show_default, default, show_choices, type
251 )
253 if confirmation_prompt:
254 if confirmation_prompt is True:
255 confirmation_prompt = _("Repeat for confirmation")
257 confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
259 while True:
260 while True:
261 value = prompt_func(prompt)
262 if value:
263 break
264 elif default is not None:
265 # Defaults of any type are accepted and round trip through
266 # value_proc like typed input, so the annotation is only
267 # accurate for typed input.
268 value = t.cast("str", default)
269 break
270 try:
271 result = value_proc(value)
272 except UsageError as e:
273 message = _mask_hidden_input(e.message, value) if hide_input else e.message
274 echo(_("Error: {message}").format(message=message), err=err)
275 continue
276 if not confirmation_prompt:
277 return result
278 while True:
279 value2 = prompt_func(confirmation_prompt)
280 is_empty = not value and not value2
281 if value2 or is_empty:
282 break
283 if value == value2:
284 return result
285 echo(_("Error: The two entered values do not match."), err=err)
288def confirm(
289 text: str,
290 default: bool | None = False,
291 abort: bool = False,
292 prompt_suffix: str = ": ",
293 show_default: bool = True,
294 err: bool = False,
295) -> bool:
296 """Prompts for confirmation (yes/no question).
298 If the user aborts the input by sending a interrupt signal this
299 function will catch it and raise a :exc:`Abort` exception.
301 :param text: the question to ask.
302 :param default: The default value to use when no input is given. If
303 ``None``, repeat until input is given.
304 :param abort: if this is set to `True` a negative answer aborts the
305 exception by raising :exc:`Abort`.
306 :param prompt_suffix: a suffix that should be added to the prompt.
307 :param show_default: shows or hides the default value in the prompt.
308 :param err: if set to true the file defaults to ``stderr`` instead of
309 ``stdout``, the same as with echo.
311 .. versionchanged:: 8.3.1
312 A space is no longer appended to the prompt.
314 .. versionchanged:: 8.0
315 Repeat until input is given if ``default`` is ``None``.
317 .. versionadded:: 4.0
318 Added the ``err`` parameter.
319 """
320 prompt = _build_prompt(
321 text,
322 prompt_suffix,
323 show_default,
324 "y/n" if default is None else ("Y/n" if default else "y/N"),
325 )
327 while True:
328 try:
329 value = _readline_prompt(visible_prompt_func, prompt, err).lower().strip()
330 except (KeyboardInterrupt, EOFError):
331 raise Abort() from None
332 if value in ("y", "yes"):
333 rv = True
334 elif value in ("n", "no"):
335 rv = False
336 elif default is not None and value == "":
337 rv = default
338 else:
339 echo(_("Error: invalid input"), err=err)
340 continue
341 break
342 if abort and not rv:
343 raise Abort()
344 return rv
347def get_pager_file(
348 color: bool | None = None,
349) -> t.ContextManager[t.TextIO]:
350 """Context manager.
352 Yields a writable file-like object which can be used as an output pager.
354 .. versionadded:: 8.4.0
356 :param color: controls if the pager supports ANSI colors or not. The
357 default is autodetection.
358 """
359 from ._termui_impl import get_pager_file
361 color = resolve_color_default(color)
363 return get_pager_file(color=color)
366def echo_via_pager(
367 text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,
368 color: bool | None = None,
369) -> None:
370 """This function takes a text and shows it via an environment specific
371 pager on stdout.
373 .. versionchanged:: 3.0
374 Added the `color` flag.
376 :param text_or_generator: the text to page, or alternatively, a
377 generator emitting the text to page.
378 :param color: controls if the pager supports ANSI colors or not. The
379 default is autodetection.
380 """
382 if inspect.isgeneratorfunction(text_or_generator):
383 i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()
384 elif isinstance(text_or_generator, str):
385 i = [text_or_generator]
386 else:
387 i = iter(t.cast("cabc.Iterable[str]", text_or_generator))
389 # convert every element of i to a text type if necessary
390 text_generator = (el if isinstance(el, str) else str(el) for el in i)
392 with get_pager_file(color=color) as pager:
393 for text in itertools.chain(text_generator, "\n"):
394 pager.write(text)
395 # Flush after each write so a slow generator streams to the pager
396 # incrementally rather than staying invisible until the pipe buffer
397 # fills (~8 KB).
398 pager.flush()
401@t.overload
402def progressbar(
403 *,
404 length: int,
405 label: str | None = None,
406 hidden: bool = False,
407 show_eta: bool = True,
408 show_percent: bool | None = None,
409 show_pos: bool = False,
410 fill_char: str = "#",
411 empty_char: str = "-",
412 bar_template: str = "%(label)s [%(bar)s] %(info)s",
413 info_sep: str = " ",
414 width: int = 36,
415 file: t.TextIO | None = None,
416 color: bool | None = None,
417 update_min_steps: int = 1,
418) -> ProgressBar[int]: ...
421@t.overload
422def progressbar(
423 iterable: cabc.Iterable[V] | None = None,
424 length: int | None = None,
425 label: str | None = None,
426 hidden: bool = False,
427 show_eta: bool = True,
428 show_percent: bool | None = None,
429 show_pos: bool = False,
430 item_show_func: t.Callable[[V | None], str | None] | None = None,
431 fill_char: str = "#",
432 empty_char: str = "-",
433 bar_template: str = "%(label)s [%(bar)s] %(info)s",
434 info_sep: str = " ",
435 width: int = 36,
436 file: t.TextIO | None = None,
437 color: bool | None = None,
438 update_min_steps: int = 1,
439) -> ProgressBar[V]: ...
442def progressbar(
443 iterable: cabc.Iterable[V] | None = None,
444 length: int | None = None,
445 label: str | None = None,
446 hidden: bool = False,
447 show_eta: bool = True,
448 show_percent: bool | None = None,
449 show_pos: bool = False,
450 item_show_func: t.Callable[[V | None], str | None] | None = None,
451 fill_char: str = "#",
452 empty_char: str = "-",
453 bar_template: str = "%(label)s [%(bar)s] %(info)s",
454 info_sep: str = " ",
455 width: int = 36,
456 file: t.TextIO | None = None,
457 color: bool | None = None,
458 update_min_steps: int = 1,
459) -> ProgressBar[V]:
460 """This function creates an iterable context manager that can be used
461 to iterate over something while showing a progress bar. It will
462 either iterate over the `iterable` or `length` items (that are counted
463 up). While iteration happens, this function will print a rendered
464 progress bar to the given `file` (defaults to stdout) and will attempt
465 to calculate remaining time and more. By default, this progress bar
466 will not be rendered if the file is not a terminal.
468 The context manager creates the progress bar. When the context
469 manager is entered the progress bar is already created. With every
470 iteration over the progress bar, the iterable passed to the bar is
471 advanced and the bar is updated. When the context manager exits,
472 a newline is printed and the progress bar is finalized on screen.
474 Note: The progress bar is currently designed for use cases where the
475 total progress can be expected to take at least several seconds.
476 Because of this, the ProgressBar class object won't display
477 progress that is considered too fast, and progress where the time
478 between steps is less than a second.
480 No printing must happen or the progress bar will be unintentionally
481 destroyed.
483 Example usage::
485 with progressbar(items) as bar:
486 for item in bar:
487 do_something_with(item)
489 Alternatively, if no iterable is specified, one can manually update the
490 progress bar through the `update()` method instead of directly
491 iterating over the progress bar. The update method accepts the number
492 of steps to increment the bar with::
494 with progressbar(length=chunks.total_bytes) as bar:
495 for chunk in chunks:
496 process_chunk(chunk)
497 bar.update(chunks.bytes)
499 The ``update()`` method also takes an optional value specifying the
500 ``current_item`` at the new position. This is useful when used
501 together with ``item_show_func`` to customize the output for each
502 manual step::
504 with click.progressbar(
505 length=total_size,
506 label='Unzipping archive',
507 item_show_func=lambda a: a.filename
508 ) as bar:
509 for archive in zip_file:
510 archive.extract()
511 bar.update(archive.size, archive)
513 :param iterable: an iterable to iterate over. If not provided the length
514 is required.
515 :param length: the number of items to iterate over. By default the
516 progressbar will attempt to ask the iterator about its
517 length, which might or might not work. If an iterable is
518 also provided this parameter can be used to override the
519 length. If an iterable is not provided the progress bar
520 will iterate over a range of that length.
521 :param label: the label to show next to the progress bar.
522 :param hidden: hide the progressbar. Defaults to ``False``. When no tty is
523 detected, it will only print the progressbar label. Setting this to
524 ``False`` also disables that.
525 :param show_eta: enables or disables the estimated time display. This is
526 automatically disabled if the length cannot be
527 determined.
528 :param show_percent: enables or disables the percentage display. The
529 default is `True` if the iterable has a length or
530 `False` if not.
531 :param show_pos: enables or disables the absolute position display. The
532 default is `False`.
533 :param item_show_func: A function called with the current item which
534 can return a string to show next to the progress bar. If the
535 function returns ``None`` nothing is shown. The current item can
536 be ``None``, such as when entering and exiting the bar.
537 :param fill_char: the character to use to show the filled part of the
538 progress bar.
539 :param empty_char: the character to use to show the non-filled part of
540 the progress bar.
541 :param bar_template: the format string to use as template for the bar.
542 The parameters in it are ``label`` for the label,
543 ``bar`` for the progress bar and ``info`` for the
544 info section.
545 :param info_sep: the separator between multiple info items (eta etc.)
546 :param width: the width of the progress bar in characters, 0 means full
547 terminal width
548 :param file: The file to write to. If this is not a terminal then
549 only the label is printed.
550 :param color: controls if the terminal supports ANSI colors or not. The
551 default is autodetection. This is only needed if ANSI
552 codes are included anywhere in the progress bar output
553 which is not the case by default.
554 :param update_min_steps: Render only when this many updates have
555 completed. This allows tuning for very fast iterators.
557 .. versionadded:: 8.2
558 The ``hidden`` argument.
560 .. versionchanged:: 8.0
561 Output is shown even if execution time is less than 0.5 seconds.
563 .. versionchanged:: 8.0
564 ``item_show_func`` shows the current item, not the previous one.
566 .. versionchanged:: 8.0
567 Labels are echoed if the output is not a TTY. Reverts a change
568 in 7.0 that removed all output.
570 .. versionadded:: 8.0
571 The ``update_min_steps`` parameter.
573 .. versionadded:: 4.0
574 The ``color`` parameter and ``update`` method.
576 .. versionadded:: 2.0
577 """
578 from ._termui_impl import ProgressBar
580 color = resolve_color_default(color)
581 return ProgressBar(
582 iterable=iterable,
583 length=length,
584 hidden=hidden,
585 show_eta=show_eta,
586 show_percent=show_percent,
587 show_pos=show_pos,
588 item_show_func=item_show_func,
589 fill_char=fill_char,
590 empty_char=empty_char,
591 bar_template=bar_template,
592 info_sep=info_sep,
593 file=file,
594 label=label,
595 width=width,
596 color=color,
597 update_min_steps=update_min_steps,
598 )
601def clear() -> None:
602 """Clears the terminal screen. This will have the effect of clearing
603 the whole visible space of the terminal and moving the cursor to the
604 top left. This does not do anything if not connected to a terminal.
606 .. versionadded:: 2.0
607 """
608 if not isatty(sys.stdout):
609 return
611 # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor
612 echo("\033[2J\033[1;1H", nl=False)
615def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str:
616 """Interprets a color value and returns the corresponding ANSI code."""
617 if isinstance(color, str) and color in _ansi_colors:
618 return str(_ansi_colors[color] + offset)
620 # bool is an int subclass: without the exclusion, True and False would
621 # silently render as the palette indices 1 and 0.
622 elif isinstance(color, int) and not isinstance(color, bool):
623 if 0 <= color <= 255:
624 return f"{38 + offset};5;{color:d}"
626 elif (
627 isinstance(color, (tuple, list))
628 and len(color) == 3
629 and all(
630 isinstance(c, int) and not isinstance(c, bool) and 0 <= c <= 255
631 for c in color
632 )
633 ):
634 r, g, b = color
635 return f"{38 + offset};2;{r:d};{g:d};{b:d}"
637 raise ValueError(_("Unknown color {colour!r}").format(colour=color))
640def style(
641 text: t.Any,
642 fg: int | tuple[int, int, int] | str | None = None,
643 bg: int | tuple[int, int, int] | str | None = None,
644 bold: bool | None = None,
645 dim: bool | None = None,
646 underline: bool | None = None,
647 overline: bool | None = None,
648 italic: bool | None = None,
649 blink: bool | None = None,
650 reverse: bool | None = None,
651 strikethrough: bool | None = None,
652 reset: bool = True,
653) -> str:
654 """Styles a text with ANSI styles and returns the new string. By
655 default the styling is self contained which means that at the end
656 of the string a reset code is issued. This can be prevented by
657 passing ``reset=False``.
659 Examples::
661 click.echo(click.style('Hello World!', fg='green'))
662 click.echo(click.style('ATTENTION!', blink=True))
663 click.echo(click.style('Some things', reverse=True, fg='cyan'))
664 click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
666 Supported color names:
668 * ``black`` (might be a gray)
669 * ``red``
670 * ``green``
671 * ``yellow`` (might be an orange)
672 * ``blue``
673 * ``magenta``
674 * ``cyan``
675 * ``white`` (might be light gray)
676 * ``bright_black``
677 * ``bright_red``
678 * ``bright_green``
679 * ``bright_yellow``
680 * ``bright_blue``
681 * ``bright_magenta``
682 * ``bright_cyan``
683 * ``bright_white``
684 * ``reset`` (reset the color code only)
686 If the terminal supports it, color may also be specified as:
688 - An integer in the interval [0, 255]. The terminal must support
689 8-bit/256-color mode.
690 - An RGB tuple of three integers in [0, 255]. The terminal must
691 support 24-bit/true-color mode.
693 See https://en.wikipedia.org/wiki/ANSI_color and
694 https://gist.github.com/XVilka/8346728 for more information.
696 :param text: the string to style with ansi codes.
697 :param fg: if provided this will become the foreground color.
698 :param bg: if provided this will become the background color.
699 :param bold: if provided this will enable or disable bold mode.
700 :param dim: if provided this will enable or disable dim mode. This is
701 badly supported.
702 :param underline: if provided this will enable or disable underline.
703 :param overline: if provided this will enable or disable overline.
704 :param italic: if provided this will enable or disable italic.
705 :param blink: if provided this will enable or disable blinking.
706 :param reverse: if provided this will enable or disable inverse
707 rendering (foreground becomes background and the
708 other way round).
709 :param strikethrough: if provided this will enable or disable
710 striking through text.
711 :param reset: by default a reset-all code is added at the end of the
712 string which means that styles do not carry over. This
713 can be disabled to compose styles.
715 .. versionchanged:: 8.5.0
716 All invalid color values raise :exc:`ValueError`. 256-color index
717 ``0`` is no longer ignored.
719 .. versionchanged:: 8.0
720 A non-string ``message`` is converted to a string.
722 .. versionchanged:: 8.0
723 Added support for 256 and RGB color codes.
725 .. versionchanged:: 8.0
726 Added the ``strikethrough``, ``italic``, and ``overline``
727 parameters.
729 .. versionchanged:: 7.0
730 Added support for bright colors.
732 .. versionadded:: 2.0
733 """
734 if not isinstance(text, str):
735 text = str(text)
737 bits = []
739 if fg is not None:
740 bits.append(f"\033[{_interpret_color(fg)}m")
742 if bg is not None:
743 bits.append(f"\033[{_interpret_color(bg, 10)}m")
745 if bold is not None:
746 bits.append(f"\033[{1 if bold else 22}m")
747 if dim is not None:
748 bits.append(f"\033[{2 if dim else 22}m")
749 if underline is not None:
750 bits.append(f"\033[{4 if underline else 24}m")
751 if overline is not None:
752 bits.append(f"\033[{53 if overline else 55}m")
753 if italic is not None:
754 bits.append(f"\033[{3 if italic else 23}m")
755 if blink is not None:
756 bits.append(f"\033[{5 if blink else 25}m")
757 if reverse is not None:
758 bits.append(f"\033[{7 if reverse else 27}m")
759 if strikethrough is not None:
760 bits.append(f"\033[{9 if strikethrough else 29}m")
761 bits.append(text)
762 if reset:
763 bits.append(_ansi_reset_all)
764 return "".join(bits)
767def unstyle(text: str) -> str:
768 """Removes ANSI styling information from a string. Usually it's not
769 necessary to use this function as Click's echo function will
770 automatically remove styling if necessary.
772 .. versionadded:: 2.0
774 :param text: the text to remove style information from.
775 """
776 return strip_ansi(text)
779def secho(
780 message: t.Any | None = None,
781 file: t.IO[t.AnyStr] | None = None,
782 nl: bool = True,
783 err: bool = False,
784 color: bool | None = None,
785 **styles: t.Any,
786) -> None:
787 """This function combines :func:`echo` and :func:`style` into one
788 call. As such the following two calls are the same::
790 click.secho('Hello World!', fg='green')
791 click.echo(click.style('Hello World!', fg='green'))
793 All keyword arguments are forwarded to the underlying functions
794 depending on which one they go with.
796 Non-string types will be converted to :class:`str`. However,
797 :class:`bytes` are passed directly to :meth:`echo` without applying
798 style. If you want to style bytes that represent text, call
799 :meth:`bytes.decode` first.
801 .. versionchanged:: 8.0
802 A non-string ``message`` is converted to a string. Bytes are
803 passed through without style applied.
805 .. versionadded:: 2.0
806 """
807 if message is not None and not isinstance(message, (bytes, bytearray)):
808 message = style(message, **styles)
810 return echo(message, file=file, nl=nl, err=err, color=color)
813@t.overload
814def edit(
815 text: bytes | bytearray,
816 editor: str | None = None,
817 env: cabc.Mapping[str, str] | None = None,
818 require_save: bool = False,
819 extension: str = ".txt",
820) -> bytes | None: ...
823@t.overload
824def edit(
825 text: str,
826 editor: str | None = None,
827 env: cabc.Mapping[str, str] | None = None,
828 require_save: bool = True,
829 extension: str = ".txt",
830) -> str | None: ...
833@t.overload
834def edit(
835 text: None = None,
836 editor: str | None = None,
837 env: cabc.Mapping[str, str] | None = None,
838 require_save: bool = True,
839 extension: str = ".txt",
840 filename: str | cabc.Iterable[str] | None = None,
841) -> None: ...
844def edit(
845 text: str | bytes | bytearray | None = None,
846 editor: str | None = None,
847 env: cabc.Mapping[str, str] | None = None,
848 require_save: bool = True,
849 extension: str = ".txt",
850 filename: str | cabc.Iterable[str] | None = None,
851) -> str | bytes | bytearray | None:
852 r"""Edits the given text in the defined editor. If an editor is given
853 (should be the full path to the executable but the regular operating
854 system search path is used for finding the executable) it overrides
855 the detected editor. Optionally, some environment variables can be
856 used. If the editor is closed without changes, `None` is returned. In
857 case a file is edited directly the return value is always `None` and
858 `require_save` and `extension` are ignored.
860 If the editor cannot be opened a :exc:`UsageError` is raised.
862 Note for Windows: to simplify cross-platform usage, the newlines are
863 automatically converted from POSIX to Windows and vice versa. As such,
864 the message here will have ``\n`` as newline markers.
866 :param text: the text to edit.
867 :param editor: optionally the editor to use. Defaults to automatic
868 detection.
869 :param env: environment variables to forward to the editor.
870 :param require_save: if this is true, then not saving in the editor
871 will make the return value become `None`.
872 :param extension: the extension to tell the editor about. This defaults
873 to `.txt` but changing this might change syntax
874 highlighting.
875 :param filename: if provided it will edit this file instead of the
876 provided text contents. It will not use a temporary
877 file as an indirection in that case. If the editor supports
878 editing multiple files at once, a sequence of files may be
879 passed as well. Invoke `click.file` once per file instead
880 if multiple files cannot be managed at once or editing the
881 files serially is desired.
883 .. versionchanged:: 8.2.0
884 ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str``
885 if the ``editor`` supports editing multiple files at once.
887 """
888 from ._termui_impl import Editor
890 ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
892 if filename is None:
893 return ed.edit(text)
895 if isinstance(filename, str):
896 filename = (filename,)
898 ed.edit_files(filenames=filename)
899 return None
902def launch(url: str, wait: bool = False, locate: bool = False) -> int:
903 """This function launches the given URL (or filename) in the default
904 viewer application for this file type. If this is an executable, it
905 might launch the executable in a new session. The return value is
906 the exit code of the launched application. Usually, ``0`` indicates
907 success.
909 Examples::
911 click.launch('https://click.palletsprojects.com/')
912 click.launch('/my/downloaded/file', locate=True)
914 .. versionadded:: 2.0
916 :param url: URL or filename of the thing to launch.
917 :param wait: Wait for the program to exit before returning. This
918 only works if the launched program blocks. In particular,
919 ``xdg-open`` on Linux does not block.
920 :param locate: if this is set to `True` then instead of launching the
921 application associated with the URL it will attempt to
922 launch a file manager with the file located. This
923 might have weird effects if the URL does not point to
924 the filesystem.
925 """
926 from ._termui_impl import open_url
928 return open_url(url, wait=wait, locate=locate)
931# If this is provided, getchar() calls into this instead. This is used
932# for unittesting purposes.
933_getchar: t.Callable[[bool], str] | None = None
936def getchar(echo: bool = False) -> str:
937 """Fetches a single character from the terminal and returns it. This
938 will always return a unicode character and under certain rare
939 circumstances this might return more than one character. The
940 situations which more than one character is returned is when for
941 whatever reason multiple characters end up in the terminal buffer or
942 standard input was not actually a terminal.
944 Note that this will always read from the terminal, even if something
945 is piped into the standard input.
947 Note for Windows: in rare cases when typing non-ASCII characters, this
948 function might wait for a second character and then return both at once.
949 This is because certain Unicode characters look like special-key markers.
951 .. versionadded:: 2.0
953 :param echo: if set to `True`, the character read will also show up on
954 the terminal. The default is to not show it.
955 """
956 global _getchar
958 if _getchar is None:
959 from ._termui_impl import getchar as f
961 _getchar = f
963 return _getchar(echo)
966def raw_terminal() -> AbstractContextManager[int]:
967 from ._termui_impl import raw_terminal as f
969 return f()
972def pause(info: str | None = None, err: bool = False) -> None:
973 """This command stops execution and waits for the user to press any
974 key to continue. This is similar to the Windows batch "pause"
975 command. If the program is not run through a terminal, this command
976 will instead do nothing.
978 .. versionadded:: 2.0
980 .. versionadded:: 4.0
981 Added the `err` parameter.
983 :param info: The message to print before pausing. Defaults to
984 ``"Press any key to continue..."``.
985 :param err: if set to message goes to ``stderr`` instead of
986 ``stdout``, the same as with echo.
987 """
988 if not isatty(sys.stdin) or not isatty(sys.stdout):
989 return
991 if info is None:
992 info = _("Press any key to continue...")
994 try:
995 if info:
996 echo(info, nl=False, err=err)
997 try:
998 getchar()
999 except (KeyboardInterrupt, EOFError):
1000 pass
1001 finally:
1002 if info:
1003 echo(err=err)