使用 Typer 快速开发命令行工具
快速构建现代化 CLI 应用
Typer 是一个基于 Python 的命令行接口开发库,它利用 click 和 Pydantic 的强大能力,让开发者能够以极简方式创建功能丰富的命令行程序。
安装方法
pip install "typer[all]"
基础示例:打印问候语
只需两行代码即可启动一个可执行的命令行应用:
import typer
app = typer.Typer()
@app.command()
def greet(name: str):
typer.echo(f"欢迎,{name}!")
if __name__ == "__main__":
app()
自动帮助文档生成
运行命令后,自动生成清晰的使用说明:
$ python main.py --help
Usage: main.py [OPTIONS] NAME
Options:
--help Show this message and exit.
多命令支持
通过装饰器为每个函数添加命令标识,即可扩展多个子命令:
@app.command()
def say_hello(name: str):
typer.echo(f"你好,{name}!")
@app.command()
def calculate_age(birth_year: int):
current_year = 2024
age = current_year - birth_year
typer.echo(f"你今年 {age} 岁。")
参数与类型自动推断
函数参数直接映射为命令行选项,支持类型校验、默认值和范围限制:
@app.command()
def process_data(
input_file: str,
output_dir: str = "./output",
verbose: bool = False,
count: int = 1,
threshold: float = 0.5
):
if count < 1:
raise typer.BadParameter("计数必须大于等于 1")
typer.echo(f"处理文件:{input_file}")
typer.echo(f"输出路径:{output_dir}")
typer.echo(f"详细模式:{verbose}")
typer.echo(f"阈值:{threshold}")
子命令结构化设计
支持嵌套命令,模拟 Git 风格的层级结构:
app = typer.Typer()
sub_app = typer.Typer()
app.add_typer(sub_app, name="manage")
@sub_app.command()
def add_user(username: str, role: str = "user"):
typer.echo(f"添加用户:{username}(角色:{role})")
@sub_app.command()
def remove_user(username: str):
typer.echo(f"移除用户:{username}")
调用方式:
$ python main.py manage add-user alice --role=admin
高级特性
- 交互式输入:支持用户在终端中逐项填写信息
- 彩色输出:使用
rich实现高亮文本展示 - 进度条:内置对长任务的可视化进度反馈
- 错误提示优化:提供精准的参数校验错误提示
所有功能均无需额外配置,开箱即用,极大提升开发效率与用户体验。