跳至内容

命令帮助

与之前相同,你可以在文档字符串和CLI 选项中添加命令帮助。

并且 typer.Typer() 应用程序接收一个参数 help,你可以使用该参数传递 CLI 程序的主要帮助文本

import typer
from typing_extensions import Annotated

app = typer.Typer(help="Awesome CLI user manager.")


@app.command()
def create(username: str):
    """
    Create a new user with USERNAME.
    """
    print(f"Creating user: {username}")


@app.command()
def delete(
    username: str,
    force: Annotated[
        bool,
        typer.Option(
            prompt="Are you sure you want to delete the user?",
            help="Force deletion without confirmation.",
        ),
    ],
):
    """
    Delete a user with USERNAME.

    If --force is not used, will ask for confirmation.
    """
    if force:
        print(f"Deleting user: {username}")
    else:
        print("Operation cancelled")


@app.command()
def delete_all(
    force: Annotated[
        bool,
        typer.Option(
            prompt="Are you sure you want to delete ALL users?",
            help="Force deletion without confirmation.",
        ),
    ],
):
    """
    Delete ALL users in the database.

    If --force is not used, will ask for confirmation.
    """
    if force:
        print("Deleting all users")
    else:
        print("Operation cancelled")


@app.command()
def init():
    """
    Initialize the users database.
    """
    print("Initializing user database")


if __name__ == "__main__":
    app()

提示

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

import typer

app = typer.Typer(help="Awesome CLI user manager.")


@app.command()
def create(username: str):
    """
    Create a new user with USERNAME.
    """
    print(f"Creating user: {username}")


@app.command()
def delete(
    username: str,
    force: bool = typer.Option(
        ...,
        prompt="Are you sure you want to delete the user?",
        help="Force deletion without confirmation.",
    ),
):
    """
    Delete a user with USERNAME.

    If --force is not used, will ask for confirmation.
    """
    if force:
        print(f"Deleting user: {username}")
    else:
        print("Operation cancelled")


@app.command()
def delete_all(
    force: bool = typer.Option(
        ...,
        prompt="Are you sure you want to delete ALL users?",
        help="Force deletion without confirmation.",
    ),
):
    """
    Delete ALL users in the database.

    If --force is not used, will ask for confirmation.
    """
    if force:
        print("Deleting all users")
    else:
        print("Operation cancelled")


@app.command()
def init():
    """
    Initialize the users database.
    """
    print("Initializing user database")


if __name__ == "__main__":
    app()

检查它

// Check the new help
$ python main.py --help

Usage: main.py [OPTIONS] COMMAND [ARGS]...

  Awesome CLI user manager.

Options:
  --install-completion  Install completion for the current shell.
  --show-completion     Show completion for the current shell, to copy it or customize the installation.
  --help                Show this message and exit.

Commands:
  create      Create a new user with USERNAME.
  delete      Delete a user with USERNAME.
  delete-all  Delete ALL users in the database.
  init        Initialize the users database.

// Now the commands have inline help 🎉

// Check the help for create
$ python main.py create --help

Usage: main.py create [OPTIONS] USERNAME

  Create a new user with USERNAME.

Options:
  --help  Show this message and exit.

// Check the help for delete
$ python main.py delete --help

Usage: main.py delete [OPTIONS] USERNAME

  Delete a user with USERNAME.

  If --force is not used, will ask for confirmation.

Options:
  --force / --no-force  Force deletion without confirmation.  [required]
  --help                Show this message and exit.

// Check the help for delete-all
$ python main.py delete-all --help

Usage: main.py delete-all [OPTIONS]

  Delete ALL users in the database.

  If --force is not used, will ask for confirmation.

Options:
  --force / --no-force  Force deletion without confirmation.  [required]
  --help                Show this message and exit.

// Check the help for init
$ python main.py init --help

Usage: main.py init [OPTIONS]

  Initialize the users database.

Options:
  --help  Show this message and exit.

提示

typer.Typer() 接收其他几个参数用于其他内容,我们稍后会看到。

