跳至内容

CLI 参数类型简介

您可以为CLI 选项CLI 参数使用多种数据类型,还可以添加数据验证要求。

数据转换

当您使用某种类型声明CLI 参数时,Typer 会将命令行中接收的数据转换为该数据类型。

例如

import typer


def main(name: str, age: int = 20, height_meters: float = 1.89, female: bool = True):
    print(f"NAME is {name}, of type: {type(name)}")
    print(f"--age is {age}, of type: {type(age)}")
    print(f"--height-meters is {height_meters}, of type: {type(height_meters)}")
    print(f"--female is {female}, of type: {type(female)}")


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

在此示例中,为CLI 参数 NAME 接收的值将被视为 str

CLI 选项 --age 的值将转换为 int--height-meters 将转换为 float

由于 femalebool CLI 选项Typer 会将其转换为“标志”--female和对应项--no-female

以下是它的样子

$ python main.py --help

// Notice how --age is an INTEGER and --height-meters is a FLOAT
Usage: main.py [OPTIONS] NAME

Arguments:
  NAME  [required]

Options:
  --age INTEGER           [default: 20]
  --height-meters FLOAT   [default: 1.89]
  --female / --no-female  [default: True]
  --help                  Show this message and exit.

// Call it with CLI parameters
$ python main.py Camila --age 15 --height-meters 1.70 --female

// All the data has the correct Python type
NAME is Camila, of type: class 'str'
--age is 15, of type: class 'int'
--height-meters is 1.7, of type: class 'float'
--female is True, of type: class 'bool'

// And if you pass an incorrect type
$ python main.py Camila --age 15.3

Usage: main.py [OPTIONS] NAME
Try "main.py --help" for help.

Error: Invalid value for '--age': '15.3' is not a valid integer

// Because 15.3 is not an INTEGER (it's a float)

观看下一个

在下一部分中查看有关特定类型和验证的更多信息...

技术细节

您将在下一部分中看到的所有类型都由 Click 的参数类型 在下面处理。