]>
crepu.dev Git - config.git/blob - djavu-asus/emacs/elpy/rpc-venv/lib/python3.11/site-packages/click/termui.py
6 from gettext
import gettext
as _
8 from ._compat
import isatty
9 from ._compat
import strip_ansi
10 from .exceptions
import Abort
11 from .exceptions
import UsageError
12 from .globals import resolve_color_default
13 from .types
import Choice
14 from .types
import convert_type
15 from .types
import ParamType
16 from .utils
import echo
17 from .utils
import LazyFile
20 from ._termui
_impl
import ProgressBar
24 # The prompt functions to use. The doc tools currently override these
25 # functions to customize how they work.
26 visible_prompt_func
: t
.Callable
[[str], str] = input
47 _ansi_reset_all
= "\033[0m"
50 def hidden_prompt_func(prompt
: str) -> str:
53 return getpass
.getpass(prompt
)
59 show_default
: bool = False,
60 default
: t
.Optional
[t
.Any
] = None,
61 show_choices
: bool = True,
62 type: t
.Optional
[ParamType
] = None,
65 if type is not None and show_choices
and isinstance(type, Choice
):
66 prompt
+= f
" ({', '.join(map(str, type.choices))})"
67 if default
is not None and show_default
:
68 prompt
= f
"{prompt} [{_format_default(default)}]"
69 return f
"{prompt}{suffix}"
72 def _format_default(default
: t
.Any
) -> t
.Any
:
73 if isinstance(default
, (io
.IOBase
, LazyFile
)) and hasattr(default
, "name"):
81 default
: t
.Optional
[t
.Any
] = None,
82 hide_input
: bool = False,
83 confirmation_prompt
: t
.Union
[bool, str] = False,
84 type: t
.Optional
[t
.Union
[ParamType
, t
.Any
]] = None,
85 value_proc
: t
.Optional
[t
.Callable
[[str], t
.Any
]] = None,
86 prompt_suffix
: str = ": ",
87 show_default
: bool = True,
89 show_choices
: bool = True,
91 """Prompts a user for input. This is a convenience function that can
92 be used to prompt a user for input later.
94 If the user aborts the input by sending an interrupt signal, this
95 function will catch it and raise a :exc:`Abort` exception.
97 :param text: the text to show for the prompt.
98 :param default: the default value to use if no input happens. If this
99 is not given it will prompt until it's aborted.
100 :param hide_input: if this is set to true then the input value will
102 :param confirmation_prompt: Prompt a second time to confirm the
103 value. Can be set to a string instead of ``True`` to customize
105 :param type: the type to use to check the value against.
106 :param value_proc: if this parameter is provided it's a function that
107 is invoked instead of the type conversion to
109 :param prompt_suffix: a suffix that should be added to the prompt.
110 :param show_default: shows or hides the default value in the prompt.
111 :param err: if set to true the file defaults to ``stderr`` instead of
112 ``stdout``, the same as with echo.
113 :param show_choices: Show or hide choices if the passed type is a Choice.
114 For example if type is a Choice of either day or week,
115 show_choices is true and text is "Group by" then the
116 prompt will be "Group by (day, week): ".
118 .. versionadded:: 8.0
119 ``confirmation_prompt`` can be a custom string.
121 .. versionadded:: 7.0
122 Added the ``show_choices`` parameter.
124 .. versionadded:: 6.0
125 Added unicode support for cmd.exe on Windows.
127 .. versionadded:: 4.0
128 Added the `err` parameter.
132 def prompt_func(text
: str) -> str:
133 f
= hidden_prompt_func
if hide_input
else visible_prompt_func
135 # Write the prompt separately so that we get nice
136 # coloring through colorama on Windows
137 echo(text
.rstrip(" "), nl
=False, err
=err
)
138 # Echo a space to stdout to work around an issue where
139 # readline causes backspace to clear the whole line.
141 except (KeyboardInterrupt, EOFError):
142 # getpass doesn't print a newline if the user aborts input with ^C.
143 # Allegedly this behavior is inherited from getpass(3).
144 # A doc bug has been filed at https://bugs.python.org/issue24711
147 raise Abort() from None
149 if value_proc
is None:
150 value_proc
= convert_type(type, default
)
152 prompt
= _build_prompt(
153 text
, prompt_suffix
, show_default
, default
, show_choices
, type
156 if confirmation_prompt
:
157 if confirmation_prompt
is True:
158 confirmation_prompt
= _("Repeat for confirmation")
160 confirmation_prompt
= _build_prompt(confirmation_prompt
, prompt_suffix
)
164 value
= prompt_func(prompt
)
167 elif default
is not None:
171 result
= value_proc(value
)
172 except UsageError
as e
:
174 echo(_("Error: The value you entered was invalid."), err
=err
)
176 echo(_("Error: {e.message}").format(e
=e
), err
=err
) # noqa: B306
178 if not confirmation_prompt
:
181 value2
= prompt_func(confirmation_prompt
)
182 is_empty
= not value
and not value2
183 if value2
or is_empty
:
187 echo(_("Error: The two entered values do not match."), err
=err
)
192 default
: t
.Optional
[bool] = False,
194 prompt_suffix
: str = ": ",
195 show_default
: bool = True,
198 """Prompts for confirmation (yes/no question).
200 If the user aborts the input by sending a interrupt signal this
201 function will catch it and raise a :exc:`Abort` exception.
203 :param text: the question to ask.
204 :param default: The default value to use when no input is given. If
205 ``None``, repeat until input is given.
206 :param abort: if this is set to `True` a negative answer aborts the
207 exception by raising :exc:`Abort`.
208 :param prompt_suffix: a suffix that should be added to the prompt.
209 :param show_default: shows or hides the default value in the prompt.
210 :param err: if set to true the file defaults to ``stderr`` instead of
211 ``stdout``, the same as with echo.
213 .. versionchanged:: 8.0
214 Repeat until input is given if ``default`` is ``None``.
216 .. versionadded:: 4.0
217 Added the ``err`` parameter.
219 prompt
= _build_prompt(
223 "y/n" if default
is None else ("Y/n" if default
else "y/N"),
228 # Write the prompt separately so that we get nice
229 # coloring through colorama on Windows
230 echo(prompt
.rstrip(" "), nl
=False, err
=err
)
231 # Echo a space to stdout to work around an issue where
232 # readline causes backspace to clear the whole line.
233 value
= visible_prompt_func(" ").lower().strip()
234 except (KeyboardInterrupt, EOFError):
235 raise Abort() from None
236 if value
in ("y", "yes"):
238 elif value
in ("n", "no"):
240 elif default
is not None and value
== "":
243 echo(_("Error: invalid input"), err
=err
)
252 text_or_generator
: t
.Union
[t
.Iterable
[str], t
.Callable
[[], t
.Iterable
[str]], str],
253 color
: t
.Optional
[bool] = None,
255 """This function takes a text and shows it via an environment specific
258 .. versionchanged:: 3.0
259 Added the `color` flag.
261 :param text_or_generator: the text to page, or alternatively, a
262 generator emitting the text to page.
263 :param color: controls if the pager supports ANSI colors or not. The
264 default is autodetection.
266 color
= resolve_color_default(color
)
268 if inspect
.isgeneratorfunction(text_or_generator
):
269 i
= t
.cast(t
.Callable
[[], t
.Iterable
[str]], text_or_generator
)()
270 elif isinstance(text_or_generator
, str):
271 i
= [text_or_generator
]
273 i
= iter(t
.cast(t
.Iterable
[str], text_or_generator
))
275 # convert every element of i to a text type if necessary
276 text_generator
= (el
if isinstance(el
, str) else str(el
) for el
in i
)
278 from ._termui
_impl
import pager
280 return pager(itertools
.chain(text_generator
, "\n"), color
)
284 iterable
: t
.Optional
[t
.Iterable
[V
]] = None,
285 length
: t
.Optional
[int] = None,
286 label
: t
.Optional
[str] = None,
287 show_eta
: bool = True,
288 show_percent
: t
.Optional
[bool] = None,
289 show_pos
: bool = False,
290 item_show_func
: t
.Optional
[t
.Callable
[[t
.Optional
[V
]], t
.Optional
[str]]] = None,
291 fill_char
: str = "#",
292 empty_char
: str = "-",
293 bar_template
: str = "%(label)s [%(bar)s] %(info)s",
296 file: t
.Optional
[t
.TextIO
] = None,
297 color
: t
.Optional
[bool] = None,
298 update_min_steps
: int = 1,
299 ) -> "ProgressBar[V]":
300 """This function creates an iterable context manager that can be used
301 to iterate over something while showing a progress bar. It will
302 either iterate over the `iterable` or `length` items (that are counted
303 up). While iteration happens, this function will print a rendered
304 progress bar to the given `file` (defaults to stdout) and will attempt
305 to calculate remaining time and more. By default, this progress bar
306 will not be rendered if the file is not a terminal.
308 The context manager creates the progress bar. When the context
309 manager is entered the progress bar is already created. With every
310 iteration over the progress bar, the iterable passed to the bar is
311 advanced and the bar is updated. When the context manager exits,
312 a newline is printed and the progress bar is finalized on screen.
314 Note: The progress bar is currently designed for use cases where the
315 total progress can be expected to take at least several seconds.
316 Because of this, the ProgressBar class object won't display
317 progress that is considered too fast, and progress where the time
318 between steps is less than a second.
320 No printing must happen or the progress bar will be unintentionally
325 with progressbar(items) as bar:
327 do_something_with(item)
329 Alternatively, if no iterable is specified, one can manually update the
330 progress bar through the `update()` method instead of directly
331 iterating over the progress bar. The update method accepts the number
332 of steps to increment the bar with::
334 with progressbar(length=chunks.total_bytes) as bar:
337 bar.update(chunks.bytes)
339 The ``update()`` method also takes an optional value specifying the
340 ``current_item`` at the new position. This is useful when used
341 together with ``item_show_func`` to customize the output for each
344 with click.progressbar(
346 label='Unzipping archive',
347 item_show_func=lambda a: a.filename
349 for archive in zip_file:
351 bar.update(archive.size, archive)
353 :param iterable: an iterable to iterate over. If not provided the length
355 :param length: the number of items to iterate over. By default the
356 progressbar will attempt to ask the iterator about its
357 length, which might or might not work. If an iterable is
358 also provided this parameter can be used to override the
359 length. If an iterable is not provided the progress bar
360 will iterate over a range of that length.
361 :param label: the label to show next to the progress bar.
362 :param show_eta: enables or disables the estimated time display. This is
363 automatically disabled if the length cannot be
365 :param show_percent: enables or disables the percentage display. The
366 default is `True` if the iterable has a length or
368 :param show_pos: enables or disables the absolute position display. The
370 :param item_show_func: A function called with the current item which
371 can return a string to show next to the progress bar. If the
372 function returns ``None`` nothing is shown. The current item can
373 be ``None``, such as when entering and exiting the bar.
374 :param fill_char: the character to use to show the filled part of the
376 :param empty_char: the character to use to show the non-filled part of
378 :param bar_template: the format string to use as template for the bar.
379 The parameters in it are ``label`` for the label,
380 ``bar`` for the progress bar and ``info`` for the
382 :param info_sep: the separator between multiple info items (eta etc.)
383 :param width: the width of the progress bar in characters, 0 means full
385 :param file: The file to write to. If this is not a terminal then
386 only the label is printed.
387 :param color: controls if the terminal supports ANSI colors or not. The
388 default is autodetection. This is only needed if ANSI
389 codes are included anywhere in the progress bar output
390 which is not the case by default.
391 :param update_min_steps: Render only when this many updates have
392 completed. This allows tuning for very fast iterators.
394 .. versionchanged:: 8.0
395 Output is shown even if execution time is less than 0.5 seconds.
397 .. versionchanged:: 8.0
398 ``item_show_func`` shows the current item, not the previous one.
400 .. versionchanged:: 8.0
401 Labels are echoed if the output is not a TTY. Reverts a change
402 in 7.0 that removed all output.
404 .. versionadded:: 8.0
405 Added the ``update_min_steps`` parameter.
407 .. versionchanged:: 4.0
408 Added the ``color`` parameter. Added the ``update`` method to
411 .. versionadded:: 2.0
413 from ._termui
_impl
import ProgressBar
415 color
= resolve_color_default(color
)
420 show_percent
=show_percent
,
422 item_show_func
=item_show_func
,
424 empty_char
=empty_char
,
425 bar_template
=bar_template
,
431 update_min_steps
=update_min_steps
,
436 """Clears the terminal screen. This will have the effect of clearing
437 the whole visible space of the terminal and moving the cursor to the
438 top left. This does not do anything if not connected to a terminal.
440 .. versionadded:: 2.0
442 if not isatty(sys
.stdout
):
445 # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor
446 echo("\033[2J\033[1;1H", nl
=False)
449 def _interpret_color(
450 color
: t
.Union
[int, t
.Tuple
[int, int, int], str], offset
: int = 0
452 if isinstance(color
, int):
453 return f
"{38 + offset};5;{color:d}"
455 if isinstance(color
, (tuple, list)):
457 return f
"{38 + offset};2;{r:d};{g:d};{b:d}"
459 return str(_ansi_colors
[color
] + offset
)
464 fg
: t
.Optional
[t
.Union
[int, t
.Tuple
[int, int, int], str]] = None,
465 bg
: t
.Optional
[t
.Union
[int, t
.Tuple
[int, int, int], str]] = None,
466 bold
: t
.Optional
[bool] = None,
467 dim
: t
.Optional
[bool] = None,
468 underline
: t
.Optional
[bool] = None,
469 overline
: t
.Optional
[bool] = None,
470 italic
: t
.Optional
[bool] = None,
471 blink
: t
.Optional
[bool] = None,
472 reverse
: t
.Optional
[bool] = None,
473 strikethrough
: t
.Optional
[bool] = None,
476 """Styles a text with ANSI styles and returns the new string. By
477 default the styling is self contained which means that at the end
478 of the string a reset code is issued. This can be prevented by
479 passing ``reset=False``.
483 click.echo(click.style('Hello World!', fg='green'))
484 click.echo(click.style('ATTENTION!', blink=True))
485 click.echo(click.style('Some things', reverse=True, fg='cyan'))
486 click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
488 Supported color names:
490 * ``black`` (might be a gray)
493 * ``yellow`` (might be an orange)
497 * ``white`` (might be light gray)
506 * ``reset`` (reset the color code only)
508 If the terminal supports it, color may also be specified as:
510 - An integer in the interval [0, 255]. The terminal must support
511 8-bit/256-color mode.
512 - An RGB tuple of three integers in [0, 255]. The terminal must
513 support 24-bit/true-color mode.
515 See https://en.wikipedia.org/wiki/ANSI_color and
516 https://gist.github.com/XVilka/8346728 for more information.
518 :param text: the string to style with ansi codes.
519 :param fg: if provided this will become the foreground color.
520 :param bg: if provided this will become the background color.
521 :param bold: if provided this will enable or disable bold mode.
522 :param dim: if provided this will enable or disable dim mode. This is
524 :param underline: if provided this will enable or disable underline.
525 :param overline: if provided this will enable or disable overline.
526 :param italic: if provided this will enable or disable italic.
527 :param blink: if provided this will enable or disable blinking.
528 :param reverse: if provided this will enable or disable inverse
529 rendering (foreground becomes background and the
531 :param strikethrough: if provided this will enable or disable
532 striking through text.
533 :param reset: by default a reset-all code is added at the end of the
534 string which means that styles do not carry over. This
535 can be disabled to compose styles.
537 .. versionchanged:: 8.0
538 A non-string ``message`` is converted to a string.
540 .. versionchanged:: 8.0
541 Added support for 256 and RGB color codes.
543 .. versionchanged:: 8.0
544 Added the ``strikethrough``, ``italic``, and ``overline``
547 .. versionchanged:: 7.0
548 Added support for bright colors.
550 .. versionadded:: 2.0
552 if not isinstance(text
, str):
559 bits
.append(f
"\033[{_interpret_color(fg)}m")
561 raise TypeError(f
"Unknown color {fg!r}") from None
565 bits
.append(f
"\033[{_interpret_color(bg, 10)}m")
567 raise TypeError(f
"Unknown color {bg!r}") from None
570 bits
.append(f
"\033[{1 if bold else 22}m")
572 bits
.append(f
"\033[{2 if dim else 22}m")
573 if underline
is not None:
574 bits
.append(f
"\033[{4 if underline else 24}m")
575 if overline
is not None:
576 bits
.append(f
"\033[{53 if overline else 55}m")
577 if italic
is not None:
578 bits
.append(f
"\033[{3 if italic else 23}m")
579 if blink
is not None:
580 bits
.append(f
"\033[{5 if blink else 25}m")
581 if reverse
is not None:
582 bits
.append(f
"\033[{7 if reverse else 27}m")
583 if strikethrough
is not None:
584 bits
.append(f
"\033[{9 if strikethrough else 29}m")
587 bits
.append(_ansi_reset_all
)
591 def unstyle(text
: str) -> str:
592 """Removes ANSI styling information from a string. Usually it's not
593 necessary to use this function as Click's echo function will
594 automatically remove styling if necessary.
596 .. versionadded:: 2.0
598 :param text: the text to remove style information from.
600 return strip_ansi(text
)
604 message
: t
.Optional
[t
.Any
] = None,
605 file: t
.Optional
[t
.IO
[t
.AnyStr
]] = None,
608 color
: t
.Optional
[bool] = None,
611 """This function combines :func:`echo` and :func:`style` into one
612 call. As such the following two calls are the same::
614 click.secho('Hello World!', fg='green')
615 click.echo(click.style('Hello World!', fg='green'))
617 All keyword arguments are forwarded to the underlying functions
618 depending on which one they go with.
620 Non-string types will be converted to :class:`str`. However,
621 :class:`bytes` are passed directly to :meth:`echo` without applying
622 style. If you want to style bytes that represent text, call
623 :meth:`bytes.decode` first.
625 .. versionchanged:: 8.0
626 A non-string ``message`` is converted to a string. Bytes are
627 passed through without style applied.
629 .. versionadded:: 2.0
631 if message
is not None and not isinstance(message
, (bytes
, bytearray
)):
632 message
= style(message
, **styles
)
634 return echo(message
, file=file, nl
=nl
, err
=err
, color
=color
)
638 text
: t
.Optional
[t
.AnyStr
] = None,
639 editor
: t
.Optional
[str] = None,
640 env
: t
.Optional
[t
.Mapping
[str, str]] = None,
641 require_save
: bool = True,
642 extension
: str = ".txt",
643 filename
: t
.Optional
[str] = None,
644 ) -> t
.Optional
[t
.AnyStr
]:
645 r
"""Edits the given text in the defined editor. If an editor is given
646 (should be the full path to the executable but the regular operating
647 system search path is used for finding the executable) it overrides
648 the detected editor. Optionally, some environment variables can be
649 used. If the editor is closed without changes, `None` is returned. In
650 case a file is edited directly the return value is always `None` and
651 `require_save` and `extension` are ignored.
653 If the editor cannot be opened a :exc:`UsageError` is raised.
655 Note for Windows: to simplify cross-platform usage, the newlines are
656 automatically converted from POSIX to Windows and vice versa. As such,
657 the message here will have ``\n`` as newline markers.
659 :param text: the text to edit.
660 :param editor: optionally the editor to use. Defaults to automatic
662 :param env: environment variables to forward to the editor.
663 :param require_save: if this is true, then not saving in the editor
664 will make the return value become `None`.
665 :param extension: the extension to tell the editor about. This defaults
666 to `.txt` but changing this might change syntax
668 :param filename: if provided it will edit this file instead of the
669 provided text contents. It will not use a temporary
670 file as an indirection in that case.
672 from ._termui
_impl
import Editor
674 ed
= Editor(editor
=editor
, env
=env
, require_save
=require_save
, extension
=extension
)
679 ed
.edit_file(filename
)
683 def launch(url
: str, wait
: bool = False, locate
: bool = False) -> int:
684 """This function launches the given URL (or filename) in the default
685 viewer application for this file type. If this is an executable, it
686 might launch the executable in a new session. The return value is
687 the exit code of the launched application. Usually, ``0`` indicates
692 click.launch('https://click.palletsprojects.com/')
693 click.launch('/my/downloaded/file', locate=True)
695 .. versionadded:: 2.0
697 :param url: URL or filename of the thing to launch.
698 :param wait: Wait for the program to exit before returning. This
699 only works if the launched program blocks. In particular,
700 ``xdg-open`` on Linux does not block.
701 :param locate: if this is set to `True` then instead of launching the
702 application associated with the URL it will attempt to
703 launch a file manager with the file located. This
704 might have weird effects if the URL does not point to
707 from ._termui
_impl
import open_url
709 return open_url(url
, wait
=wait
, locate
=locate
)
712 # If this is provided, getchar() calls into this instead. This is used
713 # for unittesting purposes.
714 _getchar
: t
.Optional
[t
.Callable
[[bool], str]] = None
717 def getchar(echo
: bool = False) -> str:
718 """Fetches a single character from the terminal and returns it. This
719 will always return a unicode character and under certain rare
720 circumstances this might return more than one character. The
721 situations which more than one character is returned is when for
722 whatever reason multiple characters end up in the terminal buffer or
723 standard input was not actually a terminal.
725 Note that this will always read from the terminal, even if something
726 is piped into the standard input.
728 Note for Windows: in rare cases when typing non-ASCII characters, this
729 function might wait for a second character and then return both at once.
730 This is because certain Unicode characters look like special-key markers.
732 .. versionadded:: 2.0
734 :param echo: if set to `True`, the character read will also show up on
735 the terminal. The default is to not show it.
740 from ._termui
_impl
import getchar
as f
744 return _getchar(echo
)
747 def raw_terminal() -> t
.ContextManager
[int]:
748 from ._termui
_impl
import raw_terminal
as f
753 def pause(info
: t
.Optional
[str] = None, err
: bool = False) -> None:
754 """This command stops execution and waits for the user to press any
755 key to continue. This is similar to the Windows batch "pause"
756 command. If the program is not run through a terminal, this command
757 will instead do nothing.
759 .. versionadded:: 2.0
761 .. versionadded:: 4.0
762 Added the `err` parameter.
764 :param info: The message to print before pausing. Defaults to
765 ``"Press any key to continue..."``.
766 :param err: if set to message goes to ``stderr`` instead of
767 ``stdout``, the same as with echo.
769 if not isatty(sys
.stdin
) or not isatty(sys
.stdout
):
773 info
= _("Press any key to continue...")
777 echo(info
, nl
=False, err
=err
)
780 except (KeyboardInterrupt, EOFError):