稍后您还将看到如何使用“回调”,其中包括在函数文档字符串中添加此相同帮助消息的方法。

覆盖命令帮助

您可能最好将帮助文本作为文档字符串添加到函数中,但如果出于某种原因您想覆盖它,可以使用传递给 @app.command()help 函数参数

import typer

app = typer.Typer()


@app.command(help="Create a new user with USERNAME.")
def create(username: str):
    """
    Some internal utility function to create.
    """
    print(f"Creating user: {username}")


@app.command(help="Delete a user with USERNAME.")
def delete(username: str):
    """
    Some internal utility function to delete.
    """
    print(f"Deleting user: {username}")


if __name__ == "__main__":
    app()

检查它

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

// Notice it uses the help passed to @app.command()
Usage: main.py [OPTIONS] COMMAND [ARGS]...

Options:
  --install-completion  Install completion for the current shell.
  --show-completion     Show completion for the current shell, to copy
                        it or customize the installation.
  --help                Show this message and exit.

Commands:
  create  Create a new user with USERNAME.
  delete  Delete a user with USERNAME.

// It uses "Create a new user with USERNAME." instead of "Some internal utility function to create."

弃用命令

在某些情况下,您的应用中可能有一个您需要弃用的命令,以便您的用户停止使用它,即使它仍然受支持一段时间。

您可以使用参数 deprecated=True 标记它

import typer

app = typer.Typer()


@app.command()
def create(username: str):
    """
    Create a user.
    """
    print(f"Creating user: {username}")


@app.command(deprecated=True)
def delete(username: str):
    """
    Delete a user.

    This is deprecated and will stop being supported soon.
    """
    print(f"Deleting user: {username}")


if __name__ == "__main__":
    app()

当您显示 --help 选项时,您会看到它被标记为“已弃用

$ python main.py --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] COMMAND [ARGS]...                  </b>
<b>                                                                     </b>
<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font>          Install completion for the current  │
<font color="#A5A5A1">│                               shell.                              │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font>             Show completion for the current     │
<font color="#A5A5A1">│                               shell, to copy it or customize the  │</font>
<font color="#A5A5A1">│                               installation.                       │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font>                        Show this message and exit.         │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Commands ────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>create       </b></font> Create a user.                                      │
<font color="#A5A5A1">│ </font><font color="#6B9F98"><b>delete       </b></font> Delete a user.              <font color="#F92672">(deprecated)           </font> │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

如果您检查已弃用命令的 --help(在本示例中,命令为 delete),它也会显示为已弃用

$ python main.py delete --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py delete [OPTIONS] USERNAME                    </b>
<b>                                                                     </b>
 <font color="#F92672">(deprecated) </font>
 Delete a user.
 This is deprecated and will stop being supported soon.

<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#F92672">*</font>    username      <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>--help</b></font>          Show this message and exit.                       │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

丰富的 Markdown 和标记

如果您已按照 打印和颜色 中所述安装了 Rich,则可以使用参数 rich_markup_mode 配置您的应用以启用标记文本。

然后,您可以在文档字符串以及CLI 参数CLI 选项help 参数中使用更多格式。您将在下面看到更多相关内容。👇

信息

默认情况下,rich_markup_modeNone,这会禁用任何富文本格式。

丰富的标记

如果您在创建 typer.Typer() 应用时将 rich_markup_mode="rich" 设置为,您将能够在文档字符串中使用 Rich 控制台标记,甚至在CLI 参数和选项的帮助中使用它

import typer
from typing_extensions import Annotated

app = typer.Typer(rich_markup_mode="rich")


@app.command()
def create(
    username: Annotated[
        str, typer.Argument(help="The username to be [green]created[/green]")
    ],
):
    """
    [bold green]Create[/bold green] a new [italic]shinny[/italic] user. :sparkles:

    This requires a [underline]username[/underline].
    """
    print(f"Creating user: {username}")


