python-cli-typer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python CLI with Typer

使用Typer开发Python CLI

Overview

概述

Use Typer for ergonomic CLI construction. Core principle: keep CLI entry points explicit and testable.
使用Typer构建符合人体工程学的CLI工具。核心原则:保持CLI入口点明确且可测试。

Install

安装

bash
uv add typer
bash
uv add typer

Quick Reference

快速参考

TaskPattern
Single command
@app.command()
Optionsfunction args with defaults
Multiple commandsmultiple
@app.command()
任务模式
单命令
@app.command()
选项带默认值的函数参数
多命令多个
@app.command()

Workflow

工作流程

  • Define a
    typer.Typer()
    app in
    cli.py
    .
  • Keep command functions small; move logic into separate modules.
  • Run CLI via
    uv run python -m <module>
    or
    uv run python cli.py
    .
  • cli.py
    中定义
    typer.Typer()
    应用。
  • 保持命令函数简洁;将业务逻辑移至独立模块。
  • 通过
    uv run python -m <module>
    uv run python cli.py
    运行CLI。

Example

示例

python
import typer

app = typer.Typer()

@app.command()
def greet(name: str, count: int = 1) -> None:
    for _ in range(count):
        typer.echo(f"Hello, {name}!")

if __name__ == "__main__":
    app()
Usage:
bash
uv run python cli.py --help
uv run python cli.py Alice
uv run python cli.py Alice --count 3
Multiple commands:
python
import typer

app = typer.Typer()


@app.command()
def create(name: str) -> None:
    """Create a new item."""
    typer.echo(f"Creating {name}...")


@app.command()
def delete(name: str, force: bool = False) -> None:
    """Delete an item."""
    if not force:
        if not typer.confirm(f"Delete {name}?"):
            raise typer.Abort()
    typer.echo(f"Deleted {name}")


if __name__ == "__main__":
    app()
python
import typer

app = typer.Typer()

@app.command()
def greet(name: str, count: int = 1) -> None:
    for _ in range(count):
        typer.echo(f"Hello, {name}!")

if __name__ == "__main__":
    app()
使用方式:
bash
uv run python cli.py --help
uv run python cli.py Alice
uv run python cli.py Alice --count 3
多命令示例:
python
import typer

app = typer.Typer()


@app.command()
def create(name: str) -> None:
    """创建一个新项目。"""
    typer.echo(f"Creating {name}...")


@app.command()
def delete(name: str, force: bool = False) -> None:
    """删除一个项目。"""
    if not force:
        if not typer.confirm(f"Delete {name}?"):
            raise typer.Abort()
    typer.echo(f"Deleted {name}")


if __name__ == "__main__":
    app()

Common Mistakes

常见错误

  • Putting heavy business logic inside CLI functions.
  • Forgetting to wire
    if __name__ == "__main__"
    for script entry.
  • 将复杂业务逻辑放在CLI函数内部。
  • 忘记添加
    if __name__ == "__main__"
    作为脚本入口。

Red Flags

注意事项

  • CLI guidance that ignores Typer when Typer is the chosen framework.
  • 若已选定Typer作为框架,请勿忽略Typer的CLI指导规范。