questionary
Questionary is a Python library for effortlessly building elegant command line user prompts. It simplifies querying users for input in CLI applications, offering various question types like text, password, select, checkbox, and confirmation prompts. As of its current version 2.1.1, it is actively maintained with regular updates.
Warnings
- breaking Between versions 1.6.0 and 1.8.0, the `value` parameter in `Choice` objects began to be implicitly type-cast to `str` upon selection. Applications expecting non-string types (e.g., `int`) to be returned from `select` or `checkbox` prompts may encounter `TypeError` or incorrect logic.
- breaking Support for Python 3.6 and 3.7 was officially deprecated with the release of version 2.0.0. Projects using these older Python versions should upgrade to Python 3.8 or newer.
- gotcha The `checkbox()` prompt does not support the `validate` argument. Attempts to pass a `Validator` or validation function to `checkbox()` will result in an error or unexpected behavior.
- gotcha Pressing `Ctrl+C` (KeyboardInterrupt) during a prompt will cause `questionary.ask()` methods to return `None` instead of raising an exception. This needs to be explicitly handled in your code if you want to differentiate between user cancellation and a valid answer.
- gotcha There are two main ways to ask multiple questions: `questionary.form()` which takes keyword arguments where values are `Question` instances, and `questionary.prompt()` which takes a list of question dictionaries. Mixing these patterns or using the wrong input format for the respective function can lead to errors.
Install
-
pip install questionary
Imports
- questionary
import questionary
- Choice
from questionary import Choice
- Validator, ValidationError
from questionary import Validator, ValidationError
- prompt
from questionary import prompt
Quickstart
import questionary
def main():
name = questionary.text("What's your name?").ask()
if name is None: # User pressed Ctrl+C
print("Operation cancelled.")
return
choice = questionary.select(
"What do you want to do?",
choices=['Order a pizza', 'Make a reservation', 'Ask for opening hours']
).ask()
if choice is None:
print("Operation cancelled.")
return
print(f"Hello, {name}!")
print(f"You chose: {choice}")
if __name__ == "__main__":
main()