SuperAPI AI 工具集

typer

编程与开发

查看项目

更新于 10-15 22:40

技能介绍

用途:Typer 让开发者通过在 Python 函数上添加类型注解来构建命令行应用,Typer 会把类型注解转换为带校验的 CLI 参数并自动生成帮助文本。该技能在用户询问使用 Typer 构建 CLI、定义参数或选项、组合子命令、测试 CLI 应用,或使用 prompt、enum、进度条、自动补全等特性时激活。

主要能力:使用 typer.Typer() 和 typer.run() 创建应用;用 typer.Argument() 定义参数、typer.Option() 定义选项;支持 enum、path、数字、日期、UUID 和自定义参数类型;用 app.add_typer() 组合子命令;用 typer.testing.CliRunner 测试;支持输出、颜色、进度条、回调与自动补全。

使用方式:按任务类型查阅对应参考文件——应用与命令、参数、参数类型、子命令、测试、进阶模式。示例:import typer; from typing import Annotated; app = typer.Typer();用 @app.command() 装饰函数,参数 name: str 为必填参数,count: Annotated[int, typer.Option()] = 1 为可选选项,formal: bool = False 表示 --formal / --no-formal;末尾用 if name == "main": app() 运行,如 python main.py Alice --count 2 --formal。

适用场景:需要为 Python 项目编写命令行工具、多级子命令、带校验的输入参数和自动化测试时。限制:不涵盖 Click 内部的细节、typer.echo / typer.style 之外的 Rich 库、FastAPI 或其他 Web 框架;共享规则需参考 python-engineering:standards-for-python-development。Typer 版本可通过 python -c "import typer; print(typer.version)" 查看,失败时显示 not found in PATH。