簡體   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