Skip to content

Ask with Prompt

When you need to ask the user for info interactively you should normally use CLI Options with Prompt, because they allow using the CLI program in a non-interactive way (for example, a Bash script could use it).

But if you absolutely need to ask for interactive information without using a CLI option, you can use typer.prompt():

import typer_cloup as typer


def main():
    person_name = typer.prompt("What's your name?")
    typer.echo(f"Hello {person_name}")


if __name__ == "__main__":
    typer.run(main)

Check it:

$ python main.py

# What's your name?:$ Camila

Hello Camila

Confirm

There's also an alternative to ask for confirmation. Again, if possible, you should use a CLI Option with a confirmation prompt:

import typer_cloup as typer


def main():
    delete = typer.confirm("Are you sure you want to delete it?")
    if not delete:
        typer.echo("Not deleting")
        raise typer.Abort()
    typer.echo("Deleting it!")


if __name__ == "__main__":
    typer.run(main)

Check it:

$ python main.py

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

Deleting it!

// This time cancel it
$ python main.py

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

Not deleting
Aborted!

Confirm or abort

As it's very common to abort if the user doesn't confirm, there's an integrated parameter abort that does it automatically:

import typer_cloup as typer


def main():
    delete = typer.confirm("Are you sure you want to delete it?", abort=True)
    typer.echo("Deleting it!")


if __name__ == "__main__":
    typer.run(main)
$ python main.py

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

Deleting it!

// This time cancel it
$ python main.py

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

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