What it is
PyInquirer is a Python library that enables the creation of beautiful, interactive command-line interfaces with prompts, lists, checkboxes, and other input types inspired by Inquirer.js.
PyInquirer provides different types of prompts such as input, confirm, list, checkbox, password, and rawlist. It supports nested questions, validation, and default values, enabling interactive CLI experiences.
Installation
pip install PyInquirerGetting started
The smallest useful thing you can do with it, and what each part means.
from PyInquirer import prompt
questions = [{
'type': 'input',
'name': 'username',
'message': 'Enter your username:'
}]
answers = prompt(questions)
print(answers['username'])from PyInquirer import prompt
questions = [{
'type': 'confirm',
'name': 'continue',
'message': 'Do you want to continue?',
'default': True
}]
answers = prompt(questions)
print(answers['continue'])Advanced usage
Where the library earns its place over a simpler alternative.
from PyInquirer import prompt
questions = [{
'type': 'list',
'name': 'color',
'message': 'Pick a color:',
'choices': ['Red', 'Green', 'Blue']
}]
answers = prompt(questions)
print(answers['color'])from PyInquirer import prompt
questions = [{
'type': 'checkbox',
'name': 'features',
'message': 'Select features:',
'choices': [
{'name': 'Feature A'},
{'name': 'Feature B'},
{'name': 'Feature C'}
]
}]
answers = prompt(questions)
print(answers['features'])from PyInquirer import prompt
questions = [{
'type': 'input',
'name': 'age',
'message': 'Enter your age:',
'validate': lambda val: val.isdigit() or 'Please enter a number'
}]
answers = prompt(questions)
print(answers['age'])from PyInquirer import prompt
questions = [{
'type': 'input',
'name': 'name',
'message': 'What is your name?'
}, {
'type': 'confirm',
'name': 'confirm',
'message': 'Is that correct?'
}]
answers = prompt(questions)
print(answers)Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- EOFError
- Occurs when input stream is closed unexpectedly. Ensure the terminal is interactive and supports input.
- KeyboardInterrupt
- Handle user interruption gracefully by wrapping prompts in try/except blocks.
Best practices
- Use descriptive messages for prompts to improve user experience.
- Validate inputs to avoid invalid data.
- Group related questions for clarity.
- Use defaults when appropriate to simplify the workflow.
- Keep the interface simple and intuitive for command-line users.
Background
Why it exists, and what it was reacting to.
PyInquirer was created as a Python adaptation of the popular Inquirer.js library for Node.js. It allows developers to easily build interactive CLIs, making terminal-based tools more user-friendly and visually appealing.
