跳至内容

带有多个值的 CLI 选项

您还可以声明一个接受不同类型多个值的CLI 选项

您可以将值的数量和类型设置为任何您想要的,但它必须是固定数量的值。

为此,请使用标准 Python typing.Tuple

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)

提示

如果可能,请优先使用Annotated 版本。

from typing import Tuple

import typer


def main(user: 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)

每个内部类型都定义了元组中每个值的类型。

所以

user: Tuple[str, int, bool]

表示参数user 是一个包含 3 个值的元组。

  • 第一个值是str
  • 第二个值是int
  • 第三个值是bool

稍后我们做

username, coins, is_wizard = user

如果您之前没有见过,这意味着user 是一个包含 3 个值的元组,我们正在将每个值分配给一个新变量

  • 元组user 中的第一个值(一个str)被分配给变量username
  • 元组user 中的第二个值(一个int)被分配给变量coins
  • 元组user 中的第三个值(一个bool)被分配给变量is_wizard

所以,这个

username, coins, is_wizard = user

等同于这个

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

提示

请注意,默认值是一个包含(None, None, None) 的元组。

您不能简单地在这里使用None 作为默认值,因为Click 不支持它

检查它

现在让我们看看它在终端中是如何工作的

// check the help
$ python main.py --help

// Notice the <TEXT INTEGER BOOLEAN>
Usage: main.py [OPTIONS]

Options:
  --user <TEXT INTEGER BOOLEAN>...
  --help                          Show this message and exit.

// Now try it
$ python main.py --user Camila 50 yes

The username Camila has 50 coins
And this user is a wizard!

// With other values
$ python main.py --user Morty 3 no

The username Morty has 3 coins

// Try with invalid values (not enough)
$ python main.py --user Camila 50

Error: Option '--user' requires 3 arguments