繁体   English   中英

如何在 Python 中为 Typer 命令添加标志

[英]How to add flags for Typer commands in Python

我是Typer的新手,但我无法在文档中真正找到我需要的信息......
我正在尝试使用 typer 命令向我的应用程序添加标志。 我想拥有:

myApp command1 --flag1 value1 --flag2 value2

目前我有一个简单的命令,它需要一个字符串:

@app.command(
    name="foo",
    help="bar",
)
def command1(path: str) -> None:  # noqa: D401
    """
    Text

    Args:
        path: my favourite path
    """
    # some code here

有什么方法可以调整上面的 function 以便它像第一个框中一样采用标志+值?

如果您尝试创建一个只有一个命令 ( command1 ) 的typer脚本,那么您需要查看这个文档页面,它告诉您有一个“陷阱”:

您可能已经注意到,如果您创建一个命令,(...) Typer 足够聪明,可以创建一个 CLI 应用程序,将单个 function 作为主 CLI 应用程序,而不是作为命令/子命令:
请注意,它不显示命令 main,即使 function 名称是 main。

但是,如果您添加多个命令,Typer 将为每个命令创建一个 CLI 命令:

稍后在文档中也提到了解决方案:

如果你想用一个命令创建一个 CLI 应用程序,但你仍然希望它是一个命令/子命令,你可以添加一个回调

在您的情况下,它可能与此类似(针对您的特定程序逻辑进行调整):

import typer
app = typer.Typer()

# I am assuming you need a mandatory 'path' and optionals 'flag1' and 'flag2'      
@app.command()
def command1(path: str, flag1: str = 'value1', flag2: str = 'value2'):
    print(f"running on {path} with {flag1} and {flag2}")

# this callback is added as workaround for the "just one command" gotcha
# you can use it for documenting purposes
@app.callback()
def callback():
    """
    Text
    Args:
        path: my favourite path
    """

if __name__ == "__main__":
    app()

然后,它将生成以下--help消息:

❯ python3 myApp.py --help

 Usage: myApp.py [OPTIONS] COMMAND [ARGS]...                    
                                                                
 Text Args:     path: my favourite path                         
                                                                 
╭─ Commands ───────────────────────────────────────────────────╮
│ command1                                                     │
╰──────────────────────────────────────────────────────────────╯


❯ python3 myApp.py command1 --help

Usage: myApp.py command1 [OPTIONS] PATH

╭─ Arguments ──────────────────────────────────────────────────╮
│ *    path      TEXT  [default: None] [required]              │
╰──────────────────────────────────────────────────────────────╯
╭─ Options ────────────────────────────────────────────────────╮
│ --flag1        TEXT  [default: value1]                       │
│ --flag2        TEXT  [default: value2]                       │
│ --help               Show this message and exit.             │
╰──────────────────────────────────────────────────────────────╯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM