cli-patterns
typerとrichを使用したPython CLIの設計—コマンド構造、出力フォーマット、進捗インジケーター、エラーハンドリング、詳細度レベル、マシンリーダブル出力パターン
description の原文を見る
Python CLI design with typer and rich — command structure, output formatting, progress indicators, error UX, verbosity levels, and machine-readable output patterns
SKILL.md 本文
注意: 実装前に context7 MCP で typer/rich API の詳細を確認してください。
コマンド構造 (typer)
import typer
from rich.console import Console
app = typer.Typer(help="My CLI Tool", no_args_is_help=True)
console = Console(stderr=True) # UI on stderr, data on stdout
@app.command()
def generate(
input_file: str = typer.Argument(help="Input file path"),
prompt: str = typer.Argument(help="Generation prompt"),
provider: str = typer.Option(None, "--provider", "-p",
help="LLM provider (e.g., ollama/qwen3:4b-instruct)"),
verbose: int = typer.Option(0, "--verbose", "-v", count=True,
help="Increase verbosity (-v, -vv, -vvv)"),
json_output: bool = typer.Option(False, "--json",
help="Output as JSON (for scripting)"),
):
"""Generate output using the configured LLM pipeline."""
出力の原則
- stdout = データ (パイプ可能)。stderr = UI (進捗、ステータス、エラー)。
- すべてのリッチ出力に
Console(stderr=True)を使用します。 - マシン可読な出力として
--jsonをサポートします。 - 終了コード: 0=成功、1=ユーザーエラー、2=システムエラー。
冗長性レベル
import structlog
log = structlog.get_logger()
# Map -v flags to log levels
LOG_LEVELS = {0: "WARNING", 1: "INFO", 2: "DEBUG", 3: "DEBUG"} # -vvv = trace via structlog
def configure_logging(verbose: int):
level = LOG_LEVELS.get(min(verbose, 3), "DEBUG")
structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(level))
| フラグ | 表示内容 | 用途 |
|---|---|---|
| (なし) | 結果のサマリー | 通常の使用 |
-v | ステージ遷移、主要な判定 | フロー理解 |
-vv | API呼び出し、タイミング、トークン | パフォーマンスデバッグ |
-vvv | 完全なプロンプト、レスポンス、検証 | LLMデバッグ |
進捗インジケーター (rich)
from rich.progress import Progress, SpinnerColumn, TextColumn
# For LLM calls (unknown duration)
with Progress(SpinnerColumn(), TextColumn("{task.description}")) as progress:
task = progress.add_task("Generating output...", total=None)
result = await llm.ainvoke(prompt)
# For multi-step pipelines (known steps)
from rich.progress import BarColumn, TaskProgressColumn
with Progress(BarColumn(), TaskProgressColumn()) as progress:
task = progress.add_task("Pipeline", total=6)
for stage in stages:
await run_stage(stage)
progress.advance(task)
テーブルとパネル
from rich.table import Table
from rich.panel import Panel
# Tabular data
table = Table(title="Pipeline Status")
table.add_column("Stage", style="cyan")
table.add_column("Status", style="green")
table.add_column("Tokens", justify="right")
table.add_row("Generate", "Complete", "1,234")
console.print(table)
# Summary panels
console.print(Panel(
f"[green]Generation complete[/green]\n"
f"Model: {result.model}\n"
f"Tokens: {result.total_tokens}",
title="Result",
))
エラーUX
# User-facing: rich panel with guidance
console.print(Panel(
f"[red]Provider '{name}' not found.[/red]\n\n"
f"Available: {', '.join(available)}\n"
f"Set via: --provider, APP_PROVIDER env, or config file",
title="Configuration Error",
border_style="red",
))
raise typer.Exit(1)
# Never show raw tracebacks. Catch, format, guide.
# Show tracebacks only at -vvv verbosity.
インタラクティブモードとパイプラインモード
import sys
from rich.prompt import Confirm
def maybe_confirm(message: str) -> bool:
"""Prompt interactively, auto-yes in pipeline mode."""
if not sys.stdin.isatty():
return True # Non-interactive: proceed
return Confirm.ask(message)
すべてのインタラクティブなプロンプトに対して、フラグや環境変数などのノンインタラクティブな選択肢を常に提供します。
サブコマンドグループ
# Nested commands for complex CLIs
pipeline_app = typer.Typer(help="Pipeline operations")
app.add_typer(pipeline_app, name="pipeline")
@pipeline_app.command("run")
def pipeline_run(to: str = typer.Option("ship", help="Run up to stage")):
"""Execute pipeline stages."""
# Usage: mytool pipeline run --to seed
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- pvliesdonk
- リポジトリ
- pvliesdonk/agents.md
- ライセンス
- MIT
- 最終更新
- 2026/3/21
Source: https://github.com/pvliesdonk/agents.md / ライセンス: MIT
関連スキル
doubt-driven-development
重要な判断はすべて、本番環境への展開前に新しい視点から対抗的レビューを実施します。速度より正確性が重要な場合、不慣れなコードを扱う場合、本番環境・セキュリティに関わるロジック・取り消し不可の操作など影響度が高い場合、または後でバグを修正するよりも今検証する方が効率的な場合に活用してください。
apprun-skills
TypeScriptを使用したAppRunアプリケーションのMVU設計に関する総合的なガイダンスが得られます。コンポーネントパターン、イベントハンドリング、状態管理(非同期ジェネレータを含む)、パラメータと保護機能を備えたルーティング・ナビゲーション、vistestを使用したテストに対応しています。AppRunコンポーネントの設計・レビュー、ルートの配線、状態フローの管理、AppRunテストの作成時に活用してください。
desloppify
コードベースのヘルスチェックと技術負債の追跡ツールです。コード品質、技術負債、デッドコード、大規模ファイル、ゴッドクラス、重複関数、コードスメル、命名規則の問題、インポートサイクル、結合度の問題についてユーザーが質問した場合に使用してください。また、ヘルススコアの確認、次の改善項目の提案、クリーンアップ計画の作成をリクエストされた際にも対応します。29言語に対応しています。
debugging-and-error-recovery
テストが失敗したり、ビルドが壊れたり、動作が期待と異なったり、予期しないエラーが発生したりした場合に、体系的な根本原因デバッグをガイドします。推測ではなく、根本原因を見つけて修正するための体系的なアプローチが必要な場合に使用してください。
test-driven-development
テスト駆動開発により実装を進めます。ロジックの実装、バグの修正、動作の変更など、あらゆる場面で活用できます。コードが正常に動作することを証明する必要がある場合、バグ報告を受けた場合、既存機能を修正する予定がある場合に使用してください。
incremental-implementation
変更を段階的に実施します。複数のファイルに影響する機能や変更を実装する場合に使用してください。大量のコードを一度に書こうとしている場合や、タスクが一度では完結できないほど大きい場合に活用します。