How to Create Interactive CLI Prompts in Python with questionary

Build mock interactive command-line prompts using questionary's select and text widgets with graceful handling of user cancellation.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 14 views 0 copies

Requires third-party packages — install first
pip install questionary

Python code

23 lines
Python 3.9+
import questionary

def main():
    # Mock interactive prompts using questionary's select and text
    choice = questionary.select(
        "What is your favorite programming language?",
        choices=["Python", "JavaScript", "Go", "Rust"]
    ).ask()

    # ask() returns None if user cancels; handle gracefully
    if choice is None:
        print("No selection made.")
        return

    name = questionary.text("What is your name?").ask()
    if name is None:
        print("Name entry cancelled.")
        return

    print(f"Hello {name}, you selected {choice}!")

if __name__ == "__main__":
    main()

Output

stdout
? What is your favorite programming language? Python
? What is your name? Ada
Hello Ada, you selected Python!

How it works

The questionary.select and questionary.text methods display interactive prompts in the terminal. Both return the selected value or typed input when the user confirms, but return None if the user cancels with Ctrl+C or Esc. Checking for None after each .ask() call prevents crashes and lets you handle the cancellation gracefully. The if __name__ == "__main__" guard ensures the prompt logic only runs when executed directly. The library uses ANSI escape codes to render menus and handle keyboard navigation in real time.

Common mistakes

  • Forgetting to check if `.ask()` returns None, which crashes on user cancellation
  • Using `input()` instead of questionary and trying to rebuild arrow-key navigation from scratch
  • Assuming the terminal supports ANSI colors when running in a non-interactive environment like CI

Variations

  1. Use `questionary.checkbox` for multi-select choices instead of single-select
  2. Add `qmark` and `instruction` parameters to customize the prompt styling

Real-world use cases

  • Interactive CLI tools that ask users to choose configuration options during setup or initialization.
  • DevOps scripts that prompt operators for environment names or deployment targets before running a command.
  • Data migration tools that let users select which tables or fields to process from the terminal.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Modern tooling

Related tutorials and quizzes for this topic.