Skip to content

Ask with Prompt

When you need to ask the user for info interactively you should normally use *CLI Option*s 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


def main():
    person_name = typer.prompt("What's your name?")
    print(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


def main():
    delete = typer.confirm("Are you sure you want to delete it?")
    if not delete:
        print("Not deleting")
        raise typer.Abort()
    print("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


def main():
    delete = typer.confirm("Are you sure you want to delete it?", abort=True)
    print("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!

Prompt with Rich

If you installed Rich as described in Printing and Colors, you can use Rich to prompt the user for input:

import typer
from rich.prompt import Prompt


def main():
    name = Prompt.ask("Enter your name :sunglasses:")
    print(f"Hey there {name}!")


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

And when you run it, it will look like:

$ python main.py

# Enter your name 😎:$ Morty

Hello Morty