python-cli-typer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython 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 typerbash
uv add typerQuick Reference
快速参考
| Task | Pattern |
|---|---|
| Single command | |
| Options | function args with defaults |
| Multiple commands | multiple |
| 任务 | 模式 |
|---|---|
| 单命令 | |
| 选项 | 带默认值的函数参数 |
| 多命令 | 多个 |
Workflow
工作流程
- Define a app in
typer.Typer().cli.py - Keep command functions small; move logic into separate modules.
- Run CLI via or
uv run python -m <module>.uv run python cli.py
- 在中定义
cli.py应用。typer.Typer() - 保持命令函数简洁;将业务逻辑移至独立模块。
- 通过或
uv run python -m <module>运行CLI。uv run python cli.py
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 3Multiple 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 for script entry.
if __name__ == "__main__"
- 将复杂业务逻辑放在CLI函数内部。
- 忘记添加作为脚本入口。
if __name__ == "__main__"
Red Flags
注意事项
- CLI guidance that ignores Typer when Typer is the chosen framework.
- 若已选定Typer作为框架,请勿忽略Typer的CLI指导规范。