|
|
|
|
@ -9,6 +9,7 @@ import typing as t
|
|
|
|
|
from contextlib import AbstractContextManager
|
|
|
|
|
from gettext import gettext as _
|
|
|
|
|
|
|
|
|
|
# _compat 模块处理 Python 版本兼容性和跨平台终端差异(如 Windows)
|
|
|
|
|
from ._compat import isatty
|
|
|
|
|
from ._compat import strip_ansi
|
|
|
|
|
from .exceptions import Abort
|
|
|
|
|
@ -25,10 +26,12 @@ if t.TYPE_CHECKING:
|
|
|
|
|
|
|
|
|
|
V = t.TypeVar("V")
|
|
|
|
|
|
|
|
|
|
# The prompt functions to use. The doc tools currently override these
|
|
|
|
|
# functions to customize how they work.
|
|
|
|
|
# 定义默认的输入函数。文档工具可能会覆盖这些函数以进行测试。
|
|
|
|
|
# visible_prompt_func 通常就是 Python 内置的 input()
|
|
|
|
|
visible_prompt_func: t.Callable[[str], str] = input
|
|
|
|
|
|
|
|
|
|
# ANSI 颜色代码映射表 (标准 16 色)
|
|
|
|
|
# 这些数字对应 ANSI 转义序列中的颜色代码
|
|
|
|
|
_ansi_colors = {
|
|
|
|
|
"black": 30,
|
|
|
|
|
"red": 31,
|
|
|
|
|
@ -52,6 +55,10 @@ _ansi_reset_all = "\033[0m"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def hidden_prompt_func(prompt: str) -> str:
|
|
|
|
|
"""
|
|
|
|
|
隐藏输入的提示函数,主要用于密码输入。
|
|
|
|
|
使用 getpass 标准库实现,输入时终端不会回显字符。
|
|
|
|
|
"""
|
|
|
|
|
import getpass
|
|
|
|
|
|
|
|
|
|
return getpass.getpass(prompt)
|
|
|
|
|
@ -65,15 +72,29 @@ def _build_prompt(
|
|
|
|
|
show_choices: bool = True,
|
|
|
|
|
type: ParamType | None = None,
|
|
|
|
|
) -> str:
|
|
|
|
|
"""
|
|
|
|
|
[内部辅助函数] 构建完整的提示字符串。
|
|
|
|
|
|
|
|
|
|
格式通常为: "Prompt Text (choice1, choice2) [default_value]: "
|
|
|
|
|
"""
|
|
|
|
|
prompt = text
|
|
|
|
|
# 如果类型是 Choice (选项),且允许显示选项,则把 (a, b, c) 追加到提示语后
|
|
|
|
|
if type is not None and show_choices and isinstance(type, Choice):
|
|
|
|
|
prompt += f" ({', '.join(map(str, type.choices))})"
|
|
|
|
|
|
|
|
|
|
# 如果有默认值且允许显示,追加 [default]
|
|
|
|
|
if default is not None and show_default:
|
|
|
|
|
prompt = f"{prompt} [{_format_default(default)}]"
|
|
|
|
|
|
|
|
|
|
# 最后加上后缀(通常是 ": ")
|
|
|
|
|
return f"{prompt}{suffix}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _format_default(default: t.Any) -> t.Any:
|
|
|
|
|
"""
|
|
|
|
|
格式化默认值以便显示。
|
|
|
|
|
如果是文件对象,显示文件名而不是对象本身。
|
|
|
|
|
"""
|
|
|
|
|
if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):
|
|
|
|
|
return default.name
|
|
|
|
|
|
|
|
|
|
@ -92,98 +113,77 @@ def prompt(
|
|
|
|
|
err: bool = False,
|
|
|
|
|
show_choices: bool = True,
|
|
|
|
|
) -> t.Any:
|
|
|
|
|
"""Prompts a user for input. This is a convenience function that can
|
|
|
|
|
be used to prompt a user for input later.
|
|
|
|
|
|
|
|
|
|
If the user aborts the input by sending an interrupt signal, this
|
|
|
|
|
function will catch it and raise a :exc:`Abort` exception.
|
|
|
|
|
|
|
|
|
|
:param text: the text to show for the prompt.
|
|
|
|
|
:param default: the default value to use if no input happens. If this
|
|
|
|
|
is not given it will prompt until it's aborted.
|
|
|
|
|
:param hide_input: if this is set to true then the input value will
|
|
|
|
|
be hidden.
|
|
|
|
|
:param confirmation_prompt: Prompt a second time to confirm the
|
|
|
|
|
value. Can be set to a string instead of ``True`` to customize
|
|
|
|
|
the message.
|
|
|
|
|
:param type: the type to use to check the value against.
|
|
|
|
|
:param value_proc: if this parameter is provided it's a function that
|
|
|
|
|
is invoked instead of the type conversion to
|
|
|
|
|
convert a value.
|
|
|
|
|
:param prompt_suffix: a suffix that should be added to the prompt.
|
|
|
|
|
:param show_default: shows or hides the default value in the prompt.
|
|
|
|
|
:param err: if set to true the file defaults to ``stderr`` instead of
|
|
|
|
|
``stdout``, the same as with echo.
|
|
|
|
|
:param show_choices: Show or hide choices if the passed type is a Choice.
|
|
|
|
|
For example if type is a Choice of either day or week,
|
|
|
|
|
show_choices is true and text is "Group by" then the
|
|
|
|
|
prompt will be "Group by (day, week): ".
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.3.1
|
|
|
|
|
A space is no longer appended to the prompt.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 8.0
|
|
|
|
|
``confirmation_prompt`` can be a custom string.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 7.0
|
|
|
|
|
Added the ``show_choices`` parameter.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 6.0
|
|
|
|
|
Added unicode support for cmd.exe on Windows.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 4.0
|
|
|
|
|
Added the `err` parameter.
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
[核心功能] 请求用户输入。
|
|
|
|
|
|
|
|
|
|
这是一个强大的 input() 替代品:
|
|
|
|
|
1. 支持自动类型转换 (type 参数)。
|
|
|
|
|
2. 支持输入校验,失败会自动重试。
|
|
|
|
|
3. 支持密码模式 (hide_input)。
|
|
|
|
|
4. 支持二次确认 (confirmation_prompt)。
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def prompt_func(text: str) -> str:
|
|
|
|
|
"""
|
|
|
|
|
实际执行输入的闭包函数。
|
|
|
|
|
处理了 Ctrl+C (KeyboardInterrupt) 和 EOF,将其转换为 Click 的 Abort 异常。
|
|
|
|
|
"""
|
|
|
|
|
f = hidden_prompt_func if hide_input else visible_prompt_func
|
|
|
|
|
try:
|
|
|
|
|
# Write the prompt separately so that we get nice
|
|
|
|
|
# coloring through colorama on Windows
|
|
|
|
|
# 分开打印提示语和读取输入。
|
|
|
|
|
# 这样做是为了在 Windows 上通过 colorama 获得更好的颜色支持。
|
|
|
|
|
echo(text[:-1], nl=False, err=err)
|
|
|
|
|
# Echo the last character to stdout to work around an issue where
|
|
|
|
|
# readline causes backspace to clear the whole line.
|
|
|
|
|
# 打印最后一个字符并等待输入
|
|
|
|
|
return f(text[-1:])
|
|
|
|
|
except (KeyboardInterrupt, EOFError):
|
|
|
|
|
# getpass doesn't print a newline if the user aborts input with ^C.
|
|
|
|
|
# Allegedly this behavior is inherited from getpass(3).
|
|
|
|
|
# A doc bug has been filed at https://bugs.python.org/issue24711
|
|
|
|
|
# getpass 在用户按 Ctrl+C 时不会打印换行,这里补一个
|
|
|
|
|
if hide_input:
|
|
|
|
|
echo(None, err=err)
|
|
|
|
|
# 抛出 Abort 异常,Click 的主循环会捕获它并优雅退出,而不是打印 Traceback
|
|
|
|
|
raise Abort() from None
|
|
|
|
|
|
|
|
|
|
# 如果没有提供自定义的值处理函数,则使用 Click 类型系统的转换器
|
|
|
|
|
if value_proc is None:
|
|
|
|
|
value_proc = convert_type(type, default)
|
|
|
|
|
|
|
|
|
|
# 构建提示语
|
|
|
|
|
prompt = _build_prompt(
|
|
|
|
|
text, prompt_suffix, show_default, default, show_choices, type
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# 处理二次确认的提示语(例如 "Repeat for confirmation: ")
|
|
|
|
|
if confirmation_prompt:
|
|
|
|
|
if confirmation_prompt is True:
|
|
|
|
|
confirmation_prompt = _("Repeat for confirmation")
|
|
|
|
|
|
|
|
|
|
confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
|
|
|
|
|
|
|
|
|
|
# 主循环:不断请求输入,直到获得有效值
|
|
|
|
|
while True:
|
|
|
|
|
while True:
|
|
|
|
|
value = prompt_func(prompt)
|
|
|
|
|
if value:
|
|
|
|
|
break
|
|
|
|
|
# 如果用户直接回车 (value为空) 且有默认值,则使用默认值
|
|
|
|
|
elif default is not None:
|
|
|
|
|
value = default
|
|
|
|
|
break
|
|
|
|
|
try:
|
|
|
|
|
# 尝试转换类型 (例如 str -> int)
|
|
|
|
|
result = value_proc(value)
|
|
|
|
|
except UsageError as e:
|
|
|
|
|
# 如果转换失败(例如用户输入 "abc" 但要求 int),打印错误信息并继续循环
|
|
|
|
|
if hide_input:
|
|
|
|
|
echo(_("Error: The value you entered was invalid."), err=err)
|
|
|
|
|
else:
|
|
|
|
|
echo(_("Error: {e.message}").format(e=e), err=err)
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# 如果不需要二次确认,直接返回结果
|
|
|
|
|
if not confirmation_prompt:
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
# 二次确认逻辑
|
|
|
|
|
while True:
|
|
|
|
|
value2 = prompt_func(confirmation_prompt)
|
|
|
|
|
is_empty = not value and not value2
|
|
|
|
|
@ -202,47 +202,28 @@ def confirm(
|
|
|
|
|
show_default: bool = True,
|
|
|
|
|
err: bool = False,
|
|
|
|
|
) -> bool:
|
|
|
|
|
"""Prompts for confirmation (yes/no question).
|
|
|
|
|
|
|
|
|
|
If the user aborts the input by sending a interrupt signal this
|
|
|
|
|
function will catch it and raise a :exc:`Abort` exception.
|
|
|
|
|
|
|
|
|
|
:param text: the question to ask.
|
|
|
|
|
:param default: The default value to use when no input is given. If
|
|
|
|
|
``None``, repeat until input is given.
|
|
|
|
|
:param abort: if this is set to `True` a negative answer aborts the
|
|
|
|
|
exception by raising :exc:`Abort`.
|
|
|
|
|
:param prompt_suffix: a suffix that should be added to the prompt.
|
|
|
|
|
:param show_default: shows or hides the default value in the prompt.
|
|
|
|
|
:param err: if set to true the file defaults to ``stderr`` instead of
|
|
|
|
|
``stdout``, the same as with echo.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.3.1
|
|
|
|
|
A space is no longer appended to the prompt.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.0
|
|
|
|
|
Repeat until input is given if ``default`` is ``None``.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 4.0
|
|
|
|
|
Added the ``err`` parameter.
|
|
|
|
|
"""
|
|
|
|
|
[核心功能] 请求用户确认 (Yes/No)。
|
|
|
|
|
|
|
|
|
|
:param default: 默认值。如果为 None,则强制用户必须输入 y 或 n。
|
|
|
|
|
:param abort: 如果为 True,当用户选择 No 时,直接抛出 Abort 异常终止程序。
|
|
|
|
|
"""
|
|
|
|
|
prompt = _build_prompt(
|
|
|
|
|
text,
|
|
|
|
|
prompt_suffix,
|
|
|
|
|
show_default,
|
|
|
|
|
# 根据默认值决定显示 [Y/n], [y/N] 还是 [y/n]
|
|
|
|
|
"y/n" if default is None else ("Y/n" if default else "y/N"),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
while True:
|
|
|
|
|
try:
|
|
|
|
|
# Write the prompt separately so that we get nice
|
|
|
|
|
# coloring through colorama on Windows
|
|
|
|
|
echo(prompt[:-1], nl=False, err=err)
|
|
|
|
|
# Echo the last character to stdout to work around an issue where
|
|
|
|
|
# readline causes backspace to clear the whole line.
|
|
|
|
|
value = visible_prompt_func(prompt[-1:]).lower().strip()
|
|
|
|
|
except (KeyboardInterrupt, EOFError):
|
|
|
|
|
raise Abort() from None
|
|
|
|
|
|
|
|
|
|
# 判断输入
|
|
|
|
|
if value in ("y", "yes"):
|
|
|
|
|
rv = True
|
|
|
|
|
elif value in ("n", "no"):
|
|
|
|
|
@ -253,6 +234,8 @@ def confirm(
|
|
|
|
|
echo(_("Error: invalid input"), err=err)
|
|
|
|
|
continue
|
|
|
|
|
break
|
|
|
|
|
|
|
|
|
|
# 如果设置了 abort=True 且结果为 False,则抛出异常
|
|
|
|
|
if abort and not rv:
|
|
|
|
|
raise Abort()
|
|
|
|
|
return rv
|
|
|
|
|
@ -262,19 +245,12 @@ def echo_via_pager(
|
|
|
|
|
text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,
|
|
|
|
|
color: bool | None = None,
|
|
|
|
|
) -> None:
|
|
|
|
|
"""This function takes a text and shows it via an environment specific
|
|
|
|
|
pager on stdout.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 3.0
|
|
|
|
|
Added the `color` flag.
|
|
|
|
|
|
|
|
|
|
:param text_or_generator: the text to page, or alternatively, a
|
|
|
|
|
generator emitting the text to page.
|
|
|
|
|
:param color: controls if the pager supports ANSI colors or not. The
|
|
|
|
|
default is autodetection.
|
|
|
|
|
"""
|
|
|
|
|
[UI工具] 调用系统分页器 (Pager, 如 less 或 more) 显示长文本。
|
|
|
|
|
"""
|
|
|
|
|
color = resolve_color_default(color)
|
|
|
|
|
|
|
|
|
|
# 处理输入:支持生成器、字符串或迭代器
|
|
|
|
|
if inspect.isgeneratorfunction(text_or_generator):
|
|
|
|
|
i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()
|
|
|
|
|
elif isinstance(text_or_generator, str):
|
|
|
|
|
@ -282,14 +258,16 @@ def echo_via_pager(
|
|
|
|
|
else:
|
|
|
|
|
i = iter(t.cast("cabc.Iterable[str]", text_or_generator))
|
|
|
|
|
|
|
|
|
|
# convert every element of i to a text type if necessary
|
|
|
|
|
# 确保所有元素都是字符串
|
|
|
|
|
text_generator = (el if isinstance(el, str) else str(el) for el in i)
|
|
|
|
|
|
|
|
|
|
from ._termui_impl import pager
|
|
|
|
|
|
|
|
|
|
# 将生成器链接起来并传递给底层 pager 实现
|
|
|
|
|
return pager(itertools.chain(text_generator, "\n"), color)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 定义 progressbar 的类型重载,用于 IDE 智能提示
|
|
|
|
|
@t.overload
|
|
|
|
|
def progressbar(
|
|
|
|
|
*,
|
|
|
|
|
@ -349,123 +327,16 @@ def progressbar(
|
|
|
|
|
color: bool | None = None,
|
|
|
|
|
update_min_steps: int = 1,
|
|
|
|
|
) -> ProgressBar[V]:
|
|
|
|
|
"""This function creates an iterable context manager that can be used
|
|
|
|
|
to iterate over something while showing a progress bar. It will
|
|
|
|
|
either iterate over the `iterable` or `length` items (that are counted
|
|
|
|
|
up). While iteration happens, this function will print a rendered
|
|
|
|
|
progress bar to the given `file` (defaults to stdout) and will attempt
|
|
|
|
|
to calculate remaining time and more. By default, this progress bar
|
|
|
|
|
will not be rendered if the file is not a terminal.
|
|
|
|
|
|
|
|
|
|
The context manager creates the progress bar. When the context
|
|
|
|
|
manager is entered the progress bar is already created. With every
|
|
|
|
|
iteration over the progress bar, the iterable passed to the bar is
|
|
|
|
|
advanced and the bar is updated. When the context manager exits,
|
|
|
|
|
a newline is printed and the progress bar is finalized on screen.
|
|
|
|
|
|
|
|
|
|
Note: The progress bar is currently designed for use cases where the
|
|
|
|
|
total progress can be expected to take at least several seconds.
|
|
|
|
|
Because of this, the ProgressBar class object won't display
|
|
|
|
|
progress that is considered too fast, and progress where the time
|
|
|
|
|
between steps is less than a second.
|
|
|
|
|
|
|
|
|
|
No printing must happen or the progress bar will be unintentionally
|
|
|
|
|
destroyed.
|
|
|
|
|
|
|
|
|
|
Example usage::
|
|
|
|
|
|
|
|
|
|
with progressbar(items) as bar:
|
|
|
|
|
for item in bar:
|
|
|
|
|
do_something_with(item)
|
|
|
|
|
|
|
|
|
|
Alternatively, if no iterable is specified, one can manually update the
|
|
|
|
|
progress bar through the `update()` method instead of directly
|
|
|
|
|
iterating over the progress bar. The update method accepts the number
|
|
|
|
|
of steps to increment the bar with::
|
|
|
|
|
|
|
|
|
|
with progressbar(length=chunks.total_bytes) as bar:
|
|
|
|
|
for chunk in chunks:
|
|
|
|
|
process_chunk(chunk)
|
|
|
|
|
bar.update(chunks.bytes)
|
|
|
|
|
|
|
|
|
|
The ``update()`` method also takes an optional value specifying the
|
|
|
|
|
``current_item`` at the new position. This is useful when used
|
|
|
|
|
together with ``item_show_func`` to customize the output for each
|
|
|
|
|
manual step::
|
|
|
|
|
|
|
|
|
|
with click.progressbar(
|
|
|
|
|
length=total_size,
|
|
|
|
|
label='Unzipping archive',
|
|
|
|
|
item_show_func=lambda a: a.filename
|
|
|
|
|
) as bar:
|
|
|
|
|
for archive in zip_file:
|
|
|
|
|
archive.extract()
|
|
|
|
|
bar.update(archive.size, archive)
|
|
|
|
|
|
|
|
|
|
:param iterable: an iterable to iterate over. If not provided the length
|
|
|
|
|
is required.
|
|
|
|
|
:param length: the number of items to iterate over. By default the
|
|
|
|
|
progressbar will attempt to ask the iterator about its
|
|
|
|
|
length, which might or might not work. If an iterable is
|
|
|
|
|
also provided this parameter can be used to override the
|
|
|
|
|
length. If an iterable is not provided the progress bar
|
|
|
|
|
will iterate over a range of that length.
|
|
|
|
|
:param label: the label to show next to the progress bar.
|
|
|
|
|
:param hidden: hide the progressbar. Defaults to ``False``. When no tty is
|
|
|
|
|
detected, it will only print the progressbar label. Setting this to
|
|
|
|
|
``False`` also disables that.
|
|
|
|
|
:param show_eta: enables or disables the estimated time display. This is
|
|
|
|
|
automatically disabled if the length cannot be
|
|
|
|
|
determined.
|
|
|
|
|
:param show_percent: enables or disables the percentage display. The
|
|
|
|
|
default is `True` if the iterable has a length or
|
|
|
|
|
`False` if not.
|
|
|
|
|
:param show_pos: enables or disables the absolute position display. The
|
|
|
|
|
default is `False`.
|
|
|
|
|
:param item_show_func: A function called with the current item which
|
|
|
|
|
can return a string to show next to the progress bar. If the
|
|
|
|
|
function returns ``None`` nothing is shown. The current item can
|
|
|
|
|
be ``None``, such as when entering and exiting the bar.
|
|
|
|
|
:param fill_char: the character to use to show the filled part of the
|
|
|
|
|
progress bar.
|
|
|
|
|
:param empty_char: the character to use to show the non-filled part of
|
|
|
|
|
the progress bar.
|
|
|
|
|
:param bar_template: the format string to use as template for the bar.
|
|
|
|
|
The parameters in it are ``label`` for the label,
|
|
|
|
|
``bar`` for the progress bar and ``info`` for the
|
|
|
|
|
info section.
|
|
|
|
|
:param info_sep: the separator between multiple info items (eta etc.)
|
|
|
|
|
:param width: the width of the progress bar in characters, 0 means full
|
|
|
|
|
terminal width
|
|
|
|
|
:param file: The file to write to. If this is not a terminal then
|
|
|
|
|
only the label is printed.
|
|
|
|
|
:param color: controls if the terminal supports ANSI colors or not. The
|
|
|
|
|
default is autodetection. This is only needed if ANSI
|
|
|
|
|
codes are included anywhere in the progress bar output
|
|
|
|
|
which is not the case by default.
|
|
|
|
|
:param update_min_steps: Render only when this many updates have
|
|
|
|
|
completed. This allows tuning for very fast iterators.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 8.2
|
|
|
|
|
The ``hidden`` argument.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.0
|
|
|
|
|
Output is shown even if execution time is less than 0.5 seconds.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.0
|
|
|
|
|
``item_show_func`` shows the current item, not the previous one.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.0
|
|
|
|
|
Labels are echoed if the output is not a TTY. Reverts a change
|
|
|
|
|
in 7.0 that removed all output.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 8.0
|
|
|
|
|
The ``update_min_steps`` parameter.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 4.0
|
|
|
|
|
The ``color`` parameter and ``update`` method.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 2.0
|
|
|
|
|
"""
|
|
|
|
|
[核心功能] 创建一个进度条对象。
|
|
|
|
|
|
|
|
|
|
它通常用作 Context Manager (with 语句):
|
|
|
|
|
with click.progressbar(items) as bar:
|
|
|
|
|
for item in bar:
|
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
实现细节:它是一个 "Facade" (门面),实际的逻辑委托给了 ._termui_impl.ProgressBar。
|
|
|
|
|
这样做是为了保持 termui.py 的 API 清晰,将复杂的终端绘制逻辑隐藏。
|
|
|
|
|
"""
|
|
|
|
|
from ._termui_impl import ProgressBar
|
|
|
|
|
|
|
|
|
|
@ -491,119 +362,56 @@ def progressbar(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def clear() -> None:
|
|
|
|
|
"""Clears the terminal screen. This will have the effect of clearing
|
|
|
|
|
the whole visible space of the terminal and moving the cursor to the
|
|
|
|
|
top left. This does not do anything if not connected to a terminal.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 2.0
|
|
|
|
|
"""
|
|
|
|
|
[UI工具] 清空终端屏幕。
|
|
|
|
|
"""
|
|
|
|
|
if not isatty(sys.stdout):
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
# ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor
|
|
|
|
|
# 使用 ANSI 转义序列:
|
|
|
|
|
# \033[2J: 清空整个屏幕
|
|
|
|
|
# \033[1;1H: 将光标移动到左上角 (第一行第一列)
|
|
|
|
|
echo("\033[2J\033[1;1H", nl=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str:
|
|
|
|
|
"""
|
|
|
|
|
[内部工具] 将颜色参数转换为 ANSI 代码字符串。
|
|
|
|
|
|
|
|
|
|
offset: 用于区分前景色 (offset=0) 和背景色 (offset=10)。
|
|
|
|
|
例如红色前景是 31,背景是 41。
|
|
|
|
|
"""
|
|
|
|
|
# 处理 8-bit 颜色 (256色模式): \033[38;5;Nm
|
|
|
|
|
if isinstance(color, int):
|
|
|
|
|
return f"{38 + offset};5;{color:d}"
|
|
|
|
|
|
|
|
|
|
# 处理 RGB 真彩色 (True Color): \033[38;2;R;G;Bm
|
|
|
|
|
if isinstance(color, (tuple, list)):
|
|
|
|
|
r, g, b = color
|
|
|
|
|
return f"{38 + offset};2;{r:d};{g:d};{b:d}"
|
|
|
|
|
|
|
|
|
|
# 处理标准具名颜色
|
|
|
|
|
return str(_ansi_colors[color] + offset)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def style(
|
|
|
|
|
text: t.Any,
|
|
|
|
|
fg: int | tuple[int, int, int] | str | None = None,
|
|
|
|
|
bg: int | tuple[int, int, int] | str | None = None,
|
|
|
|
|
bold: bool | None = None,
|
|
|
|
|
dim: bool | None = None,
|
|
|
|
|
underline: bool | None = None,
|
|
|
|
|
overline: bool | None = None,
|
|
|
|
|
italic: bool | None = None,
|
|
|
|
|
blink: bool | None = None,
|
|
|
|
|
reverse: bool | None = None,
|
|
|
|
|
strikethrough: bool | None = None,
|
|
|
|
|
fg: int | tuple[int, int, int] | str | None = None, # 前景色
|
|
|
|
|
bg: int | tuple[int, int, int] | str | None = None, # 背景色
|
|
|
|
|
bold: bool | None = None, # 加粗
|
|
|
|
|
dim: bool | None = None, # 变暗
|
|
|
|
|
underline: bool | None = None, # 下划线
|
|
|
|
|
overline: bool | None = None, # 上划线
|
|
|
|
|
italic: bool | None = None, # 斜体
|
|
|
|
|
blink: bool | None = None, # 闪烁
|
|
|
|
|
reverse: bool | None = None, # 反转 (前背景对调)
|
|
|
|
|
strikethrough: bool | None = None, # 删除线
|
|
|
|
|
reset: bool = True,
|
|
|
|
|
) -> str:
|
|
|
|
|
"""Styles a text with ANSI styles and returns the new string. By
|
|
|
|
|
default the styling is self contained which means that at the end
|
|
|
|
|
of the string a reset code is issued. This can be prevented by
|
|
|
|
|
passing ``reset=False``.
|
|
|
|
|
|
|
|
|
|
Examples::
|
|
|
|
|
|
|
|
|
|
click.echo(click.style('Hello World!', fg='green'))
|
|
|
|
|
click.echo(click.style('ATTENTION!', blink=True))
|
|
|
|
|
click.echo(click.style('Some things', reverse=True, fg='cyan'))
|
|
|
|
|
click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
|
|
|
|
|
|
|
|
|
|
Supported color names:
|
|
|
|
|
|
|
|
|
|
* ``black`` (might be a gray)
|
|
|
|
|
* ``red``
|
|
|
|
|
* ``green``
|
|
|
|
|
* ``yellow`` (might be an orange)
|
|
|
|
|
* ``blue``
|
|
|
|
|
* ``magenta``
|
|
|
|
|
* ``cyan``
|
|
|
|
|
* ``white`` (might be light gray)
|
|
|
|
|
* ``bright_black``
|
|
|
|
|
* ``bright_red``
|
|
|
|
|
* ``bright_green``
|
|
|
|
|
* ``bright_yellow``
|
|
|
|
|
* ``bright_blue``
|
|
|
|
|
* ``bright_magenta``
|
|
|
|
|
* ``bright_cyan``
|
|
|
|
|
* ``bright_white``
|
|
|
|
|
* ``reset`` (reset the color code only)
|
|
|
|
|
|
|
|
|
|
If the terminal supports it, color may also be specified as:
|
|
|
|
|
|
|
|
|
|
- An integer in the interval [0, 255]. The terminal must support
|
|
|
|
|
8-bit/256-color mode.
|
|
|
|
|
- An RGB tuple of three integers in [0, 255]. The terminal must
|
|
|
|
|
support 24-bit/true-color mode.
|
|
|
|
|
|
|
|
|
|
See https://en.wikipedia.org/wiki/ANSI_color and
|
|
|
|
|
https://gist.github.com/XVilka/8346728 for more information.
|
|
|
|
|
|
|
|
|
|
:param text: the string to style with ansi codes.
|
|
|
|
|
:param fg: if provided this will become the foreground color.
|
|
|
|
|
:param bg: if provided this will become the background color.
|
|
|
|
|
:param bold: if provided this will enable or disable bold mode.
|
|
|
|
|
:param dim: if provided this will enable or disable dim mode. This is
|
|
|
|
|
badly supported.
|
|
|
|
|
:param underline: if provided this will enable or disable underline.
|
|
|
|
|
:param overline: if provided this will enable or disable overline.
|
|
|
|
|
:param italic: if provided this will enable or disable italic.
|
|
|
|
|
:param blink: if provided this will enable or disable blinking.
|
|
|
|
|
:param reverse: if provided this will enable or disable inverse
|
|
|
|
|
rendering (foreground becomes background and the
|
|
|
|
|
other way round).
|
|
|
|
|
:param strikethrough: if provided this will enable or disable
|
|
|
|
|
striking through text.
|
|
|
|
|
:param reset: by default a reset-all code is added at the end of the
|
|
|
|
|
string which means that styles do not carry over. This
|
|
|
|
|
can be disabled to compose styles.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.0
|
|
|
|
|
A non-string ``message`` is converted to a string.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.0
|
|
|
|
|
Added support for 256 and RGB color codes.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.0
|
|
|
|
|
Added the ``strikethrough``, ``italic``, and ``overline``
|
|
|
|
|
parameters.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 7.0
|
|
|
|
|
Added support for bright colors.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 2.0
|
|
|
|
|
"""
|
|
|
|
|
[核心功能] 为文本添加 ANSI 样式。
|
|
|
|
|
|
|
|
|
|
返回的是包含 ANSI 转义码的字符串,例如 "\033[31mError\033[0m"。
|
|
|
|
|
"""
|
|
|
|
|
if not isinstance(text, str):
|
|
|
|
|
text = str(text)
|
|
|
|
|
@ -612,16 +420,20 @@ def style(
|
|
|
|
|
|
|
|
|
|
if fg:
|
|
|
|
|
try:
|
|
|
|
|
# 构造前景颜色代码
|
|
|
|
|
bits.append(f"\033[{_interpret_color(fg)}m")
|
|
|
|
|
except KeyError:
|
|
|
|
|
raise TypeError(f"Unknown color {fg!r}") from None
|
|
|
|
|
|
|
|
|
|
if bg:
|
|
|
|
|
try:
|
|
|
|
|
# 构造背景颜色代码 (传入 offset=10)
|
|
|
|
|
bits.append(f"\033[{_interpret_color(bg, 10)}m")
|
|
|
|
|
except KeyError:
|
|
|
|
|
raise TypeError(f"Unknown color {bg!r}") from None
|
|
|
|
|
|
|
|
|
|
# 构造各种字体样式的代码
|
|
|
|
|
# ANSI 码规则: N 开启, 20+N 关闭 (通常)
|
|
|
|
|
if bold is not None:
|
|
|
|
|
bits.append(f"\033[{1 if bold else 22}m")
|
|
|
|
|
if dim is not None:
|
|
|
|
|
@ -638,20 +450,19 @@ def style(
|
|
|
|
|
bits.append(f"\033[{7 if reverse else 27}m")
|
|
|
|
|
if strikethrough is not None:
|
|
|
|
|
bits.append(f"\033[{9 if strikethrough else 29}m")
|
|
|
|
|
|
|
|
|
|
bits.append(text)
|
|
|
|
|
|
|
|
|
|
# 如果 reset=True (默认),在末尾添加重置代码,防止样式泄漏到后面的文本
|
|
|
|
|
if reset:
|
|
|
|
|
bits.append(_ansi_reset_all)
|
|
|
|
|
return "".join(bits)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def unstyle(text: str) -> str:
|
|
|
|
|
"""Removes ANSI styling information from a string. Usually it's not
|
|
|
|
|
necessary to use this function as Click's echo function will
|
|
|
|
|
automatically remove styling if necessary.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 2.0
|
|
|
|
|
|
|
|
|
|
:param text: the text to remove style information from.
|
|
|
|
|
"""
|
|
|
|
|
[UI工具] 移除字符串中的 ANSI 转义码。
|
|
|
|
|
当需要计算字符串的实际显示长度,或者将输出重定向到日志文件时很有用。
|
|
|
|
|
"""
|
|
|
|
|
return strip_ansi(text)
|
|
|
|
|
|
|
|
|
|
@ -664,32 +475,19 @@ def secho(
|
|
|
|
|
color: bool | None = None,
|
|
|
|
|
**styles: t.Any,
|
|
|
|
|
) -> None:
|
|
|
|
|
"""This function combines :func:`echo` and :func:`style` into one
|
|
|
|
|
call. As such the following two calls are the same::
|
|
|
|
|
|
|
|
|
|
click.secho('Hello World!', fg='green')
|
|
|
|
|
click.echo(click.style('Hello World!', fg='green'))
|
|
|
|
|
|
|
|
|
|
All keyword arguments are forwarded to the underlying functions
|
|
|
|
|
depending on which one they go with.
|
|
|
|
|
|
|
|
|
|
Non-string types will be converted to :class:`str`. However,
|
|
|
|
|
:class:`bytes` are passed directly to :meth:`echo` without applying
|
|
|
|
|
style. If you want to style bytes that represent text, call
|
|
|
|
|
:meth:`bytes.decode` first.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.0
|
|
|
|
|
A non-string ``message`` is converted to a string. Bytes are
|
|
|
|
|
passed through without style applied.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 2.0
|
|
|
|
|
"""
|
|
|
|
|
[核心功能] Style + Echo 的组合简写。
|
|
|
|
|
|
|
|
|
|
click.secho('Hello', fg='red') 等同于 click.echo(click.style('Hello', fg='red'))
|
|
|
|
|
"""
|
|
|
|
|
# 如果 message 是字节串,不应用样式(因为样式是针对文本的)
|
|
|
|
|
if message is not None and not isinstance(message, (bytes, bytearray)):
|
|
|
|
|
message = style(message, **styles)
|
|
|
|
|
|
|
|
|
|
return echo(message, file=file, nl=nl, err=err, color=color)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 定义 edit 的多重重载,用于处理不同的返回值类型
|
|
|
|
|
@t.overload
|
|
|
|
|
def edit(
|
|
|
|
|
text: bytes | bytearray,
|
|
|
|
|
@ -729,49 +527,25 @@ def edit(
|
|
|
|
|
extension: str = ".txt",
|
|
|
|
|
filename: str | cabc.Iterable[str] | None = None,
|
|
|
|
|
) -> str | bytes | bytearray | None:
|
|
|
|
|
r"""Edits the given text in the defined editor. If an editor is given
|
|
|
|
|
(should be the full path to the executable but the regular operating
|
|
|
|
|
system search path is used for finding the executable) it overrides
|
|
|
|
|
the detected editor. Optionally, some environment variables can be
|
|
|
|
|
used. If the editor is closed without changes, `None` is returned. In
|
|
|
|
|
case a file is edited directly the return value is always `None` and
|
|
|
|
|
`require_save` and `extension` are ignored.
|
|
|
|
|
|
|
|
|
|
If the editor cannot be opened a :exc:`UsageError` is raised.
|
|
|
|
|
|
|
|
|
|
Note for Windows: to simplify cross-platform usage, the newlines are
|
|
|
|
|
automatically converted from POSIX to Windows and vice versa. As such,
|
|
|
|
|
the message here will have ``\n`` as newline markers.
|
|
|
|
|
|
|
|
|
|
:param text: the text to edit.
|
|
|
|
|
:param editor: optionally the editor to use. Defaults to automatic
|
|
|
|
|
detection.
|
|
|
|
|
:param env: environment variables to forward to the editor.
|
|
|
|
|
:param require_save: if this is true, then not saving in the editor
|
|
|
|
|
will make the return value become `None`.
|
|
|
|
|
:param extension: the extension to tell the editor about. This defaults
|
|
|
|
|
to `.txt` but changing this might change syntax
|
|
|
|
|
highlighting.
|
|
|
|
|
:param filename: if provided it will edit this file instead of the
|
|
|
|
|
provided text contents. It will not use a temporary
|
|
|
|
|
file as an indirection in that case. If the editor supports
|
|
|
|
|
editing multiple files at once, a sequence of files may be
|
|
|
|
|
passed as well. Invoke `click.file` once per file instead
|
|
|
|
|
if multiple files cannot be managed at once or editing the
|
|
|
|
|
files serially is desired.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 8.2.0
|
|
|
|
|
``filename`` now accepts any ``Iterable[str]`` in addition to a ``str``
|
|
|
|
|
if the ``editor`` supports editing multiple files at once.
|
|
|
|
|
|
|
|
|
|
r"""
|
|
|
|
|
[核心功能] 调用系统编辑器 (如 Vim, Nano) 编辑文本。
|
|
|
|
|
|
|
|
|
|
工作原理:
|
|
|
|
|
1. 创建一个临时文件。
|
|
|
|
|
2. 将 text 写入临时文件。
|
|
|
|
|
3. 调用环境变量 EDITOR 指定的编辑器打开该文件。
|
|
|
|
|
4. 等待编辑器进程结束。
|
|
|
|
|
5. 读取临时文件的新内容并返回。
|
|
|
|
|
"""
|
|
|
|
|
from ._termui_impl import Editor
|
|
|
|
|
|
|
|
|
|
ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
|
|
|
|
|
|
|
|
|
|
# 情况1:编辑内存中的字符串
|
|
|
|
|
if filename is None:
|
|
|
|
|
return ed.edit(text)
|
|
|
|
|
|
|
|
|
|
# 情况2:直接编辑指定的文件
|
|
|
|
|
if isinstance(filename, str):
|
|
|
|
|
filename = (filename,)
|
|
|
|
|
|
|
|
|
|
@ -780,61 +554,29 @@ def edit(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def launch(url: str, wait: bool = False, locate: bool = False) -> int:
|
|
|
|
|
"""This function launches the given URL (or filename) in the default
|
|
|
|
|
viewer application for this file type. If this is an executable, it
|
|
|
|
|
might launch the executable in a new session. The return value is
|
|
|
|
|
the exit code of the launched application. Usually, ``0`` indicates
|
|
|
|
|
success.
|
|
|
|
|
|
|
|
|
|
Examples::
|
|
|
|
|
|
|
|
|
|
click.launch('https://click.palletsprojects.com/')
|
|
|
|
|
click.launch('/my/downloaded/file', locate=True)
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 2.0
|
|
|
|
|
|
|
|
|
|
:param url: URL or filename of the thing to launch.
|
|
|
|
|
:param wait: Wait for the program to exit before returning. This
|
|
|
|
|
only works if the launched program blocks. In particular,
|
|
|
|
|
``xdg-open`` on Linux does not block.
|
|
|
|
|
:param locate: if this is set to `True` then instead of launching the
|
|
|
|
|
application associated with the URL it will attempt to
|
|
|
|
|
launch a file manager with the file located. This
|
|
|
|
|
might have weird effects if the URL does not point to
|
|
|
|
|
the filesystem.
|
|
|
|
|
"""
|
|
|
|
|
[系统集成] 打开 URL 或文件。
|
|
|
|
|
|
|
|
|
|
在 Windows 上调用 start,macOS 调用 open,Linux 调用 xdg-open。
|
|
|
|
|
:param locate: 如果为 True,则在文件管理器中定位文件,而不是打开它。
|
|
|
|
|
"""
|
|
|
|
|
from ._termui_impl import open_url
|
|
|
|
|
|
|
|
|
|
return open_url(url, wait=wait, locate=locate)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# If this is provided, getchar() calls into this instead. This is used
|
|
|
|
|
# for unittesting purposes.
|
|
|
|
|
# 用于单元测试的钩子
|
|
|
|
|
_getchar: t.Callable[[bool], str] | None = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def getchar(echo: bool = False) -> str:
|
|
|
|
|
"""Fetches a single character from the terminal and returns it. This
|
|
|
|
|
will always return a unicode character and under certain rare
|
|
|
|
|
circumstances this might return more than one character. The
|
|
|
|
|
situations which more than one character is returned is when for
|
|
|
|
|
whatever reason multiple characters end up in the terminal buffer or
|
|
|
|
|
standard input was not actually a terminal.
|
|
|
|
|
|
|
|
|
|
Note that this will always read from the terminal, even if something
|
|
|
|
|
is piped into the standard input.
|
|
|
|
|
|
|
|
|
|
Note for Windows: in rare cases when typing non-ASCII characters, this
|
|
|
|
|
function might wait for a second character and then return both at once.
|
|
|
|
|
This is because certain Unicode characters look like special-key markers.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 2.0
|
|
|
|
|
|
|
|
|
|
:param echo: if set to `True`, the character read will also show up on
|
|
|
|
|
the terminal. The default is to not show it.
|
|
|
|
|
"""
|
|
|
|
|
[系统集成] 从终端读取单个字符(不等待回车)。
|
|
|
|
|
常用于 "Press any key to continue" 的场景。
|
|
|
|
|
"""
|
|
|
|
|
global _getchar
|
|
|
|
|
|
|
|
|
|
# 延迟加载实现
|
|
|
|
|
if _getchar is None:
|
|
|
|
|
from ._termui_impl import getchar as f
|
|
|
|
|
|
|
|
|
|
@ -844,27 +586,21 @@ def getchar(echo: bool = False) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def raw_terminal() -> AbstractContextManager[int]:
|
|
|
|
|
"""
|
|
|
|
|
[高级功能] 将终端切换到 RAW 模式。
|
|
|
|
|
在此模式下,所有按键事件都会直接发送给程序,而不是由 Shell 处理(例如 Ctrl+C 不会发送信号)。
|
|
|
|
|
"""
|
|
|
|
|
from ._termui_impl import raw_terminal as f
|
|
|
|
|
|
|
|
|
|
return f()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def pause(info: str | None = None, err: bool = False) -> None:
|
|
|
|
|
"""This command stops execution and waits for the user to press any
|
|
|
|
|
key to continue. This is similar to the Windows batch "pause"
|
|
|
|
|
command. If the program is not run through a terminal, this command
|
|
|
|
|
will instead do nothing.
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 2.0
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 4.0
|
|
|
|
|
Added the `err` parameter.
|
|
|
|
|
|
|
|
|
|
:param info: The message to print before pausing. Defaults to
|
|
|
|
|
``"Press any key to continue..."``.
|
|
|
|
|
:param err: if set to message goes to ``stderr`` instead of
|
|
|
|
|
``stdout``, the same as with echo.
|
|
|
|
|
"""
|
|
|
|
|
[UI工具] 暂停执行,直到用户按任意键。
|
|
|
|
|
类似 Windows 的 batch 命令 `pause`。
|
|
|
|
|
"""
|
|
|
|
|
# 如果不是终端环境(例如管道操作),直接跳过
|
|
|
|
|
if not isatty(sys.stdin) or not isatty(sys.stdout):
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
@ -875,9 +611,9 @@ def pause(info: str | None = None, err: bool = False) -> None:
|
|
|
|
|
if info:
|
|
|
|
|
echo(info, nl=False, err=err)
|
|
|
|
|
try:
|
|
|
|
|
getchar()
|
|
|
|
|
getchar() # 等待按键
|
|
|
|
|
except (KeyboardInterrupt, EOFError):
|
|
|
|
|
pass
|
|
|
|
|
finally:
|
|
|
|
|
if info:
|
|
|
|
|
echo(err=err)
|
|
|
|
|
echo(err=err) # 补一个换行
|