Typer 是一个用于构建命令行界面(CLI)应用的 Python 库,致力于提供简单、直观的方式来定义命令行参数和选项。在本指南中,我们将详细介绍如何使用 Typer 编写 CLI 应用程序。
1、安装
首先,我们需要安装 Typer。您可以使用以下命令通过 pip 安装:
pip install typer
2、基本用法
import typer
def main(
firstname: str, # 简单的参数,默认等同于 firstname: str = typer.Argument(...)
lastname: str = typer.Argument(..., help="Lastname"), # ... 表示必选, 虽然 Argument 本身就是必选
email: str = typer.Option(..., '-e', '--email', # Option 为可选参数, ... 表示这个可选参数为必选项, 后面可跟缩写和非缩写的参数名
prompt="Please enter your email"), # prompt 为提示信息, 如果没有明确指定,则会弹出提示要求输入
# 类型为int,所以可以指定最小值和最大值, clamp 表示超出了就按照最大值或最小值来处理
age: int = typer.Option(None, '-a', '--age', min=1, max=100, clamp=True)
):
"""
Say hello to someone.
"""
# 上方为CLI的描述, 会自动放入帮助信息
print(f"Hello {firstname} {lastname}")
print(f'Your email is {email}')
if age:
print(f'Your age is {age}')
if __name__ == '__main__':
typer.run(main) # 运行主函数
可以看到,当只需要一个主命令的时候,那么使用typer.run(main)会非常方便。
参数有两种typer.Argument 和 typer.Option
输出结果:
> python .\1.py --help
Usage: 1.py [OPTIONS] FIRSTNAME LASTNAME
Say hello to someone.
Arguments:
FIRSTNAME [required]
Options:
-e, --email TEXT [required]
--install-completion Install completion for the current shell.
--show-completion Show completion for the current shell, to copy it
or customize the installation.
--help Show this message and exit.
> python .\1.py Fried Pei
Please enter your email: 365433079@qq.com
Hello Fried Pei
Your email is 365433079@qq.com
> python .\1.py Fried Pei --age 28 --email 365433079@qq.com
Hello Fried Pei
Your email is 365433079@qq.com
Your age is 28