Calmcode - typer: prompt

Prompt

1 2 3 4 5 6 7 8 9 10

You could also choose to show the user a prompt. This is great if you want the user to confirm that they're passing the correct input. If you wan to use the prompt-feature though, be sure to use an Option. Not an Argument.

Using a prompt in Typer

The basic example is shown in the app below.

import typer
from typing import List
from pathlib import Path

app = typer.Typer(name="demo", add_completion=False, help="This is a demo app.")


@app.command()
def create_db(table: str = typer.Option(..., prompt="What is the name of the table?",
                                        confirmation_prompt=True)):
    """Pretend to make a database"""
    console.print(f"Creating table in database {table}", style="green")

@app.command()
def delete_db(table: str = typer.Option(..., prompt="What is the name of the table?",
                                        confirmation_prompt=True)):
    """Pretend to delete a database"""
    sure = typer.confirm("Are you really really really sure?")
    if sure:
        console.print(f"Deleting table in database {table}", style="red")
    else:
        console.print(f"Back to safety!", style="green")


if __name__ == "__main__":
    app()

You should now notice a prompt pop up when using these commands.

python cli.py create-db
python cli.py delete-db

Note that even if you pass in a table name, the latter command will still check if you're sure.

python cli.py delete-db --table foobar

Pretty Output

If you're interested in learning on how to make terminal output richer, definately check out the rich library. We've got a course on it for rich.