Skip to content

Recipes

Complete, runnable CLIs. Each one is self-contained: save it as app.py and run it with python app.py --help.

For management commands in a Django project, see Django projects.

A git-style CLI with short aliases

Common commands get short names, and the help stays readable because each command is listed once.

import typer

from typer_swissknife import add_typer, command

app = typer.Typer(help="A tiny task manager.")
tags = typer.Typer(help="Manage tags.")

TASKS: list[str] = []


@command(app, aliases=("a",))
def add(title: str) -> None:
    """Add a task."""
    TASKS.append(title)
    print(f"Added: {title}")


@command(app, name="list", aliases=("ls", "l"))
def list_tasks() -> None:
    """List the tasks."""
    for number, title in enumerate(TASKS, start=1):
        print(f"{number}. {title}")


@command(app, name="remove", aliases=("rm", "del"))
def remove_task(number: int) -> None:
    """Remove a task by number."""
    print(f"Removed task {number}")


@command(tags, name="list", aliases=("ls",))
def list_tags() -> None:
    """List the tags."""
    print("home, work")


add_typer(app, tags, name="tags", aliases=("t",))

if __name__ == "__main__":
    app()
$ python app.py --help
...
│ add (a)                 Add a task.               │
│ list (ls, l)            List the tasks.           │
│ remove (rm, del)        Remove a task by number.  │
│ tags (t)                Manage tags.              │

$ python app.py t ls
home, work

A branded CLI with banners

The main app, each group and the important commands open their help page with a banner.

import typer

from typer_swissknife import add_typer, command, get_ascii_help_text

app = typer.Typer(help=get_ascii_help_text("Shop", body="Manage the online shop."))
products = typer.Typer(help="Manage products.")
orders = typer.Typer(help="Manage orders.")


@command(products, name="list", aliases=("ls",), ascii_name="Products")
def list_products() -> None:
    """List all products.

    Products are sorted by name.
    """
    print("chair, desk, lamp")


@command(orders, name="list", aliases=("ls",))
def list_orders() -> None:
    """List open orders."""
    print("#1001, #1002")


add_typer(app, products, name="products", aliases=("p",), ascii_name="Products")
add_typer(app, orders, name="orders", aliases=("o",), ascii_name="Orders", ascii_font="slant")

if __name__ == "__main__":
    app()

python app.py p --help shows the PRODUCTS banner and "Manage products.", while python app.py --help lists products (p) Manage products. on one line.

Passing arbitrary amounts through to a function

An invoice command forwards any --name AMOUNT option to a calculation, without declaring each one. Decimal("free") raises decimal.InvalidOperation, which is not a ValueError, so a small converter turns it into one; a bad amount is then a clean usage error instead of a traceback.

from decimal import Decimal, InvalidOperation

import typer

from typer_swissknife import command

app = typer.Typer()


def money(value: str) -> Decimal:
    try:
        return Decimal(value)
    except InvalidOperation:
        raise ValueError(value) from None


@command(app, aliases=("inv",))
def invoice(customer: str, **adjustments: money) -> None:
    """Print the invoice total for CUSTOMER.

    Any --name AMOUNT option is added to the base price of 100,
    for example --shipping 7.50 --discount -10.
    """
    total = sum(adjustments.values(), Decimal("100"))

    print(f"{customer}: {total}")


@command(app)
def customers() -> None:
    """List customers."""
    print("acme, globex")

if __name__ == "__main__":
    app()
$ python app.py inv acme --shipping 7.50 --discount -10
acme: 97.50

$ python app.py inv acme --shipping free
...
│ Invalid value for --shipping: 'free' is not a valid money. │

Template variables for a render command

Without an annotation, values stay strings, which fits template variables.

from string import Template

import typer

from typer_swissknife import command

app = typer.Typer()


@command(app)
def render(template: str, **variables) -> None:
    """Fill $placeholders in TEMPLATE with --name value options."""
    print(Template(template).safe_substitute(variables))


@command(app)
def version() -> None:
    print("1.0")

if __name__ == "__main__":
    app()
$ python app.py render 'Hello $name, welcome to $city' --name Abdullah --city Damascus
Hello Abdullah, welcome to Damascus