
使用方式
关于
使用 Click/Typer 构建专业 CLI 应用,支持富文本输出、进度条和交互式提示。
name: python-cli-ops description: "Python CLI 应用模式。触发条件:cli、command line、typer、click、argparse、terminal、rich、console、terminal ui。" license: MIT compatibility: "Python 3.10+。现代 CLI 开发需要 typer 和 rich。" allowed-tools: "Read Write Bash" metadata: author: claude-mods related-skills: python-typing-ops, python-observability-ops
Python CLI 模式
使用 Typer 和 Rich 进行现代 CLI 开发。
基础 Typer 应用
import typer
app = typer.Typer(
name="myapp",
help="My awesome CLI application",
add_completion=True,
)
@app.command()
def hello(
name: str = typer.Argument(..., help="Name to greet"),
count: int = typer.Option(1, "--count", "-c", help="Times to greet"),
loud: bool = typer.Option(False, "--loud", "-l", help="Uppercase"),
):
"""Say hello to someone."""
message = f"Hello, {name}!"
if loud:
message = message.upper()
for _ in range(count):
typer.echo(message)
if __name__ == "__main__":
app()
命令组
import typer
app = typer.Typer()
users_app = typer.Typer(help="User management commands")
app.add_typer(users_app, name="users")
@users_app.command("list")
def list_users():
"""List all users."""
typer.echo("Listing users...")
@users_app.command("create")
def create_user(name: str, email: str):
"""Create a new user."""
typer.echo(f"Creating user: {name} <{email}>")
Rich 输出
from rich.console import Console
from rich.table import Table
from rich.progress import track
console = Console()
# 表格
table = Table(title="Users")
table.add_column("Name", style="cyan")
table.add_column("Email", style="green")
table.add_row("Alice", "alice@example.com")
console.print(table)
# 进度条
for item in track(items, description="Processing..."):
process(item)
# 样式化输出
console.print("[bold red]Error:[/] Something went wrong")
console.print("[green]Success![/] Operation completed")
快速参考
| 功能 | Typer 用法 |
|------|-----------|
| 必需参数 | name: str = typer.Argument(...) |
| 可选参数 | name: str = typer.Argument("default") |
| 选项 | --flag: bool = typer.Option(False) |
| 短选项 | typer.Option(..., "--name", "-n") |
| 确认提示 | typer.confirm("Continue?") |
| 退出码 | raise typer.Exit(code=1) |
附加资源
./references/typer-advanced.md- 高级 Typer 模式./references/rich-patterns.md- Rich 终端 UI 模式./references/testing-cli.md- CLI 测试策略
兼容工具
Claude CodeCursorGitHub Copilot
标签
后端开发
