Interactive command line user interfaces for Python applications with various prompt types including input, password, lists, checkboxes, and confirmations
npx @tessl/cli install tessl/pypi-pyinquirer@1.0.0A Python module for creating interactive command line user interfaces based on Inquirer.js. PyInquirer provides a comprehensive set of prompt types for collecting user input with support for validation, filtering, conditional prompts, and custom styling.
pip install PyInquirerprompt_toolkit==1.0.14, Pygments>=2.2.0, regex>=2016.11.21from PyInquirer import prompt, print_jsonFor styling and validation:
from PyInquirer import style_from_dict, Token, Validator, ValidationError, SeparatorFor version information:
from PyInquirer import __version__from PyInquirer import prompt, print_json
questions = [
{
'type': 'input',
'name': 'first_name',
'message': 'What\'s your first name?',
},
{
'type': 'confirm',
'name': 'continue',
'message': 'Do you want to continue?',
'default': True
},
{
'type': 'list',
'name': 'size',
'message': 'What size do you need?',
'choices': ['Large', 'Medium', 'Small'],
'filter': lambda val: val.lower()
}
]
answers = prompt(questions)
print_json(answers) # Pretty print the resultsPyInquirer follows a question-based approach where prompts are defined as dictionaries with specific properties. The main workflow is:
prompt() function which displays interactive UIprint_json() for output formattingThe library supports conditional prompts, validation, filtering, and custom styling through a modular design that separates prompt types, validation logic, and presentation concerns.
The core function for displaying interactive prompts to users. All prompt types are accessed through this single function by specifying the type parameter in question dictionaries.
def prompt(questions, answers=None, **kwargs):
"""
Display interactive prompts to collect user input.
Parameters:
- questions: list or dict, list of question dictionaries or single question
- answers: dict, optional existing answers to merge with new responses
- patch_stdout: bool, whether to patch stdout (default: False)
- return_asyncio_coroutine: bool, return asyncio coroutine (default: False)
- true_color: bool, enable true color support (default: False)
- refresh_interval: int, refresh interval in milliseconds (default: 0)
- eventloop: custom event loop (default: None)
- keyboard_interrupt_msg: str, message on Ctrl+C (default: 'Cancelled by user')
Returns:
dict: Dictionary of answers keyed by question names
"""Basic text input with optional validation and filtering. Supports default values, custom validation functions, and input processing.
# Question format for input prompts
{
'type': 'input',
'name': str, # Key for storing answer
'message': str, # Question text to display
'default': str, # Default value (optional)
'validate': callable, # Validation function or Validator class (optional)
'filter': callable, # Function to process the answer (optional)
'when': callable, # Function to conditionally show question (optional)
'qmark': str, # Custom question mark symbol (default: '?') (optional)
'style': object # Custom style object (default: default_style) (optional)
}Usage example:
questions = [
{
'type': 'input',
'name': 'phone',
'message': 'What\'s your phone number?',
'validate': lambda val: len(val) >= 10 or 'Phone number must be at least 10 digits'
}
]Key bindings:
Text input: Type characters normallyEnter: Submit input (if validation passes)Ctrl+C: Cancel and exit←/→ (Arrow keys): Move cursor within inputBackspace/Delete: Delete charactersMasked password input that extends input prompts with hidden character display.
# Question format for password prompts
{
'type': 'password',
'name': str, # Key for storing answer
'message': str, # Question text to display
'default': str, # Default value (optional)
'validate': callable, # Validation function (optional)
'filter': callable, # Function to process answer (optional)
'when': callable, # Conditional display function (optional)
'qmark': str, # Custom question mark symbol (default: '?') (optional)
'style': object # Custom style object (default: default_style) (optional)
}Key bindings:
Text input: Type characters (displayed as masked)Enter: Submit password (if validation passes)Ctrl+C: Cancel and exit←/→ (Arrow keys): Move cursor within inputBackspace/Delete: Delete charactersYes/No confirmation prompts with customizable default values.
# Question format for confirm prompts
{
'type': 'confirm',
'name': str, # Key for storing answer
'message': str, # Question text to display
'default': bool, # Default value (True or False, optional)
'when': callable, # Conditional display function (optional)
'qmark': str, # Custom question mark symbol (default: '?') (optional)
'style': object # Custom style object (default: default_style) (optional)
}Key bindings:
y/Y: Select Yesn/N: Select NoEnter: Use default value (if set)Ctrl+C: Cancel and exitSingle-choice selection from a list with arrow key navigation.
# Question format for list prompts
{
'type': 'list',
'name': str, # Key for storing answer
'message': str, # Question text to display
'choices': list, # List of choice strings or choice objects
'default': any, # Default choice index or value (optional)
'filter': callable, # Function to process selected value (optional)
'when': callable, # Conditional display function (optional)
'qmark': str, # Custom question mark symbol (default: '?') (optional)
'style': object, # Custom style object (default: default_style) (optional)
'pageSize': int # Number of choices to display per page (optional)
}
# Choice object format
{
'name': str, # Display name
'value': any, # Actual value (defaults to name if not specified)
'disabled': bool or str # Disable choice with optional reason text
}Key bindings:
↑/↓ (Arrow keys): Navigate up/down through choicesEnter: Select current choiceCtrl+C: Cancel and exitNumbered list selection where users type the number corresponding to their choice.
# Question format for rawlist prompts
{
'type': 'rawlist',
'name': str, # Key for storing answer
'message': str, # Question text to display
'choices': list, # List of choice strings or choice objects
'default': int, # Default choice index (optional)
'filter': callable, # Function to process selected value (optional)
'when': callable, # Conditional display function (optional)
'qmark': str, # Custom question mark symbol (default: '?') (optional)
'style': object # Custom style object (default: default_style) (optional)
}Key bindings:
1-9 (Number keys): Select choice by number (max 9 choices)Enter: Confirm selectionCtrl+C: Cancel and exitLimitations:
Multiple choice selection with spacebar to toggle individual options.
# Question format for checkbox prompts
{
'type': 'checkbox',
'name': str, # Key for storing answer
'message': str, # Question text to display
'choices': list, # List of choice strings or choice objects
'default': list, # List of default selected values (optional)
'validate': callable, # Validation function for selected items (optional)
'filter': callable, # Function to process selected values (optional)
'when': callable, # Conditional display function (optional)
'qmark': str, # Custom question mark symbol (default: '?') (optional)
'style': object # Custom style object (default: default_style) (optional)
}
# Choice object format with checkbox-specific properties
{
'name': str, # Display name
'value': any, # Actual value (defaults to name)
'checked': bool, # Pre-select this choice (default: False)
'disabled': bool or str # Disable choice with optional reason text
}Key bindings:
↑/↓ (Arrow keys): Navigate up/down through choicesSpace: Toggle selection of current choicea: Toggle all (select all/deselect all)i: Invert selection (selected becomes unselected and vice versa)Enter: Confirm final selectionCtrl+C: Cancel and exitCompact single-choice prompt that expands to show all options. Users type single-character shortcuts to select options.
# Question format for expand prompts
{
'type': 'expand',
'name': str, # Key for storing answer
'message': str, # Question text to display
'choices': list, # List of choice objects with key shortcuts
'default': str, # Default choice key (defaults to 'h' for help)
'when': callable, # Conditional display function (optional)
'qmark': str, # Custom question mark symbol (default: '?') (optional)
'style': object # Custom style object (default: default_style) (optional)
}
# Choice object format for expand prompts
{
'key': str, # Single character shortcut (lowercase)
'name': str, # Display name and description
'value': any # Actual value to return
}Key bindings:
<letter> (Choice key): Select choice by typing its key letterh: Show help (expand all options)Enter: Confirm current selectionCtrl+C: Cancel and exitUsage example:
{
'type': 'expand',
'name': 'conflict',
'message': 'Conflict on file.js:',
'choices': [
{'key': 'y', 'name': 'Overwrite', 'value': 'overwrite'},
{'key': 'a', 'name': 'Overwrite this one and all next', 'value': 'overwrite_all'},
{'key': 'd', 'name': 'Show diff', 'value': 'diff'}
]
}Opens external editor for multi-line text input. Supports various editors and configuration options.
# Question format for editor prompts
{
'type': 'editor',
'name': str, # Key for storing answer
'message': str, # Question text to display
'default': str, # Default text to edit (optional)
'validate': callable, # Validation function (optional)
'filter': callable, # Function to process answer (optional)
'eargs': dict, # Editor configuration (optional)
'when': callable, # Conditional display function (optional)
'qmark': str, # Custom question mark symbol (default: '?') (optional)
'style': object # Custom style object (default: default_style) (optional)
}
# Editor arguments (eargs) format
{
'editor': str, # Editor command/path (optional, default detected from environment)
'env': dict, # Environment variables (optional)
'ext': str, # File extension for temp file (optional, default: '.txt')
'save': bool, # Whether to save file (optional, default: True)
'filename': str # Edit existing file instead of temp file (optional)
}Helper functions for output formatting and data processing.
def print_json(data):
"""
Pretty print JSON data with syntax highlighting.
Parameters:
- data: any, data to format and print as JSON
"""
def format_json(data):
"""
Format data as indented JSON string.
Parameters:
- data: any, data to format
Returns:
str: Formatted JSON string
"""
def colorize_json(data):
"""
Add syntax highlighting to JSON data.
Parameters:
- data: any, data to colorize
Returns:
str: JSON string with ANSI color codes
"""
def here(path):
"""
Get absolute path relative to package directory.
Parameters:
- path: str, relative path from package root
Returns:
str: Absolute path
"""
def yellow(message):
"""
Print message in yellow color.
Parameters:
- message: str, text to print in yellow
"""
def blue(message):
"""
Print message in blue color.
Parameters:
- message: str, text to print in blue
"""
def gray(message):
"""
Print message in gray color.
Parameters:
- message: str, text to print in gray
"""
# Package version constant
__version__: str # Package version string (e.g., '1.0.2')Visual separator for grouping choices in list-based prompts.
class Separator:
"""
Visual separator for choice groups.
Parameters:
- line: str, custom separator line (default: 15 dashes)
"""
def __init__(self, line=None):
"""
Create separator with optional custom line.
Parameters:
- line: str, separator line text (optional)
"""
def __str__(self):
"""
Returns:
str: The separator line string
"""Usage example:
from PyInquirer import Separator
choices = [
'Option 1',
'Option 2',
Separator(),
'Option 3',
'Option 4',
Separator('= Advanced Options ='),
'Advanced Option 1'
]Input validation support with custom validators and error handling.
class Validator:
"""
Base class for input validators.
Re-exported from prompt_toolkit.validation.
"""
def validate(self, document):
"""
Validate input document.
Parameters:
- document: Document object with text property
Raises:
ValidationError: If validation fails
"""
class ValidationError(Exception):
"""
Exception raised for validation failures.
Re-exported from prompt_toolkit.validation.
Parameters:
- message: str, error message to display
- cursor_position: int, cursor position for error highlight (optional)
"""Custom validator example:
from PyInquirer import Validator, ValidationError
class NumberValidator(Validator):
def validate(self, document):
try:
int(document.text)
except ValueError:
raise ValidationError(
message='Please enter a valid number',
cursor_position=len(document.text)
)Customizable styling for prompts using token-based theming.
def style_from_dict(style_dict):
"""
Create style from dictionary of token mappings.
Re-exported from prompt_toolkit.styles.
Parameters:
- style_dict: dict, mapping of Token types to color/style strings
Returns:
Style object for use with prompts
"""
# Available style tokens
class Token:
"""
Style token types for customizing prompt appearance.
Re-exported from prompt_toolkit.token.
"""
Separator = None # Separator line color
QuestionMark = None # Question mark (?) color
Selected = None # Selected item color
Pointer = None # Arrow pointer color
Instruction = None # Instruction text color
Answer = None # Answer text color
Question = None # Question text color
SetCursorPosition = None # Cursor positioning token
# Default style object
default_style: object # Default orange-themed style with mappings:
# Token.Separator: '#6C6C6C'
# Token.QuestionMark: '#5F819D'
# Token.Selected: ''
# Token.Pointer: '#FF9D00 bold'
# Token.Instruction: ''
# Token.Answer: '#FF9D00 bold'
# Token.Question: 'bold'Custom styling example:
from PyInquirer import style_from_dict, Token, prompt
custom_style = style_from_dict({
Token.QuestionMark: '#E91E63 bold',
Token.Selected: '#673AB7 bold',
Token.Answer: '#2196f3 bold',
Token.Question: 'bold',
})
answers = prompt(questions, style=custom_style)Custom exceptions for error handling and parameter validation.
class PromptParameterException(ValueError):
"""
Exception raised when required prompt parameters are missing.
Parameters:
- message: str, name of missing parameter
- errors: any, additional error information (optional)
"""
def __init__(self, message, errors=None):
"""
Create exception for missing parameter.
Parameters:
- message: str, parameter name that is missing
- errors: any, additional error context (optional)
"""
class EditorArgumentsError(Exception):
"""
Exception raised for invalid editor configuration arguments.
Used specifically by editor prompts when eargs parameters are invalid.
"""questions = [
{
'type': 'confirm',
'name': 'has_comments',
'message': 'Do you have any comments?'
},
{
'type': 'input',
'name': 'comments',
'message': 'Please enter your comments:',
'when': lambda answers: answers.get('has_comments', False)
}
]def get_size_choices(answers):
if answers.get('category') == 'clothing':
return ['XS', 'S', 'M', 'L', 'XL']
else:
return ['Small', 'Medium', 'Large']
questions = [
{
'type': 'list',
'name': 'category',
'message': 'Select category:',
'choices': ['clothing', 'electronics']
},
{
'type': 'list',
'name': 'size',
'message': 'Select size:',
'choices': get_size_choices
}
]questions = [
{
'type': 'input',
'name': 'quantity',
'message': 'How many items?',
'validate': lambda val: val.isdigit() or 'Please enter a valid number',
'filter': lambda val: int(val) # Convert string to integer
}
]