@app.command(help="[bold red]Delete[/bold red] a user with [italic]USERNAME[/italic].")
def delete(
    username: Annotated[
        str, typer.Argument(help="The username to be [red]deleted[/red]")
    ],
    force: Annotated[
        bool, typer.Option(help="Force the [bold red]deletion[/bold red] :boom:")
    ] = False,
):
    """
    Some internal utility function to delete.
    """
    print(f"Deleting user: {username}")


if __name__ == "__main__":
    app()

提示

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

import typer

app = typer.Typer(rich_markup_mode="rich")


@app.command()
def create(
    username: str = typer.Argument(
        ..., help="The username to be [green]created[/green]"
    ),
):
    """
    [bold green]Create[/bold green] a new [italic]shiny[/italic] user. :sparkles:

    This requires a [underline]username[/underline].
    """
    print(f"Creating user: {username}")


@app.command(help="[bold red]Delete[/bold red] a user with [italic]USERNAME[/italic].")
def delete(
    username: str = typer.Argument(..., help="The username to be [red]deleted[/red]"),
    force: bool = typer.Option(
        False, help="Force the [bold red]deletion[/bold red] :boom:"
    ),
):
    """
    Some internal utility function to delete.
    """
    print(f"Deleting user: {username}")


if __name__ == "__main__":
    app()

有了它,您可以使用 Rich 控制台标记 来格式化命令 create 的文档字符串中的文本,将单词“create”加粗并显示为绿色,甚至使用 表情符号

您还可以在 username CLI 参数的帮助中使用标记。

与之前相同,为命令 delete 覆盖的帮助文本也可以使用 Rich 标记,在 CLI 参数和 CLI 选项中也是如此。

如果您运行该程序并查看帮助,您将看到Typer在内部使用Rich来格式化帮助。

查看create命令的帮助

$ python main.py create --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py create [OPTIONS] USERNAME                     </b>
<b>                                                                     </b>
 <font color="#A6E22E"><b>Create</b></font> a new <i>shiny</i> user. ✨
 This requires a <font color="#A5A5A1"><u style="text-decoration-style:single">username</u></font><font color="#A5A5A1">.                                           </font>

<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#F92672">*</font>    username      <font color="#F4BF75"><b>TEXT</b></font>  The username to be <font color="#A6E22E">created</font>               │
<font color="#A5A5A1">│                          [default: None]                          │</font>
<font color="#A5A5A1">│                          </font><font color="#A6194C">[required]                </font>               │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font>          Show this message and exit.                       │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

并查看delete命令的帮助

$ python main.py delete --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py delete [OPTIONS] USERNAME                     </b>
<b>                                                                     </b>
 <font color="#F92672"><b>Delete</b></font> a user with <i>USERNAME</i>.

<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#F92672">*</font>    username      <font color="#F4BF75"><b>TEXT</b></font>  The username to be <font color="#F92672">deleted</font>               │
<font color="#A5A5A1">│                          [default: None]                          │</font>
<font color="#A5A5A1">│                          </font><font color="#A6194C">[required]                </font>               │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--force</b></font>    <font color="#AE81FF"><b>--no-force</b></font>      Force the <font color="#F92672"><b>deletion</b></font> 💥                  │
<font color="#A5A5A1">│                            [default: no-force]                    │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font>                     Show this message and exit.            │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

Rich Markdown

如果您在创建typer.Typer()应用程序时设置rich_markup_mode="markdown",您将能够在文档字符串中使用 Markdown

import typer
from typing_extensions import Annotated

app = typer.Typer(rich_markup_mode="markdown")


@app.command()
def create(
    username: Annotated[str, typer.Argument(help="The username to be **created**")],
):
    """
    **Create** a new *shinny* user. :sparkles:

    * Create a username

    * Show that the username is created

    ---

    Learn more at the [Typer docs website](https://typer.fastapi.org.cn)
    """
    print(f"Creating user: {username}")


@app.command(help="**Delete** a user with *USERNAME*.")
def delete(
    username: Annotated[str, typer.Argument(help="The username to be **deleted**")],
    force: Annotated[bool, typer.Option(help="Force the **deletion** :boom:")] = False,
):
    """
    Some internal utility function to delete.
    """
    print(f"Deleting user: {username}")


