跳到主要内容

多值参数

Multiple CLI Options

可以为 CLI Option 定义为允许多次调用,获取所有调用值的形式

from typing import List, Optional

import typer
from typing_extensions import Annotated


def main(user: Annotated[Optional[List[str]], typer.Option()] = None):
if not user:
print(f"No provided users (raw input = {user})")
raise typer.Abort()
for u in user:
print(f"Processing user: {u}")


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

image-20240801133801883

自定义值的数量和类型

可以把 CLI Options 定义成多值的同时,定义值的不同类型

from typing import Tuple

import typer
from typing_extensions import Annotated


def main(user: Annotated[Tuple[str, int, bool], typer.Option()] = (None, None, None)):
username, coins, is_wizard = user
if not username:
print("No user provided")
raise typer.Abort()
print(f"The username {username} has {coins} coins")
if is_wizard:
print("And this user is a wizard!")


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

Each of the internal types defines the type of each value in the tuple.

user: Tuple[str, int, bool]

意味着 user 参数包含三个不同类型的值(按顺序)

  • The first value is a str.
  • The second value is an int.
  • The third value is a bool.

Later we do:

username, coins, is_wizard = user

is equivalent to this:

username = user[0]
coins = user[1]
is_wizard = user[2]

image-20240801134232411

CLI Arguments with Multiple Values

CLI Arguments 也可以是多值的

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)

image-20240801135202424

We also declared a final CLI argument celebration, and it's correctly used even if we pass an arbitrary number of files first.

自定义值的数量和类型

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)