自定义命令名称

默认情况下,命令名称根据函数名称生成。

因此,如果您的函数类似于

def create(username: str):
    ...

那么命令名称将为 create

但是,如果您在代码中某个地方已经有一个名为 create() 的函数,则必须以不同的方式命名您的 CLI 函数。

如果您希望命令仍然命名为 create,该怎么办?

为此,您可以在 @app.command() 装饰器的第一个参数中设置命令的名称

import typer

app = typer.Typer()


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


@app.command("delete")
def cli_delete_user(username: str):
    print(f"Deleting user: {username}")


if __name__ == "__main__":
    app()

现在,即使函数名为 cli_create_user()cli_delete_user(),命令仍将命名为 createdelete

fast →python main.py --help
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
delete

python main.py create Camila
Creating user: Camila

restart ↻

请注意,函数名称中的任何下划线都将替换为破折号。

因此,如果您的函数类似于

def create_user(username: str):
    ...
那么命令名称将为 create-user