if __name__ == "__main__":
    app()

提示

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

import typer

app = typer.Typer(rich_markup_mode="markdown")


@app.command()
def create(username: str = typer.Argument(..., help="The username to be **created**")):
    """
    **Create** a new *shiny* user. :sparkles:

    * Create a username

    * Show that the username is created

    ---

    Learn more at the [Typer docs website](https://typer.fastapi.org.cn)
    """
    print(f"Creating user: {username}")


@app.command(help="**Delete** a user with *USERNAME*.")
def delete(
    username: str = typer.Argument(..., help="The username to be **deleted**"),
    force: bool = typer.Option(False, help="Force the **deletion** :boom:"),
):
    """
    Some internal utility function to delete.
    """
    print(f"Deleting user: {username}")


if __name__ == "__main__":
    app()

有了它,您可以使用 Markdown 来格式化命令create的文档字符串中的文本,加粗单词“create”,显示项目列表,甚至使用表情符号

与之前相同,为命令delete覆盖的帮助文本也可以使用 Markdown。

查看create命令的帮助

$ python main.py create --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py create [OPTIONS] USERNAME                     </b>
<b>                                                                     </b>
 <b>Create</b> a new <i>shiny</i> user. ✨

 <font color="#F4BF75"><b> • </b></font><font color="#A5A5A1">Create a username                                                </font>
 <font color="#F4BF75"><b> • </b></font><font color="#A5A5A1">Show that the username is created                                </font>

 <font color="#F4BF75">───────────────────────────────────────────────────────────────────</font>
 Learn more at the <font color="#44919F">Typer docs website</font>

<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#F92672">*</font>    username      <font color="#F4BF75"><b>TEXT</b></font>  The username to be <b>created</b>               │
<font color="#A5A5A1">│                          [default: None]                          │</font>
<font color="#A5A5A1">│                          </font><font color="#A6194C">[required]                              </font> │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font>          Show this message and exit.                       │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

delete命令也是如此

$ python main.py delete --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py delete [OPTIONS] USERNAME                     </b>
<b>                                                                     </b>
 <b>Delete</b> a user with <i>USERNAME</i>.

<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#F92672">*</font>    username      <font color="#F4BF75"><b>TEXT</b></font>  The username to be <b>deleted</b>               │
<font color="#A5A5A1">│                          [default: None]                          │</font>
<font color="#A5A5A1">│                          </font><font color="#A6194C">[required]                              </font> │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--force</b></font>    <font color="#AE81FF"><b>--no-force</b></font>      Force the <b>deletion</b> 💥                  │
<font color="#A5A5A1">│                            [default: no-force]                    │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font>                     Show this message and exit.            │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

信息

请注意,在 Markdown 中您无法定义颜色。对于颜色,您可能更喜欢使用 Rich 标记。

帮助面板

如果您有许多命令或 CLI 参数,您可能希望在使用--help选项时在不同的面板中显示它们的文档。

如果您已安装Rich(如打印和颜色中所述),您可以配置要用于每个命令或 CLI 参数的面板。

命令的帮助面板

要设置命令的面板,您可以传递参数rich_help_panel,其中包含您要使用的面板的名称

import typer

app = typer.Typer(rich_markup_mode="rich")


@app.command()
def create(username: str):
    """
    [green]Create[/green] a new user. :sparkles:
    """
    print(f"Creating user: {username}")


@app.command()
def delete(username: str):
    """
    [red]Delete[/red] a user. :fire:
    """
    print(f"Deleting user: {username}")


@app.command(rich_help_panel="Utils and Configs")
def config(configuration: str):
    """
    [blue]Configure[/blue] the system. :wrench:
    """
    print(f"Configuring the system with: {configuration}")


@app.command(rich_help_panel="Utils and Configs")
def sync():
    """
    [blue]Synchronize[/blue] the system or something fancy like that. :recycle:
    """
    print("Syncing the system")


