Skip to main content
ClaudeWave
Skill355 repo starsupdated today

python-cli-patterns

This Claude Code skill provides production-ready patterns for building Python command-line applications using Typer and Rich. It covers basic command structure, organizing commands into groups, formatting output with tables and progress bars, and implementing error handling. Use this skill when developing CLI tools that require clean argument parsing, professional terminal UI formatting, or structured command hierarchies.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/aiskillstore/marketplace /tmp/python-cli-patterns && cp -r /tmp/python-cli-patterns/skills/0xdarkmatter/python-cli-patterns ~/.claude/skills/python-cli-patterns
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# Python CLI Patterns

Modern CLI development with Typer and Rich.

## Basic Typer App

```python
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()
```

## Command Groups

```python
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}>")

@app.command()
def version():
    """Show version."""
    typer.echo("1.0.0")

# Usage: myapp users list
#        myapp users create "John" "john@example.com"
#        myapp version
```

## Rich Output

```python
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():
    """Display users in a table."""
    table = Table(title="Users")
    table.add_column("ID", style="cyan")
    table.add_column("Name", style="green")
    table.add_column("Email")

    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():
    """Process items with progress bar."""
    items = list(range(100))
    for item in track(items, description="Processing..."):
        do_something(item)
    console.print("[green]Done![/green]")
```

## Error Handling

```python
import typer
from rich.console import Console

console = Console()

def error(message: str, code: int = 1):
    """Print error and exit."""
    console.print(f"[red]Error:[/red] {message}")
    raise typer.Exit(code)

@app.command()
def process(file: str):
    """Process a file."""
    if not os.path.exists(file):
        error(f"File not found: {file}")

    try:
        result = process_file(file)
        console.print(f"[green]Success:[/green] {result}")
    except ValueError as e:
        error(str(e))
```

## Quick Reference

| Feature | Typer Syntax |
|---------|--------------|
| Required arg | `name: str` |
| Optional arg | `name: str = "default"` |
| Option | `typer.Option(default, "--flag", "-f")` |
| Argument | `typer.Argument(..., help="...")` |
| Boolean flag | `verbose: bool = False` |
| Enum choice | `color: Color = Color.red` |

| Rich Feature | Usage |
|--------------|-------|
| Table | `Table()` + `add_column/row` |
| Progress | `track(items)` |
| Colors | `[red]text[/red]` |
| Panel | `Panel("content", title="Title")` |

## Additional Resources

- `./references/typer-patterns.md` - Advanced Typer patterns
- `./references/rich-output.md` - Rich tables, progress, formatting
- `./references/configuration.md` - Config files, environment variables

## Assets

- `./assets/cli-template.py` - Full CLI application template

---

## See Also

**Related Skills:**
- `python-typing-patterns` - Type hints for CLI arguments
- `python-observability-patterns` - Logging for CLI applications

**Complementary Skills:**
- `python-env` - Package CLI for distribution
jira-safeSkill

Implement SAFe methodology in Jira. Use when creating Epics, Features, Stories with proper hierarchy, acceptance criteria, and parent-child linking.

jira-workflowSkill

Orchestrate Jira workflows end-to-end. Use when building stories with approvals, transitioning items through lifecycle states, or syncing task completion with Jira.

chinese-learning-assistantSkill

HSK4級レベルから流暢さを目指す学習者向け。中国語表現の使用場面・自然さを分析し、作文を「ネイティブらしい流暢な表現」に改善。bilibili等のコンテンツ理解とネイティブとの会話をサポート。実際の用例をWeb検索で提示

frontend-dev-guidelinesSkill

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

skill-developerSkill

Claude Code 스킬, 훅, 에이전트, 명령어를 생성하고 관리하기 위한 메타 스킬. 새 스킬 생성, 스킬 트리거 설정, 훅 설정, Claude Code 인프라 관리 시 사용.

sitemapkitSkill

Discover and extract sitemaps from any website using SitemapKit. Use this skill whenever the user wants to find pages on a website, get a list of URLs from a domain, audit a site's structure, crawl a sitemap, check what pages exist on a site, or do anything involving sitemaps or site URL discovery — even if they don't explicitly say "sitemap". Requires the sitemapkit MCP server configured with a valid SITEMAPKIT_API_KEY.

create-prSkill

GitHubのプルリクエスト(PR)を作成する際に使用します。変更のコミット、プッシュ、PR作成を含む完全なワークフローを日本語で実行します。「PRを作って」「プルリクエストを作成」「pull requestを作成」などのリクエストで自動的に起動します。

create-svg-from-promptSkill

Generate an SVG of a user-requested image or scene