Command CLI Options

Commands can also have their own CLI options.

In fact, each command can have different CLI arguments and CLI options:

import typer_cloup as typer

app = typer.Typer()


@app.command()
def create(username: str):
    typer.echo(f"Creating user: {username}")


@app.command()
def delete(
    username: str,
    force: bool = typer.Option(..., prompt="Are you sure you want to delete the user?"),
):
    if force:
        typer.echo(f"Deleting user: {username}")
    else:
        typer.echo("Operation cancelled")


@app.command()
def delete_all(
    force: bool = typer.Option(..., prompt="Are you sure you want to delete ALL users?")
):
    if force:
        typer.echo("Deleting all users")
    else:
        typer.echo("Operation cancelled")


@app.command()
def init():
    typer.echo("Initializing user database")


if __name__ == "__main__":
    app()

Here we have multiple commands, with different CLI parameters:

  • create:
    • username: a CLI argument.
  • delete:
    • username: a CLI argument.
    • --force: a CLI option, if not provided, it's prompted.
  • delete-all:
    • --force: a CLI option, if not provided, it's prompted.
  • init:
    • Doesn't take any CLI parameters.
// Check the help
python main.py --help

Usage: main.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  create
  delete
  delete-all
  info

Tip

Check the command delete-all, by default command names are generated from the function name, replacing _ with -.

Test it:

// Check the command create
$ python main.py create Camila

Creating user: Camila

// Now test the command delete
$ python main.py delete Camila

# Are you sure you want to delete the user? [y/N]: $ y

Deleting user: Camila

$ python main.py delete Wade

# Are you sure you want to delete the user? [y/N]: $ n

Operation cancelled

// And finally, the command delete-all
// Notice it doesn't have CLI arguments, only a CLI option

$ python main.py delete-all

# Are you sure you want to delete ALL users? [y/N]: $ y

Deleting all users

$ python main.py delete-all

# Are you sure you want to delete ALL users? [y/N]: $ n

Operation cancelled

// And if you pass the --force CLI option, it doesn't need to confirm

$ python main.py delete-all --force

Deleting all users

// And init that doesn't take any CLI parameter
$ python main.py init

Initializing user database
You can ask questions about Typer. Try:
How can I terminate a program?
How to launch applications?
How to add help to CLI argument?