@app.command(rich_help_panel="Help and Others")
def help():
    """
    Get [yellow]help[/yellow] with the system. :question:
    """
    print("Opening help portal...")


@app.command(rich_help_panel="Help and Others")
def report():
    """
    [yellow]Report[/yellow] an issue. :bug:
    """
    print("Please open a new issue online, not a direct message")


if __name__ == "__main__":
    app()

没有面板的命令将显示在默认面板Commands中,其余命令将显示在下一个面板中

$ python main.py --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] COMMAND [ARGS]...                   </b>
<b>                                                                     </b>
<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font>          Install completion for the current  │
<font color="#A5A5A1">│                               shell.                              │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font>             Show completion for the current     │
<font color="#A5A5A1">│                               shell, to copy it or customize the  │</font>
<font color="#A5A5A1">│                               installation.                       │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font>                        Show this message and exit.         │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Commands ────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>create          </b></font> <font color="#A6E22E">Create</font> a new user. ✨                            │
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>delete          </b></font> <font color="#F92672">Delete</font> a user. 🔥                                │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Utils and Configs ───────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>config  </b></font> <font color="#66D9EF">Configure</font> the system. 🔧                                 │
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>sync    </b></font> <font color="#66D9EF">Synchronize</font> the system or something fancy like that. ♻   │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Help and Others ─────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>help         </b></font> Get <font color="#F4BF75">help</font> with the system. ❓                        │
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>report       </b></font> <font color="#F4BF75">Report</font> an issue. 🐛                                 │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

CLI 参数的帮助面板

同样,您可以使用rich_help_panel配置CLI 参数CLI 选项的面板。

当然,在同一应用程序中,您还可以为命令设置rich_help_panel

from typing import Union

import typer
from typing_extensions import Annotated

app = typer.Typer(rich_markup_mode="rich")


@app.command()
def create(
    username: Annotated[str, typer.Argument(help="The username to create")],
    lastname: Annotated[
        str,
        typer.Argument(
            help="The last name of the new user", rich_help_panel="Secondary Arguments"
        ),
    ] = "",
    force: Annotated[bool, typer.Option(help="Force the creation of the user")] = False,
    age: Annotated[
        Union[int, None],
        typer.Option(help="The age of the new user", rich_help_panel="Additional Data"),
    ] = None,
    favorite_color: Annotated[
        Union[str, None],
        typer.Option(
            help="The favorite color of the new user",
            rich_help_panel="Additional Data",
        ),
    ] = None,
):
    """
    [green]Create[/green] a new user. :sparkles:
    """
    print(f"Creating user: {username}")


@app.command(rich_help_panel="Utils and Configs")
def config(configuration: str):
    """
    [blue]Configure[/blue] the system. :wrench:
    """
    print(f"Configuring the system with: {configuration}")


if __name__ == "__main__":
    app()

提示

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

from typing import Union

import typer

app = typer.Typer(rich_markup_mode="rich")


@app.command()
def create(
    username: str = typer.Argument(..., help="The username to create"),
    lastname: str = typer.Argument(
        "", help="The last name of the new user", rich_help_panel="Secondary Arguments"
    ),
    force: bool = typer.Option(False, help="Force the creation of the user"),
    age: Union[int, None] = typer.Option(
        None, help="The age of the new user", rich_help_panel="Additional Data"
    ),
    favorite_color: Union[str, None] = typer.Option(
        None,
        help="The favorite color of the new user",
        rich_help_panel="Additional Data",
    ),
):
    """
    [green]Create[/green] a new user. :sparkles:
    """
    print(f"Creating user: {username}")


@app.command(rich_help_panel="Utils and Configs")
def config(configuration: str):
    """
    [blue]Configure[/blue] the system. :wrench:
    """
    print(f"Configuring the system with: {configuration}")


if __name__ == "__main__":
    app()

