Python port of Inquirer.js providing interactive command-line user interfaces with extensive customization options.
—
Styling, validation, separators, and utility functions for prompt customization and enhanced functionality.
Functions and classes for customizing prompt appearance and creating consistent visual themes.
def get_style(
style: Optional[Dict[str, str]] = None,
style_override: bool = True
) -> InquirerPyStyleParameters:
Returns: InquirerPyStyle object for use with prompts
Style Elements:
style_keys = {
"question": "Question text color/format",
"answer": "User answer color/format",
"pointer": "Selection pointer color/format",
"highlighted": "Highlighted choice color/format",
"selected": "Selected items color/format (checkbox)",
"separator": "Separator line color/format",
"instruction": "Instruction text color/format",
"text": "General text color/format",
"disabled": "Disabled items color/format",
"fuzzy_prompt": "Fuzzy search prompt color/format",
"fuzzy_info": "Fuzzy search info color/format",
"fuzzy_match": "Fuzzy search match highlight"
}Usage Examples:
Basic styling:
from InquirerPy import inquirer
from InquirerPy.utils import get_style
# Create custom style
custom_style = get_style({
"question": "#ff6600 bold",
"answer": "#00aa44 bold",
"pointer": "#ff0066",
"highlighted": "#ff0066 bold",
"instruction": "#888888 italic"
})
# Use with any prompt
name = inquirer.text(
message="Enter name:",
style=custom_style
).execute()Theme-based styling:
# Dark theme
dark_theme = get_style({
"question": "#ffffff bold",
"answer": "#00ff00 bold",
"pointer": "#ffff00",
"highlighted": "#ffff00 bold reverse",
"selected": "#00ffff",
"separator": "#666666",
"instruction": "#cccccc",
"text": "#ffffff"
})
# Light theme
light_theme = get_style({
"question": "#000066 bold",
"answer": "#006600 bold",
"pointer": "#660066",
"highlighted": "#660066 bold reverse",
"selected": "#006666",
"separator": "#999999",
"instruction": "#666666",
"text": "#000000"
})Pre-built validators for common input validation scenarios.
class NumberValidator:
def __init__(
self,
message: str = "Input should be a number",
float_allowed: bool = False
): ...
def validate(self, document) -> None: ...class PathValidator:
def __init__(
self,
message: str = "Input is not a valid path",
is_file: bool = False,
is_dir: bool = False
): ...
def validate(self, document) -> None: ...class EmptyInputValidator:
def __init__(
self,
message: str = "Input cannot be empty"
): ...
def validate(self, document) -> None: ...class PasswordValidator:
def __init__(
self,
length: int = 8,
cap: bool = False,
special: bool = False,
number: bool = False,
message: str = "Password does not meet requirements"
): ...
def validate(self, document) -> None: ...Usage Examples:
Number validation:
from InquirerPy import inquirer
from InquirerPy.validator import NumberValidator
# Integer only
port = inquirer.text(
message="Port number:",
validate=NumberValidator(message="Please enter a valid port number")
).execute()
# Allow floats
price = inquirer.text(
message="Price:",
validate=NumberValidator(
message="Please enter a valid price",
float_allowed=True
)
).execute()Path validation:
from InquirerPy.validator import PathValidator
# File must exist
config_file = inquirer.filepath(
message="Config file:",
validate=PathValidator(
message="File must exist",
is_file=True
)
).execute()
# Directory must exist
output_dir = inquirer.filepath(
message="Output directory:",
validate=PathValidator(
message="Directory must exist",
is_dir=True
)
).execute()Password validation:
from InquirerPy.validator import PasswordValidator
# Complex password requirements
password = inquirer.secret(
message="Create password:",
validate=PasswordValidator(
length=12,
cap=True,
special=True,
number=True,
message="Password must be 12+ chars with uppercase, number, and special character"
)
).execute()Custom validation:
# Custom validator function
def validate_email(email):
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(pattern, email):
return "Please enter a valid email address"
return True
email = inquirer.text(
message="Email address:",
validate=validate_email
).execute()Visual separator for organizing choices in list-based prompts.
class Separator:
def __init__(self, line: str = "---------------") -> None: ...
def __str__(self) -> str: ...Usage Examples:
Basic separators:
from InquirerPy import inquirer
from InquirerPy.separator import Separator
framework = inquirer.select(
message="Choose framework:",
choices=[
"React",
"Vue.js",
"Angular",
Separator(),
"Django",
"Flask",
"FastAPI",
Separator("--- Other ---"),
"Express.js",
"Spring Boot"
]
).execute()Custom separators:
# Different separator styles
choices = [
"Option 1",
"Option 2",
Separator("═" * 20),
"Option 3",
Separator("--- Section B ---"),
"Option 4",
Separator(), # Default dashes
"Option 5"
]
selection = inquirer.select(message="Choose:", choices=choices).execute()Helper functions for display, calculation, and prompt functionality.
def calculate_height(
height: Optional[Union[int, str]],
max_height: Optional[Union[int, str]],
height_offset: int = 2
) -> Tuple[Optional[int], int]Calculates optimal prompt height and max height based on terminal size with offset adjustment.
def patched_print(*values) -> NoneThread-safe printing function that works correctly with prompt-toolkit applications.
def color_print(
formatted_text: List[Tuple[str, str]],
style: Optional[Dict[str, str]] = None
) -> NonePrints colored text using prompt-toolkit formatted text and styling.
Parameters:
Usage Examples:
Colored output:
from InquirerPy.utils import color_print
# Print colored messages using formatted text
color_print([("red", "Error: "), ("", "Something went wrong")])
color_print([("green", "Success: "), ("", "Operation completed")])
# With custom styling
color_print(
[("class:info", "Information: "), ("class:detail", "Process finished")],
style={"info": "blue bold", "detail": "cyan"}
)Safe printing in prompts:
from InquirerPy.utils import patched_print
# Use instead of regular print() when running prompts
def custom_prompt_with_output():
patched_print("Starting survey...")
result = inquirer.text(message="Name:").execute()
patched_print(f"Hello {result}!")
return resultCustom exceptions for error handling and prompt validation.
class InvalidArgument(Exception):
def __init__(self, message: str = "invalid argument"): ...class RequiredKeyNotFound(Exception):
def __init__(self, message: str = "required key not found"): ...Usage Example:
from InquirerPy import prompt
from InquirerPy.exceptions import InvalidArgument, RequiredKeyNotFound
try:
questions = [
{"type": "invalid_type", "message": "Test"} # Invalid type
]
result = prompt(questions)
except RequiredKeyNotFound:
print("Question missing required fields")
except InvalidArgument as e:
print(f"Invalid question configuration: {e}")Pre-defined Unicode symbols and constants for consistent visual appearance.
# Available constants
INQUIRERPY_KEYBOARD_INTERRUPT = "INQUIRERPY_KEYBOARD_INTERRUPT"
INQUIRERPY_POINTER_SEQUENCE = "❯" # Default pointer symbol
INQUIRERPY_FILL_CIRCLE_SEQUENCE = "●" # Filled checkbox symbol
INQUIRERPY_EMPTY_CIRCLE_SEQUENCE = "○" # Empty checkbox symbol
INQUIRERPY_QMARK_SEQUENCE = "?" # Question mark symbolUsage Example:
from InquirerPy import inquirer
from InquirerPy.enum import (
INQUIRERPY_POINTER_SEQUENCE,
INQUIRERPY_FILL_CIRCLE_SEQUENCE,
INQUIRERPY_EMPTY_CIRCLE_SEQUENCE
)
# Custom symbols for checkbox
features = inquirer.checkbox(
message="Select features:",
choices=["Auth", "DB", "API"],
pointer="→",
enabled_symbol="✓",
disabled_symbol="✗"
).execute()Pre-defined spinner patterns for prompts with loading states.
class SPINNERS(NamedTuple):
dots: List[str] # ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
dots2: List[str] # ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"]
line: List[str] # ["-", "\\", "|", "/"]
line2: List[str] # ["⠂", "-", "–", "—", "–", "-"]
pipe: List[str] # ["┤", "┘", "┴", "└", "├", "┌", "┬", "┐"]
star: List[str] # ["✶", "✸", "✹", "✺", "✹", "✷"]
star2: List[str] # ["+", "x", "*"]
flip: List[str] # ["_", "_", "_", "-", "`", "`", "'", "´", "-", "_", "_", "_"]
hamburger: List[str] # ["☱", "☲", "☴"]
grow_vertical: List[str] # ["▁", "▃", "▄", "▅", "▆", "▇", "▆", "▅", "▄", "▃"]
grow_horizontal: List[str] # ["▏", "▎", "▍", "▌", "▋", "▊", "▉", "▊", "▋", "▌", "▍", "▎"]
box_bounce: List[str] # ["▖", "▘", "▝", "▗"]
triangle: List[str] # ["◢", "◣", "◤", "◥"]
arc: List[str] # ["◜", "◠", "◝", "◞", "◡", "◟"]Usage Example:
from InquirerPy import inquirer
from InquirerPy.containers import SPINNERS
# Use predefined spinner patterns in prompts with async operations
result = inquirer.select(
message="Loading options...",
choices=async_load_choices, # Async function
spinner_pattern=SPINNERS.dots
).execute()Auto-completion class for file system path input.
class FilePathCompleter(Completer):
def __init__(
self,
only_directories: bool = False,
only_files: bool = False
): ...Parameters:
Usage Example:
from InquirerPy.prompts.filepath import FilePathCompleter
from InquirerPy import inquirer
# Custom completer for specific directory
custom_completer = FilePathCompleter(only_directories=True)
path = inquirer.text(
message="Enter directory path:",
completer=custom_completer
).execute()Common type aliases used throughout the InquirerPy API for flexible parameter handling.
# Message types - strings or functions returning strings
InquirerPyMessage = Union[str, Callable[..., str]]
# Default values - any type or functions returning any type
InquirerPyDefault = Union[Any, Callable[..., Any]]
# Choice lists - static lists or functions returning lists
InquirerPyListChoices = Union[List[Any], Callable[..., List[Any]]]
# Validation - Validator objects or boolean functions
InquirerPyValidate = Union[Validator, Callable[[Any], bool]]
# Keybindings - mapping of actions to key combinations
InquirerPyKeybindings = Dict[str, List[str]]
# Session results - question names/indices mapped to answers
InquirerPySessionResult = Dict[Union[str, int], Any]
# Question definitions - single question or list of questions
InquirerPyQuestions = Union[List[Dict[str, Any]], Dict[str, Any]]
# Style configuration
InquirerPyStyle = NamedTuple("InquirerPyStyle", [("style", Style)])Install with Tessl CLI
npx tessl i tessl/pypi-inquirerpy