Get the FREE Ultimate OpenClaw Setup Guide →

python-cli-patterns

Scanned
npx machina-cli add skill aiskillstore/marketplace/python-cli-patterns --openclaw
Files (1)
SKILL.md
4.0 KB

Python CLI Patterns

Modern CLI development with Typer and Rich.

Basic Typer App

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

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

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

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

FeatureTyper Syntax
Required argname: str
Optional argname: str = "default"
Optiontyper.Option(default, "--flag", "-f")
Argumenttyper.Argument(..., help="...")
Boolean flagverbose: bool = False
Enum choicecolor: Color = Color.red
Rich FeatureUsage
TableTable() + add_column/row
Progresstrack(items)
Colors[red]text[/red]
PanelPanel("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

Source

git clone https://github.com/aiskillstore/marketplace/blob/main/skills/0xdarkmatter/python-cli-patterns/SKILL.mdView on GitHub

Overview

Learn modern Python CLI development with Typer and Rich. This guide covers basic commands, command grouping, rich UI, and robust error handling to build practical CLI tools.

How This Skill Works

The skill demonstrates building a Typer app via typer.Typer, defining commands with @app.command, and composing sub-commands with add_typer for modular groups. It also shows enriching output using Rich components like Console, Table, and track for progress, plus error handling with typer.Exit. You can reference assets and references to accelerate development.

When to Use It

  • Build a modern Python CLI with typed arguments and options using Typer.
  • Organize commands into groups or sub commands for larger tools such as user management.
  • Display rich UI elements like tables, progress bars, and colored messages with Rich.
  • Handle errors gracefully with consistent colored output and typed exit codes.
  • Consult the provided references and assets to accelerate CLI template development.

Quick Start

  1. Step 1: Install Typer and Rich (pip install typer rich).
  2. Step 2: Create a Typer app and define a few commands with @app.command.
  3. Step 3: Add Rich output (console, table, progress) and simple error handling.

Best Practices

  • Start with a small Typer app and iterate by adding sub commands with add_typer.
  • Enable command completion by setting add_completion to True on the Typer app.
  • Leverage Rich for output components such as Table, track, and Panel.
  • Keep command logic focused and move heavy operations into helpers.
  • Use a centralized error helper that prints with color and exits with a code.

Example Use Cases

  • Basic Typer app with hello command and optional count and loud flag.
  • User management namespace with list and create subcommands.
  • Show a table of users using Rich Console and Table.
  • Process items with a progress bar using Rich track.
  • Error handling pattern that prints colored errors and exits with a code.

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers