name: python-cli-patterns description: “用于Python的命令行界面应用模式。触发关键词:cli,命令行,typer,click,argparse,终端,rich,控制台,终端用户界面。” compatibility: “Python 3.10+。现代CLI开发需要typer和rich。” allowed-tools: “Read Write Bash” depends-on: [] related-skills: [python-typing-patterns, python-observability-patterns]
Python CLI 模式
使用 Typer 和 Rich 进行现代 CLI 开发。
基础 Typer 应用
import typer
app = typer.Typer(
name="myapp",
help="我的超棒CLI应用",
add_completion=True,
)
@app.command()
def hello(
name: str = typer.Argument(..., help="要问候的名字"),
count: int = typer.Option(1, "--count", "-c", help="问候次数"),
loud: bool = typer.Option(False, "--loud", "-l", help="大写输出"),
):
"""向某人问好。"""
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="用户管理命令")
app.add_typer(users_app, name="users")
@users_app.command("list")
def list_users():
"""列出所有用户。"""
typer.echo("正在列出用户...")
@users_app.command("create")
def create_user(name: str, email: str):
"""创建新用户。"""
typer.echo(f"创建用户: {name} <{email}>")
@app.command()
def version():
"""显示版本。"""
typer.echo("1.0.0")
# 用法: myapp users list
# myapp users create "John" "john@example.com"
# myapp version
Rich 输出
from rich.console import Console
from rich.table import Table
from rich.progress import track
from rich.panel import Panel
import typer
console = Console()
@app.command()
def show_users():
"""在表格中显示用户。"""
table = Table(title="用户")
table.add_column("ID", style="cyan")
table.add_column("姓名", style="green")
table.add_column("邮箱")
users = [
(1, "Alice", "alice@example.com"),
(2, "Bob", "bob@example.com"),
]
for id, name, email in users:
table.add_row(str(id), name, email)
console.print(table)
@app.command()
def process():
"""使用进度条处理项目。"""
items = list(range(100))
for item in track(items, description="处理中..."):
do_something(item)
console.print("[green]完成![/green]")
错误处理
import typer
from rich.console import Console
console = Console()
def error(message: str, code: int = 1):
"""打印错误并退出。"""
console.print(f"[red]错误:[/red] {message}")
raise typer.Exit(code)
@app.command()
def process(file: str):
"""处理文件。"""
if not os.path.exists(file):
error(f"文件未找到: {file}")
try:
result = process_file(file)
console.print(f"[green]成功:[/green] {result}")
except ValueError as e:
error(str(e))
快速参考
| 功能 | Typer 语法 |
|---|---|
| 必需参数 | name: str |
| 可选参数 | name: str = "default" |
| 选项 | typer.Option(default, "--flag", "-f") |
| 参数 | typer.Argument(..., help="...") |
| 布尔标志 | verbose: bool = False |
| 枚举选择 | color: Color = Color.red |
| Rich 功能 | 用法 |
|---|---|
| 表格 | Table() + add_column/row |
| 进度条 | track(items) |
| 颜色 | [red]text[/red] |
| 面板 | Panel("content", title="Title") |
附加资源
./references/typer-patterns.md- 高级 Typer 模式./references/rich-output.md- Rich 表格、进度条、格式化./references/configuration.md- 配置文件、环境变量
资源文件
./assets/cli-template.py- 完整的 CLI 应用模板
另请参阅
相关技能:
python-typing-patterns- CLI 参数的类型提示python-observability-patterns- CLI 应用的日志记录
互补技能:
python-env- 打包 CLI 以供分发