必需的 CLI 选项

我们之前说过默认情况下

  • CLI 选项可选的
  • CLI 参数必需的

嗯,这是它们默认情况下的工作方式,也是许多 CLI 程序和系统中的约定。

但如果你真的想,你可以更改它。

要使CLI 选项成为必需的,你可以将 typer.Option() 放在 Annotated 中,并使参数没有默认值。

让我们使 --lastname 成为必需的CLI 选项

import typer
from typing_extensions import Annotated


def main(name: str, lastname: Annotated[str, typer.Option()]):
    print(f"Hello {name} {lastname}")


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

typer.Argument() 一样,也支持使用函数参数默认值的老式方法,在这种情况下,你只需不将任何内容传递给 default 参数即可。

import typer


def main(name: str, lastname: str = typer.Option()):
    print(f"Hello {name} {lastname}")


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

或者你可以明确地将 ... 传递给 typer.Option(default=...)

import typer


def main(name: str, lastname: str = typer.Option(default=...)):
    print(f"Hello {name} {lastname}")


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

信息

如果您之前没有见过 ...:它是一个特殊单值,它是 Python 的一部分,称为“省略号”

这将告诉 Typer 它仍然是一个CLI 选项,但它没有默认值,并且是必需的。

提示

同样,如果可能,最好使用 Annotated 版本。这样,您的代码在标准 Python 和 Typer 中的含义相同。

并测试它

// Pass the NAME CLI argument
$ python main.py Camila

// We didn't pass the now required --lastname CLI option
Usage: main.py [OPTIONS] NAME
Try "main.py --help" for help.

Error: Missing option '--lastname'.

// Now update it to pass the required --lastname CLI option
$ python main.py Camila --lastname Gutiérrez

Hello Camila Gutiérrez

// And if you check the help
$ python main.py --help

Usage: main.py [OPTIONS] NAME

Options:
  --lastname TEXT       [required]
  --help                Show this message and exit.

// It now tells you that --lastname is required 🎉