繁体   English   中英

Python Typer 和 CLI 选项的多个输入

[英]Python Typer and multiple inputs to CLI option

我正在尝试使用 Python Typer 创建一个带有选项输入的 CLI:

  • 取多个值
  • 是一个列表类型。

例如:

$ ./my_cli --device 1 2
...
Got unexpected extra argument (2)   

我的代码如下所示:

def main(
    devices: List[str] = typer.Option([], help="Devices to query"),
):
    print(f"CLI option is {devices}")

有任何想法吗?

from typing import List, Optional

import typer


def main(device: Optional[List[str]] = typer.Option(None)):
    if not device:
        print("No provided devices")
        raise typer.Abort()
    for d in device:
        print(f"Processing device: {d}")


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

然后它可以像这样使用:

$ ./my_cli --device 1 --device 2

查看文档

如果 CLI 的唯一输入是设备列表,您可以将其简化为使用arguments 然后它可以像这样使用:

$ ./my_cli 1 2
from pathlib import Path
from typing import List

import typer


def main(files: List[Path], celebration: str):
    for path in files:
        if path.is_file():
            print(f"This file exists: {path.name}")
            print(celebration)


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

暂无
暂无

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

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