带有多个值的 CLI 参数
CLI 参数 也可以接收多个值。
可以使用 typing.List
定义 CLI 参数 的类型。
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)
然后可以传递任意数量的该类型的 CLI 参数
$ python main.py ./index.md ./first-steps.md woohoo!
This file exists: index.md
woohoo!
This file exists: first-steps.md
woohoo!
提示
还声明了一个最终的 CLI 参数 celebration
,即使先传递任意数量的 files
,它也能被正确使用。
信息
List
只能在最后一个命令中使用(如果有子命令),因为这将把右侧的所有内容都视为预期 CLI 参数 的一部分。
CLI 参数 使用元组¶
如果你想要指定数量的值和类型,可以使用元组,它甚至可以有默认值。
from typing import Tuple
import typer
from typing_extensions import Annotated
def main(
names: Annotated[
Tuple[str, str, str], typer.Argument(help="Select 3 characters to play with")
] = ("Harry", "Hermione", "Ron"),
):
for name in names:
print(f"Hello {name}")
if __name__ == "__main__":
typer.run(main)
提示
如果可能,建议使用 Annotated
版本。
from typing import Tuple
import typer
def main(
names: Tuple[str, str, str] = typer.Argument(
("Harry", "Hermione", "Ron"), help="Select 3 characters to play with"
),
):
for name in names:
print(f"Hello {name}")
if __name__ == "__main__":
typer.run(main)
检查一下
// Check the help
$ python main.py --help
Usage: main.py [OPTIONS] [NAMES]...
Arguments:
[NAMES]... Select 3 characters to play with [default: Harry, Hermione, Ron]
Options:
--help Show this message and exit.
// Use it with its defaults
$ python main.py
Hello Harry
Hello Hermione
Hello Ron
// If you pass an invalid number of arguments you will get an error
$ python main.py Draco Hagrid
Error: Argument 'names' takes 3 values
// And if you pass the exact number of values it will work correctly
$ python main.py Draco Hagrid Dobby
Hello Draco
Hello Hagrid
Hello Dobby