跳至内容

带有帮助的 CLI 选项

您已经看到如何使用 help 参数为CLI 参数添加帮助文本。

现在让我们对CLI 选项执行相同的操作

import typer
from typing_extensions import Annotated


def main(
    name: str,
    lastname: Annotated[str, typer.Option(help="Last name of person to greet.")] = "",
    formal: Annotated[bool, typer.Option(help="Say hi formally.")] = False,
):
    """
    Say hi to NAME, optionally with a --lastname.

    If --formal is used, say hi very formally.
    """
    if formal:
        print(f"Good day Ms. {name} {lastname}.")
    else:
        print(f"Hello {name} {lastname}")


if __name__ == "__main__":
    typer.run(main)

提示

如果可能,最好使用 Annotated 版本。

import typer


def main(
    name: str,
    lastname: str = typer.Option("", help="Last name of person to greet."),
    formal: bool = typer.Option(False, help="Say hi formally."),
):
    """
    Say hi to NAME, optionally with a --lastname.

    If --formal is used, say hi very formally.
    """
    if formal:
        print(f"Good day Ms. {name} {lastname}.")
    else:
        print(f"Hello {name} {lastname}")


if __name__ == "__main__":
    typer.run(main)

typer.Argument() 相同,我们可以将 typer.Option() 放在 Annotated 中。

然后我们可以传递 help 关键字参数

lastname: Annotated[str, typer.Option(help="this option does this and that")] = ""

...来创建该CLI 选项的帮助。

typer.Argument() 相同,Typer 也支持使用函数参数默认值的老式风格

lastname: str = typer.Option(default="", help="this option does this and that")

将上面的示例复制到文件 main.py 中。

测试它

$ python main.py --help

Usage: main.py [OPTIONS] NAME

  Say hi to NAME, optionally with a --lastname.

  If --formal is used, say hi very formally.

Arguments:
  NAME  [required]

Options:
  --lastname TEXT         Last name of person to greet. [default: ]
  --formal / --no-formal  Say hi formally.  [default: False]
  --help                  Show this message and exit.

// Now you have a help text for the --lastname and --formal CLI options 🎉

CLI 选项帮助面板

CLI 参数相同,您可以将一些CLI 选项的帮助放入不同的面板中,以通过 --help 选项显示。

如果您已按照打印和颜色文档中的说明安装了 Rich,则可以将 rich_help_panel 参数设置为每个CLI 选项所需的 painel 名称

import typer
from typing_extensions import Annotated


def main(
    name: str,
    lastname: Annotated[str, typer.Option(help="Last name of person to greet.")] = "",
    formal: Annotated[
        bool,
        typer.Option(
            help="Say hi formally.", rich_help_panel="Customization and Utils"
        ),
    ] = False,
    debug: Annotated[
        bool,
        typer.Option(
            help="Enable debugging.", rich_help_panel="Customization and Utils"
        ),
    ] = False,
):
    """
    Say hi to NAME, optionally with a --lastname.

    If --formal is used, say hi very formally.
    """
    if formal:
        print(f"Good day Ms. {name} {lastname}.")
    else:
        print(f"Hello {name} {lastname}")


if __name__ == "__main__":
    typer.run(main)

提示

如果可能,最好使用 Annotated 版本。

import typer


def main(
    name: str,
    lastname: str = typer.Option("", help="Last name of person to greet."),
    formal: bool = typer.Option(
        False, help="Say hi formally.", rich_help_panel="Customization and Utils"
    ),
    debug: bool = typer.Option(
        False, help="Enable debugging.", rich_help_panel="Customization and Utils"
    ),
):
    """
    Say hi to NAME, optionally with a --lastname.

    If --formal is used, say hi very formally.
    """
    if formal:
        print(f"Good day Ms. {name} {lastname}.")
    else:
        print(f"Hello {name} {lastname}")


if __name__ == "__main__":
    typer.run(main)

现在,当您检查 --help 选项时,您将看到一个名为“Options”的默认面板,用于没有自定义 rich_help_panelCLI 选项

在下面,您将看到其他面板,用于在 rich_help_panel 参数中设置了自定义面板的CLI 选项

$ python main.py --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] NAME                                </b>
<b>                                                                     </b>
 Say hi to NAME, optionally with a <font color="#A1EFE4"><b>--lastname</b></font>.
 If <font color="#6B9F98"><b>--formal</b></font><font color="#A5A5A1"> is used, say hi very formally.                          </font>

<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#F92672">*</font>    name      <font color="#F4BF75"><b>TEXT</b></font>  [default: None] <font color="#A6194C">[required]</font>                   │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--lastname</b></font>                  <font color="#F4BF75"><b>TEXT</b></font>  Last name of person to greet.   │
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font>                      <font color="#F4BF75"><b>    </b></font>  Show this message and exit.     │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Customization and Utils ─────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--formal</b></font>    <font color="#AE81FF"><b>--no-formal</b></font>      Say hi formally.                     │
<font color="#A5A5A1">│                              [default: no-formal]                 │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--debug</b></font>     <font color="#AE81FF"><b>--no-debug</b></font>       Enable debugging.                    │
<font color="#A5A5A1">│                              [default: no-debug]                  │</font>
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

这里我们有一个名为“Customization and Utils”的自定义CLI 选项面板。

使用 Rich 的样式帮助

在未来的章节中,您将了解如何在阅读命令 - 命令帮助时在CLI 选项help 中使用自定义标记。

如果您很赶时间,可以跳到那里,但除此之外,最好继续在此处阅读并按顺序学习教程。

从帮助中隐藏默认值

您可以使用 show_default=False 告诉 Typer 在帮助文本中不显示默认值

import typer
from typing_extensions import Annotated


def main(fullname: Annotated[str, typer.Option(show_default=False)] = "Wade Wilson"):
    print(f"Hello {fullname}")


if __name__ == "__main__":
    typer.run(main)

提示

如果可能,最好使用 Annotated 版本。

import typer


def main(fullname: str = typer.Option("Wade Wilson", show_default=False)):
    print(f"Hello {fullname}")


if __name__ == "__main__":
    typer.run(main)

它将不再在帮助文本中显示默认值

$ python main.py

Hello Wade Wilson

// Show the help
$ python main.py --help

Usage: main.py [OPTIONS]

Options:
  --fullname TEXT
  --help                Show this message and exit.

// Notice there's no [default: Wade Wilson] 🔥

技术细节

在 Click 应用程序中,默认值默认隐藏。🙈

Typer 中,这些默认值默认显示。👀

自定义默认字符串

您可以使用相同的 show_default 传递一个自定义字符串(而不是 bool)以自定义要在帮助文本中显示的默认值

import typer
from typing_extensions import Annotated


def main(
    fullname: Annotated[
        str, typer.Option(show_default="Deadpoolio the amazing's name")
    ] = "Wade Wilson",
):
    print(f"Hello {fullname}")


if __name__ == "__main__":
    typer.run(main)

提示

如果可能,最好使用 Annotated 版本。

import typer


def main(
    fullname: str = typer.Option(
        "Wade Wilson", show_default="Deadpoolio the amazing's name"
    ),
):
    print(f"Hello {fullname}")


if __name__ == "__main__":
    typer.run(main)

它将用于帮助文本

$ python main.py

Hello Wade Wilson

// Show the help
$ python main.py --help

Usage: main.py [OPTIONS]

Options:
  --fullname TEXT       [default: (Deadpoolio the amazing's name)]
  --help                Show this message and exit.

// Notice how it shows "(Deadpoolio the amazing's name)" instead of the actual default of "Wade Wilson"