然后,如果您运行该应用程序,您将在各自的面板中看到所有CLI 参数

  • 首先是CLI 参数,它们在名为“Arguments”的默认面板中没有设置面板名称。
  • 接下来是带有自定义面板CLI 参数。在此示例中,名为“辅助参数”。
  • 然后是CLI 选项,它们在名为“选项”的默认面板中没有面板。
  • 最后,带有自定义面板设置的CLI 选项。在此示例中,名为“附加数据”。

你可以查看命令 create--help 选项

$ python main.py create --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py create [OPTIONS] USERNAME [LASTNAME]          </b>
<b>                                                                     </b>
 <font color="#A6E22E">Create</font> a new user. ✨

<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#F92672">*</font>    username      <font color="#F4BF75"><b>TEXT</b></font>  The username to create [default: None]   │
<font color="#A5A5A1">│                          </font><font color="#A6194C">[required]            </font>                   │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Secondary Arguments ─────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│   lastname      </font><font color="#A37F4E"><b>[LASTNAME]</b></font>  The last name of the new user         │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--force</b></font>    <font color="#AE81FF"><b>--no-force</b></font>      Force the creation of the user         │
<font color="#A5A5A1">│                            [default: no-force]                    │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font>                     Show this message and exit.            │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Additional Data ─────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--age</b></font>                   <font color="#F4BF75"><b>INTEGER</b></font>  The age of the new user          │
<font color="#A5A5A1">│                                  [default: None]                  │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--favorite-color</b></font>        <font color="#F4BF75"><b>TEXT   </b></font>  The favorite color of the new    │
<font color="#A5A5A1">│                                  user                             │</font>
<font color="#A5A5A1">│                                  [default: None]                  │</font>
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

当然,rich_help_panel 可以以相同的方式用于同一应用程序中的命令。

当你使用主 --help 选项时,将显示这些面板。

$ python main.py --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] COMMAND [ARGS]...                   </b>
<b>                                                                     </b>
<font color="#A5A5A1">╭─ Options ─────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--install-completion</b></font>          Install completion for the current  │
<font color="#A5A5A1">│                               shell.                              │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font>             Show completion for the current     │
<font color="#A5A5A1">│                               shell, to copy it or customize the  │</font>
<font color="#A5A5A1">│                               installation.                       │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font>                        Show this message and exit.         │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Commands ────────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>create          </b></font> <font color="#A6E22E">Create</font> a new user. ✨                            │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>
<font color="#A5A5A1">╭─ Utils and Configs ───────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>config         </b></font> <font color="#66D9EF">Configure</font> the system. 🔧                          │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

你可以看到“工具和配置”命令的自定义面板。

尾声

如果需要,你还可以向命令的帮助中添加一个尾声部分

import typer

app = typer.Typer(rich_markup_mode="rich")


@app.command(epilog="Made with :heart: in [blue]Venus[/blue]")
def create(username: str):
    """
    [green]Create[/green] a new user. :sparkles:
    """
    print(f"Creating user: {username}")


if __name__ == "__main__":
    app()

当你查看 --help 选项时,它将如下所示

$ python main.py --help

<b> </b><font color="#F4BF75"><b>Usage: </b></font><b>main.py [OPTIONS] USERNAME                            </b>
<b>                                                                     </b>
 <font color="#A6E22E">Create</font> a new user. ✨

<font color="#A5A5A1">╭─ Arguments ───────────────────────────────────────────────────────╮</font>
<font color="#A5A5A1">│ </font><font color="#F92672">*</font>    username      <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>--install-completion</b></font>          Install completion for the current  │
<font color="#A5A5A1">│                               shell.                              │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--show-completion</b></font>             Show completion for the current     │
<font color="#A5A5A1">│                               shell, to copy it or customize the  │</font>
<font color="#A5A5A1">│                               installation.                       │</font>
<font color="#A5A5A1">│ </font><font color="#A1EFE4"><b>--help</b></font>                        Show this message and exit.         │
<font color="#A5A5A1">╰───────────────────────────────────────────────────────────────────╯</font>

 Made with ❤ in <font color="#66D9EF">Venus</font>