Python library to build pretty command line user prompts with interactive forms and validation
Overall
score
96%
Intelligent text input with completion support including word completion for predefined choices and file system path completion with filtering options.
Text input with intelligent completion from a predefined list of choices, supporting fuzzy matching and metadata display.
def autocomplete(message: str, choices: List[str], default: str = "",
qmark: str = "?", completer: Optional[Completer] = None,
meta_information: Optional[Dict[str, Any]] = None,
ignore_case: bool = True, match_middle: bool = True,
complete_style: CompleteStyle = CompleteStyle.COLUMN,
validate: Any = None, style: Optional[Style] = None,
**kwargs) -> Question:
"""
Create an autocomplete text input prompt.
Args:
message: The question/prompt text to display
choices: List of possible completion choices
default: Default value pre-filled in input
qmark: Question prefix symbol (default "?")
completer: Custom completer instance (overrides choices)
meta_information: Dict mapping choices to metadata descriptions
ignore_case: Case-insensitive matching
match_middle: Allow matching anywhere in choice text
complete_style: Completion display style (COLUMN, MULTI_COLUMN, READLINE)
validate: Validator function or Validator instance
style: Custom styling configuration
**kwargs: Additional prompt_toolkit arguments
Returns:
Question instance ready for execution
"""File and directory path input with intelligent filesystem completion, filtering, and validation.
def path(message: str, default: Union[Path, str] = "", qmark: str = "?",
validate: Any = None, completer: Optional[Completer] = None,
style: Optional[Style] = None, only_directories: bool = False,
get_paths: Optional[Callable[[], List[str]]] = None,
file_filter: Optional[Callable[[str], bool]] = None,
complete_style: CompleteStyle = CompleteStyle.MULTI_COLUMN,
**kwargs) -> Question:
"""
Create a file/directory path input prompt with completion.
Args:
message: The question/prompt text to display
default: Default path value
qmark: Question prefix symbol (default "?")
validate: Validator function or Validator instance
completer: Custom path completer (overrides built-in)
style: Custom styling configuration
only_directories: Restrict completion to directories only
get_paths: Custom function to provide path suggestions
file_filter: Function to filter displayed files/directories
complete_style: Completion display style
**kwargs: Additional prompt_toolkit arguments
Returns:
Question instance ready for execution
"""Customizable word completion for autocomplete prompts.
class WordCompleter(Completer):
def __init__(self, choices: Union[List[str], Callable[[], List[str]]],
ignore_case: bool = True,
meta_information: Optional[Dict[str, Any]] = None,
match_middle: bool = True) -> None:
"""
Word completion from a list of choices.
Args:
choices: Static list or function returning list of choices
ignore_case: Case-insensitive matching
meta_information: Dict mapping choices to metadata
match_middle: Allow matching anywhere in choice text
"""
def get_completions(self, document: Document,
complete_event: CompleteEvent) -> Iterable[Completion]:
"""
Generate completions for the current document state.
Args:
document: Current input document
complete_event: Completion event details
Yields:
Completion objects with matched text and metadata
"""Advanced path completion with better user experience and filtering options.
class GreatUXPathCompleter(PathCompleter):
def __init__(self, only_directories: bool = False,
get_paths: Optional[Callable[[], List[str]]] = None,
file_filter: Optional[Callable[[str], bool]] = None,
min_input_len: int = 0, expanduser: bool = False) -> None:
"""
Enhanced path completion with filtering and UX improvements.
Args:
only_directories: Show only directories in completion
get_paths: Custom function to provide additional paths
file_filter: Function to filter displayed files
min_input_len: Minimum input length to trigger completion
expanduser: Expand ~ to user home directory
"""
def get_completions(self, document: Document,
complete_event: CompleteEvent) -> Iterable[Completion]:
"""
Generate path completions with enhanced filtering.
Args:
document: Current input document
complete_event: Completion event details
Yields:
Completion objects for matching paths
"""import questionary
# Simple word completion
language = questionary.autocomplete(
"Choose programming language:",
choices=["Python", "JavaScript", "TypeScript", "Java", "C++", "Go", "Rust"]
).ask()
# With default value
framework = questionary.autocomplete(
"Select framework:",
choices=["Django", "Flask", "FastAPI", "Tornado"],
default="Django"
).ask()import questionary
# Choices with descriptions
database = questionary.autocomplete(
"Select database:",
choices=["postgresql", "mysql", "sqlite", "mongodb"],
meta_information={
"postgresql": "Advanced open-source relational database",
"mysql": "Popular open-source relational database",
"sqlite": "Lightweight embedded database",
"mongodb": "Document-oriented NoSQL database"
}
).ask()import questionary
# Dynamic choices from function
def get_available_ports():
# Could query system for available ports
return ["8000", "8080", "3000", "5000", "9000"]
port = questionary.autocomplete(
"Choose port:",
choices=get_available_ports()
).ask()
# Custom completer
from questionary.prompts.autocomplete import WordCompleter
custom_completer = WordCompleter(
choices=["option1", "option2", "option3"],
ignore_case=True,
match_middle=False
)
result = questionary.autocomplete(
"Enter option:",
choices=[], # Not used when completer is provided
completer=custom_completer
).ask()import questionary
# File path input
config_file = questionary.path("Enter config file path:").ask()
# Directory path only
output_dir = questionary.path(
"Select output directory:",
only_directories=True
).ask()
# With default path
log_file = questionary.path(
"Log file location:",
default="/var/log/app.log"
).ask()import questionary
from pathlib import Path
# Directory-only with validation
def validate_directory(path):
p = Path(path)
if not p.exists():
return f"Directory {path} does not exist"
if not p.is_dir():
return f"{path} is not a directory"
return True
project_dir = questionary.path(
"Select project directory:",
only_directories=True,
validate=validate_directory
).ask()
# File filtering
def python_files_only(filename):
return filename.endswith('.py') or Path(filename).is_dir()
python_file = questionary.path(
"Select Python file:",
file_filter=python_files_only
).ask()
# Custom path suggestions
def get_common_paths():
return ["/home/user/projects", "/opt", "/usr/local"]
path = questionary.path(
"Enter path:",
get_paths=get_common_paths
).ask()import questionary
from prompt_toolkit.completion import CompleteStyle
# Different completion display styles
result = questionary.autocomplete(
"Choose option:",
choices=["very_long_option_name_1", "very_long_option_name_2", "short"],
complete_style=CompleteStyle.MULTI_COLUMN # or COLUMN, READLINE
).ask()import questionary
from questionary import Validator, ValidationError
class EmailValidator(Validator):
def validate(self, document):
text = document.text
if '@' not in text:
raise ValidationError(
message="Please enter a valid email address",
cursor_position=len(text)
)
email = questionary.autocomplete(
"Enter email:",
choices=["user@domain.com", "admin@site.org"],
validate=EmailValidator()
).ask()Install with Tessl CLI
npx tessl i tessl/pypi-questionarydocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10