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.
pip install questionary
Python code
23 linesimport 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
? 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
- Use `questionary.checkbox` for multi-select choices instead of single-select
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.