### Install Development Dependencies Source: https://github.com/magmax/python-inquirer/blob/main/docs/contributing.md Install the package with development requirements using Poetry. ```sh poetry install ``` -------------------------------- ### Install Project with Development Requirements Source: https://github.com/magmax/python-inquirer/blob/main/CONTRIBUTING.md Use this command to install the project and its development dependencies using Poetry. ```sh $ poetry install ``` -------------------------------- ### Run Interactive Python Session Source: https://github.com/magmax/python-inquirer/blob/main/docs/contributing.md Start an interactive Python session after installing dependencies. ```sh poetry run python ``` -------------------------------- ### Install inquirer with pip Source: https://github.com/magmax/python-inquirer/blob/main/docs/installation.md Use this command to install the inquirer library using pip. ```bash pip install inquirer ``` -------------------------------- ### Install Pre-commit Git Hooks Source: https://github.com/magmax/python-inquirer/blob/main/docs/contributing.md Install pre-commit as a Git hook for linting and code formatting checks before committing. ```sh nox --session=pre-commit -- install ``` -------------------------------- ### Install Pre-commit Git Hooks with Nox Source: https://github.com/magmax/python-inquirer/blob/main/CONTRIBUTING.md Set up pre-commit as a Git hook to run linting and code formatting checks before committing. ```sh $ nox --session=pre-commit -- install ``` -------------------------------- ### List Prompt Example Source: https://github.com/magmax/python-inquirer/blob/main/README.md Presents a list of choices for single selection. The 'carousel' argument can be set to True for circular navigation. ```python import inquirer questions = [ inquirer.List('size', message="What size do you need?", choices=['Jumbo', 'Large', 'Standard', 'Medium', 'Small', 'Micro'], ), ] answers = inquirer.prompt(questions) ``` -------------------------------- ### Text Prompt Example Source: https://github.com/magmax/python-inquirer/blob/main/README.md Demonstrates how to ask for text input, including basic validation for a phone number using regex. Ensure the 're' module is imported. ```python import re import inquirer questions = [ inquirer.Text('name', message="What's your name"), inquirer.Text('surname', message="What's your surname"), inquirer.Text('phone', message="What's your phone number", validate=lambda _, x: re.match('\+?\d[\d ]+\d', x), ) ] answers = inquirer.prompt(questions) ``` -------------------------------- ### Python inquirer usage example Source: https://github.com/magmax/python-inquirer/blob/main/docs/installation.md Demonstrates how to define and prompt users with various question types including text, password, checkbox, and confirmation. ```python import inquirer if __name__ == "__main__": questions = [ inquirer.Text("user", message="Please enter your github username", validate=lambda _, x: x != "."), inquirer.Password("password", message="Please enter your password"), inquirer.Text("repo", message="Please enter the repo name", default="default"), inquirer.Checkbox( "topics", message="Please define your type of project?", choices=["common", "backend", "frontend"], ), inquirer.Text( "organization", message=( "If this is a repo from a organization please enter the organization name," " if not just leave this blank" ), ), inquirer.Confirm( "correct", message="This will delete all your current labels and create a new ones. Continue?", default=False, ), ] answers = inquirer.prompt(questions) print(answers) ``` -------------------------------- ### Run Interactive Python Session Source: https://github.com/magmax/python-inquirer/blob/main/CONTRIBUTING.md Start an interactive Python session within the project's environment managed by Poetry. ```sh $ poetry run python ``` -------------------------------- ### Editor Prompt Example Source: https://github.com/magmax/python-inquirer/blob/main/README.md Use the Editor prompt for multi-line text input. It opens an external editor. The environment variables $VISUAL and $EDITOR can configure the editor, with fallbacks to vim, emacs, or nano. ```python import inquirer questions = [ inquirer.Editor('long_text', message="Provide long text") ] answers = inquirer.prompt(questions) ``` -------------------------------- ### Path Prompt Example Source: https://github.com/magmax/python-inquirer/blob/main/README.md A specialized Text prompt for handling file or directory paths with built-in validation. Use `path_type=inquirer.Path.DIRECTORY` for directories or `path_type=inquirer.Path.FILE` for files. ```python import inquirer questions = [ inquirer.Path('log_file', message="Where logs should be located?", path_type=inquirer.Path.DIRECTORY, ), ] answers = inquirer.prompt(questions) ``` -------------------------------- ### Checkbox Prompt Example Source: https://github.com/magmax/python-inquirer/blob/main/README.md Allows multiple selections from a list of choices. Options include 'carousel' for circular navigation and 'locked' to prevent deselection of specific choices. ```python import inquirer questions = [ inquirer.Checkbox('interests', message="What are you interested in?", choices=['Computers', 'Books', 'Science', 'Nature', 'Fantasy', 'History'], ), ] answers = inquirer.prompt(questions) ``` -------------------------------- ### Text Input with Validation Source: https://github.com/magmax/python-inquirer/blob/main/docs/examples.md Demonstrates how to use inquirer.Text for user input and provides a custom validation function for phone numbers. Ensure the 'inquirer' library is installed. ```python import os import re import sys from pprint import pprint sys.path.append(os.path.realpath(".")) import inquirer # noqa def phone_validation(answers, current): if not re.match(r"\+?\d[\d ]+\d", current): raise inquirer.errors.ValidationError("", reason="I don't like your phone number!") return True questions = [ inquirer.Text("name", message="What's your name?"), inquirer.Text("surname", message="What's your surname, {name}?"), inquirer.Text( "phone", message="What's your phone number", validate=phone_validation, ), ] answers = inquirer.prompt(questions) pprint(answers) ``` -------------------------------- ### Define Text Questions with Formatted Messages Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md Use the `Text` question type to get string input. Messages can be formatted using previous answers. ```python questions = [ Text(name='name', message="What's your name?"), Text(name='surname', message="What's your surname, {name}") ] ``` -------------------------------- ### Custom ConsoleRender for Reusable Theming Source: https://context7.com/magmax/python-inquirer/llms.txt Instantiate a custom ConsoleRender with a theme for consistent styling across multiple prompts. Pass the renderer instance to `prompt()` or shortcut functions. ```python from inquirer.render.console import ConsoleRender from inquirer.themes import BlueComposure import inquirer render = ConsoleRender(theme=BlueComposure()) questions = [ inquirer.Text("project", message="Project name?"), inquirer.Confirm("private", message="Private repository?", default=False), ] # Reuse the same render instance answers = inquirer.prompt(questions, render=render) print(answers) # Single prompt reusing the same renderer username = inquirer.text(message="Owner username?", render=render) print(username) ``` -------------------------------- ### Path Shortcut Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Shortcut function to create a path input question. ```APIDOC ## inquirer.shortcuts.path(message, render=None, **kwargs) ``` -------------------------------- ### Run Full Test Suite with Nox Source: https://github.com/magmax/python-inquirer/blob/main/docs/contributing.md Execute all available Nox sessions to run the full test suite. ```sh nox ``` -------------------------------- ### Use Shortcut Functions for Single Prompts Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md Utilize shortcut functions like `inquirer.text`, `inquirer.password`, `inquirer.list_input`, and `inquirer.confirm` for quick, single-prompt interactions. ```python text = inquirer.text(message="Enter your username") password = inquirer.password(message='Please enter your password'), choice = inquirer.list_input("Public or private?", choices=['public', 'private']) correct = inquirer.confirm("This will delete all your current labels and create a new ones. Continue?", default=False) ``` -------------------------------- ### List Available Nox Sessions Source: https://github.com/magmax/python-inquirer/blob/main/docs/contributing.md Display a list of all available Nox sessions for the project. ```sh nox --list-sessions ``` -------------------------------- ### Loading Theme from Dictionary Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Loads a custom theme from a dictionary, allowing detailed customization of prompt elements. ```APIDOC ## inquirer.themes.load_theme_from_dict(dict_theme) Load a theme from a dict. Expected format: : ```pycon >>> { ... "Question": { ... "mark_color": "yellow", ... "brackets_color": "normal", ... ... ... }, ... "List": { ... "selection_color": "bold_blue", ... "selection_cursor": "->" ... } ... } ``` Color values should be string representing valid blessings.Terminal colors. ``` -------------------------------- ### Confirmation Prompts Source: https://github.com/magmax/python-inquirer/blob/main/docs/examples.md Shows how to use inquirer.Confirm to ask binary yes/no questions. The 'default' parameter can pre-select an answer. ```python import os import sys from pprint import pprint sys.path.append(os.path.realpath(".")) import inquirer # noqa questions = [ inquirer.Confirm("continue", message="Should I continue"), inquirer.Confirm("stop", message="Should I stop", default=True), ] answers = inquirer.prompt(questions) pprint(answers) ``` -------------------------------- ### Checkbox Selection (Simple) Source: https://github.com/magmax/python-inquirer/blob/main/docs/examples.md Illustrates inquirer.Checkbox for multi-select choices. The 'default' parameter can pre-select options. ```python import os import sys from pprint import pprint sys.path.append(os.path.realpath(".")) import inquirer # noqa questions = [ inquirer.Checkbox( "interests", message="What are you interested in?", choices=["Computers", "Books", "Science", "Nature", "Fantasy", "History"], default=["Computers", "Books"], ), ] answers = inquirer.prompt(questions) pprint(answers) ``` -------------------------------- ### Create a Text Question Object Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md Instantiate a Text question object with a name and a message. ```python Text('name', "What's your name?") ``` -------------------------------- ### List Input Shortcut Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Shortcut function to create a list selection question. ```APIDOC ## inquirer.shortcuts.list_input(message, render=None, **kwargs) ``` -------------------------------- ### inquirer.prompt Source: https://context7.com/magmax/python-inquirer/llms.txt The main entry point for presenting a sequence of questions to the user. It iterates through a list of Question objects, renders each in the terminal, and collects answers into a dictionary. ```APIDOC ## inquirer.prompt(questions, render=None, answers=None, theme=Default(), raise_keyboard_interrupt=False) ### Description The main entry point for presenting a sequence of questions. Iterates through the list of `Question` objects, renders each one in the terminal, and collects answers into a dict keyed by each question's `name`. Returns `None` (printing "Cancelled by user") if the user presses Ctrl+C, unless `raise_keyboard_interrupt=True`. ### Parameters - **questions** (list) - A list of `Question` objects to present to the user. - **render** (optional) - A custom renderer. - **answers** (optional) - Initial answers to pre-populate. - **theme** (optional) - The theme to use for rendering. - **raise_keyboard_interrupt** (bool) - If True, raises KeyboardInterrupt on Ctrl+C. ### Request Example ```python import re import inquirer questions = [ inquirer.Text("name", message="What's your name?"), inquirer.Text( "surname", message="What's your surname, {name}?", # uses previous answer via format string ), inquirer.Text( "phone", message="What's your phone number?", validate=lambda _, x: bool(re.match(r"\+?\d[\d ]+\d", x)), ), ] answers = inquirer.prompt(questions) # answers = {'name': 'John', 'surname': 'Doe', 'phone': '+1 555 1234'} print(answers) ``` ``` -------------------------------- ### inquirer.questions.load_from_json() Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md Loads question definitions from a JSON string. ```APIDOC ## load_from_json(json_string) ### Description Creates question objects from a JSON string. ### Parameters - **json_string** (str): A JSON string containing question configurations. ``` -------------------------------- ### Loading Theme from JSON Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Loads a custom theme from a JSON string, providing a flexible way to define prompt styles. ```APIDOC ## inquirer.themes.load_theme_from_json(json_theme) Load a theme from a json. Expected format: : ```pycon >>> { ... "Question": { ... "mark_color": "yellow", ... "brackets_color": "normal", ... ... ... }, ... "List": { ... "selection_color": "bold_blue", ... "selection_cursor": "->" ... } ... } ``` Color values should be string representing valid blessings.Terminal colors. ``` -------------------------------- ### Define Checkbox Question with Hints Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md Use the `Checkbox` question type for multiple selections. Hints can be provided for each choice, displayed above the first choice. ```python from inquirer import questions choices = { "foo": "Foo", "bar": "Bar", "bazz": "Bazz", } question = questions.Checkbox("foo", "Choose one:", choices=choices.keys(), hints=choices) ``` -------------------------------- ### Themed Prompts Source: https://github.com/magmax/python-inquirer/blob/main/docs/examples.md Demonstrates applying a custom theme to inquirer prompts using the 'theme' parameter. The GreenPassion theme is used here. ```python import inquirer from inquirer.themes import GreenPassion q = [ inquirer.Text("name", message="Whats your name?", default="No one"), inquirer.List("jon", message="Does Jon Snow know?", choices=["yes", "no"], default="no"), inquirer.Checkbox( "kill_list", message="Who you want to kill?", choices=["Cersei", "Littlefinger", "The Mountain"] ), ] inquirer.prompt(q, theme=GreenPassion()) ``` -------------------------------- ### Load Questions from JSON File Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md Load questions from a JSON file using `load_from_json`. Ensure the JSON file path is correctly specified and the file is opened in read mode. ```python import os import sys from pprint import pprint sys.path.append(os.path.realpath(".")) import inquirer # noqa with open("examples/test_questions.json") as fd: questions = inquirer.load_from_json(fd.read()) answers = inquirer.prompt(questions) pprint(answers) ``` -------------------------------- ### inquirer.questions.load_from_list() Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md Loads question definitions from a list of dictionaries. ```APIDOC ## load_from_list(data_list) ### Description Creates question objects from a list of dictionaries. ### Parameters - **data_list** (list): A list of dictionaries, where each dictionary represents a question configuration. ``` -------------------------------- ### Basic Prompting with inquirer.prompt Source: https://context7.com/magmax/python-inquirer/llms.txt Use inquirer.prompt to present a list of questions and collect answers. Answers are returned as a dictionary keyed by question name. Handles basic text input and formatted messages. ```python import re import inquirer questions = [ inquirer.Text("name", message="What's your name?"), inquirer.Text( "surname", message="What's your surname, {name}?", # uses previous answer via format string ), inquirer.Text( "phone", message="What's your phone number?", validate=lambda _, x: bool(re.match(r"\+?\d[\d ]+\d", x)), ), ] answers = inquirer.prompt(questions) # answers = {'name': 'John', 'surname': 'Doe', 'phone': '+1 555 1234'} print(answers) ``` -------------------------------- ### inquirer.questions.load_from_dict() Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md Loads question definitions from a dictionary. ```APIDOC ## load_from_dict(data) ### Description Creates question objects from a dictionary representation. ### Parameters - **data** (dict): A dictionary containing question configurations. ``` -------------------------------- ### inquirer.prompt.prompt() Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md The main function to prompt users with a list of questions and collect their answers. ```APIDOC ## prompt() ### Description This function is the primary interface for running interactive prompts. It takes a list of question objects and returns a dictionary of answers. ### Method `prompt(questions, answers=None, theme=None, raise_keyboard_interrupt=False)` ### Parameters - **questions** (list): A list of question objects to be presented to the user. - **answers** (dict, optional): A dictionary of pre-filled answers. Defaults to None. - **theme** (Theme, optional): A theme object to customize the appearance. Defaults to None. - **raise_keyboard_interrupt** (bool, optional): Whether to raise KeyboardInterrupt on Ctrl+C. Defaults to False. ### Returns - dict: A dictionary where keys are question names and values are the user's answers. ``` -------------------------------- ### Loading Questions from List Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Loads a list of question objects from a list of dictionaries. Each dictionary must contain 'name' and 'kind' keys. ```APIDOC ## inquirer.questions.load_from_list(question_list) Load a list of questions from a list of dicts. It requires the keys ‘name’ and ‘kind’ for each dict. * **Returns:** A list of Question objects with associated data. * **Return type:** list[[*Question*](#inquirer.questions.Question)] ``` -------------------------------- ### Text Shortcut Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Shortcut function to create a standard text input question. ```APIDOC ## inquirer.shortcuts.text(message, autocomplete=None, render=None, **kwargs) ``` -------------------------------- ### Loading Questions from JSON Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Loads questions from a JSON string. Can handle both single question objects and lists of questions. ```APIDOC ## inquirer.questions.load_from_json(question_json) Load Questions from a JSON string. * **Returns:** A list of Question objects with associated data if the JSON contains a list or a Question if the JSON contains a dict. * **Return type:** list | dict ``` -------------------------------- ### Password Shortcut Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Shortcut function to create a password input question. ```APIDOC ## inquirer.shortcuts.password(message, render=None, **kwargs) ``` -------------------------------- ### Loading Questions from Dictionary Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Loads a single question object from a dictionary. Requires 'name' and 'kind' keys. ```APIDOC ## inquirer.questions.load_from_dict(question_dict) Load one question from a dict. It requires the keys ‘name’ and ‘kind’. * **Returns:** The Question object with associated data. * **Return type:** [*Question*](#inquirer.questions.Question) ``` -------------------------------- ### Run Specific Nox Session (Unit Tests) Source: https://github.com/magmax/python-inquirer/blob/main/docs/contributing.md Invoke a specific Nox session, such as the unit test suite. ```sh nox --session=tests ``` -------------------------------- ### Filesystem Path Input with Existence and Type Validation Source: https://context7.com/magmax/python-inquirer/llms.txt Use `inquirer.Path` for filesystem path input. `path_type` can restrict to files or directories. `exists=True` requires the path to exist, `exists=False` requires it to not exist. `~` is automatically expanded. ```python import inquirer questions = [ inquirer.Path( "config", message="Path to existing config file", path_type=inquirer.Path.FILE, exists=True, ), inquirer.Path( "output_dir", message="Output directory (will be created)", path_type=inquirer.Path.DIRECTORY, exists=False, default="~/output", ), ] answers = inquirer.prompt(questions) # answers = {'config': '/etc/myapp/config.yaml', 'output_dir': '/home/user/output'} ``` -------------------------------- ### Multi-Select Checkbox Prompt with Hints and Defaults Source: https://context7.com/magmax/python-inquirer/llms.txt Use `inquirer.Checkbox` for multi-select prompts. Spacebar toggles selections, Enter confirms. `default` sets pre-selected items, and `locked` prevents deselection. Hints provide extra information for each choice. ```python import inquirer questions = [ inquirer.Checkbox( "features", message="Which features should be enabled?", choices=[ ("Authentication", "auth"), ("Rate Limiting", "rate_limit"), ("Caching", "cache"), ("Logging", "logging"), ("Monitoring", "monitoring"), ], default=["auth", "logging"], # pre-selected values locked=["auth"], # 'auth' cannot be deselected carousel=True, hints={ "auth": "OAuth2 / JWT support", "rate_limit": "Throttle requests per IP", "cache": "Redis-backed response cache", "logging": "Structured JSON logging", "monitoring": "Prometheus metrics endpoint", }, ) ] answers = inquirer.prompt(questions) # answers = {'features': ['auth', 'cache', 'logging']} ``` -------------------------------- ### Applying Built-in and Custom Themes Source: https://context7.com/magmax/python-inquirer/llms.txt Customize the terminal appearance of prompts using built-in themes or by defining a custom theme from a dictionary. Themes control colors and selection indicators. ```python import inquirer from inquirer.themes import GreenPassion, BlueComposure, load_theme_from_dict # Use a built-in theme answers = inquirer.prompt( [ inquirer.Text("name", message="Your name?"), inquirer.List("env", message="Environment?", choices=["dev", "staging", "prod"]), inquirer.Checkbox("roles", message="Roles?", choices=["admin", "editor", "viewer"]), ], theme=GreenPassion(), ) # Custom theme via dict custom_theme = load_theme_from_dict({ "Question": { "mark_color": "bright_magenta", "brackets_color": "bold", }, "List": { "selection_color": "bold_blue", "selection_cursor": "→", }, "Checkbox": { "selection_icon": "❯", "selected_icon": "◉", "unselected_icon": "◯", }, }) answers = inquirer.prompt( [inquirer.List("choice", message="Pick one", choices=["a", "b", "c"] )], theme=custom_theme, ) ``` -------------------------------- ### inquirer.shortcuts Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md Provides convenient shortcut functions for creating common question types. ```APIDOC ## Shortcuts Module ### Description This module offers simplified functions to quickly create instances of various question types without needing to explicitly use the question classes. ### Functions - **checkbox(**kwargs**): Shortcut for creating a Checkbox question. - **confirm(**kwargs**): Shortcut for creating a Confirm question. - **editor(**kwargs**): Shortcut for creating an Editor question. - **list_input(**kwargs**): Shortcut for creating a List question. - **password(**kwargs**): Shortcut for creating a Password question. - **path(**kwargs**): Shortcut for creating a Path question. - **text(**kwargs**): Shortcut for creating a Text question. ``` -------------------------------- ### ConsoleRender Class Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.render.console.md The main class for rendering prompts to the console, handling clearing, printing, and the overall rendering process. ```APIDOC ## Class: ConsoleRender ### Description Manages the rendering of prompts to the console. It provides methods for clearing the screen, printing lines of text, and rendering the entire prompt interface. ### Methods - **clear_bottombar()**: Clears the bottom bar of the console output. - **clear_eos()**: Clears the console from the current cursor position to the end of the screen. - **print_line(base, lf=True, **kwargs)**: Prints a line of text to the console. - **print_str(base, lf=False, **kwargs)**: Prints a string to the console without necessarily adding a newline. - **render(question, answers=None)**: Renders the complete prompt interface for a given question. - **render_error(message)**: Renders an error message to the console. - **render_factory(question_type)**: A factory method to get the appropriate renderer for a given question type. - **render_in_bottombar(message)**: Renders a message in the bottom bar of the console. ### Properties - **height** (int): The current height of the console. - **width** (int): The current width of the console. ``` -------------------------------- ### Load Questions from List, JSON, or Dictionary Source: https://context7.com/magmax/python-inquirer/llms.txt Define questions programmatically for dynamic CLI flows. Supports loading from Python lists of dictionaries, JSON strings, or single dictionaries. ```python import inquirer # From a list of dicts question_list = [ {"kind": "text", "name": "name", "message": "What's your name?"}, {"kind": "text", "name": "surname", "message": "What's your surname?"}, {"kind": "list", "name": "size", "message": "What size?", "choices": ["Small", "Medium", "Large"]}, {"kind": "confirm", "name": "confirm", "message": "Confirm choices?", "default": True}, ] questions = inquirer.load_from_list(question_list) answers = inquirer.prompt(questions) # From a JSON string (or file) import json json_str = json.dumps(question_list) questions = inquirer.load_from_json(json_str) answers = inquirer.prompt(questions) # From a single dict single = inquirer.load_from_dict({"kind": "password", "name": "token", "message": "API token"}) # single is a Password question object ``` -------------------------------- ### Confirm Shortcut Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Shortcut function to create a confirmation question (yes/no). ```APIDOC ## inquirer.shortcuts.confirm(message, render=None, **kwargs) ``` -------------------------------- ### Checkbox Shortcut Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Shortcut function to create a checkbox question. ```APIDOC ## inquirer.shortcuts.checkbox(message, render=None, **kwargs) ``` -------------------------------- ### Checkbox Selection with Tuples Source: https://github.com/magmax/python-inquirer/blob/main/docs/examples.md Shows how to use inquirer.Checkbox with a list of tuples for choices, where each tuple contains a display label and a value. This allows for non-string values to be returned. ```python import os import sys from pprint import pprint sys.path.append(os.path.realpath(".")) import inquirer # noqa questions = [ inquirer.Checkbox( "interests", message="What are you interested in?", choices=[ ("Computers", "c"), ("Books", "b"), ("Science", "s"), ("Nature", "n"), ("Fantasy", "f"), ("History", "h"), ], default=["c", "b"], ), ] answers = inquirer.prompt(questions) pprint(answers) ``` -------------------------------- ### Shortcut Functions for Single Prompts Source: https://context7.com/magmax/python-inquirer/llms.txt Use one-liner functions for quick, individual prompts. These functions directly return the user's answer value, simplifying common input scenarios. ```python import inquirer # Single text input name = inquirer.text(message="Enter your name", default="World") # Password input token = inquirer.password(message="Enter API token") # Yes/no confirmation confirmed = inquirer.confirm(message="Deploy to production?", default=False) # Single-select list size = inquirer.list_input( message="Choose a size", choices=["Small", "Medium", "Large"], default="Medium", ) # Multi-select checkbox tags = inquirer.checkbox( message="Select applicable tags", choices=["bug", "enhancement", "documentation", "question"], ) # Path input log_dir = inquirer.path( message="Log directory", path_type=inquirer.Path.DIRECTORY, ) # Editor input notes = inquirer.editor(message="Add release notes") print(name, token, confirmed, size, tags, log_dir, notes) ``` -------------------------------- ### Theme Classes Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Provides predefined themes for customizing the appearance of Inquirer prompts. ```APIDOC ### *class* inquirer.themes.BlueComposure Bases: [`Default`](#inquirer.themes.Default) ### *class* inquirer.themes.Default Bases: [`Theme`](#inquirer.themes.Theme) ### *class* inquirer.themes.GreenPassion Bases: [`Default`](#inquirer.themes.Default) ### *class* inquirer.themes.RedSolace Bases: [`Default`](#inquirer.themes.Default) ### *class* inquirer.themes.Theme Bases: `object` ``` -------------------------------- ### Question Factory Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md A factory function to create question objects based on their 'kind'. ```APIDOC ## inquirer.questions.question_factory(kind, *args, **kwargs) ``` -------------------------------- ### Implement Autocompletion Function Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md Use the `autocomplete` parameter in `inquirer.Text` to provide a function that generates suggestions. The function receives the current input and TAB press count, returning the replacement string. ```python import inquirer suggestions = ["inquirer", "hello", "world", "foo", "bar", "baz", "qux"] def autocomplete_fn(_text, state): # Every time the user presses TAB, we'll switch to the next suggestion # The `state` variable contains the index of the current suggestion # We can wrap it around to the first suggestion if we reach the end return suggestions[state % len(suggestions)] questions = [ inquirer.Text( "name", message="Press TAB to cycle through suggestions", autocomplete=autocomplete_fn, ), ] answers = inquirer.prompt(questions) print(answers) ``` -------------------------------- ### inquirer.Path Source: https://context7.com/magmax/python-inquirer/llms.txt Validates input as a filesystem path. Can restrict to files or directories and enforce existence or non-existence. Automatically expands the tilde (~) character. ```APIDOC ## `inquirer.Path(name, message, default=None, path_type="any", exists=None, validate=True, ignore=False)` Like `Text`, but validates that the input is a valid filesystem path. `path_type` restricts to `Path.ANY` (default), `Path.FILE`, or `Path.DIRECTORY`. `exists=True` requires the path to exist; `exists=False` requires it to not exist. Expands `~` automatically. ```python import inquirer questions = [ inquirer.Path( "config", message="Path to existing config file", path_type=inquirer.Path.FILE, exists=True, ), inquirer.Path( "output_dir", message="Output directory (will be created)", path_type=inquirer.Path.DIRECTORY, exists=False, default="~/output", ), ] answers = inquirer.prompt(questions) # answers = {'config': '/etc/myapp/config.yaml', 'output_dir': '/home/user/output'} ``` ``` -------------------------------- ### Path Question Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Represents a file or directory path input question. It supports validation for path existence and type. ```APIDOC ## class inquirer.questions.Path(name, default=None, path_type='any', exists=None, **kwargs) Bases: [`Text`](#inquirer.questions.Text) #### ANY *= 'any' #### DIRECTORY *= 'directory' #### FILE *= 'file' #### kind *= 'path' #### validate(current) * **Parameters:** **current** (*str*) ``` -------------------------------- ### inquirer.questions.question_factory() Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md A factory function to create question objects based on type. ```APIDOC ## question_factory(kind, **kwargs) ### Description Factory function that instantiates the correct question type based on the provided 'kind' string and other keyword arguments. ### Parameters - **kind** (str): The type of question to create (e.g., 'text', 'list', 'confirm'). - **kwargs**: Additional arguments to pass to the question constructor. ``` -------------------------------- ### List Selection Source: https://github.com/magmax/python-inquirer/blob/main/docs/examples.md Demonstrates inquirer.List for presenting a single-choice list to the user. The 'choices' parameter accepts a list of strings. ```python import os import sys from pprint import pprint sys.path.append(os.path.realpath(".")) import inquirer # noqa questions = [ inquirer.List( "size", message="What size do you need?", choices=["Jumbo", "Large", "Standard", "Medium", "Small", "Micro"], ), ] answers = inquirer.prompt(questions) pprint(answers) ``` -------------------------------- ### inquirer.events.KeyEventGenerator Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md Generates key press events. ```APIDOC ## KeyEventGenerator Class ### Description Handles the generation of key press events during user interaction. ### Methods - **next()**: Returns the next key event. ``` -------------------------------- ### Render Class Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.render.md The Render class is responsible for rendering questions and processing answers. It takes an implementation of a renderer as an argument. ```APIDOC ## class inquirer.render.Render(impl=) Bases: `object` #### render(question, answers) Method to render a question with the given answers. ``` -------------------------------- ### Single-Select List Prompt with Choices from Callable Source: https://context7.com/magmax/python-inquirer/llms.txt Use `inquirer.List` for single-select prompts. Choices can be dynamically provided by a callable function. `carousel=True` enables circular navigation. ```python import inquirer def get_envs(answers): return ["development", "staging", "production"] questions = [ inquirer.List( "environment", message="Select deployment environment", choices=get_envs, default="staging", carousel=True, ), inquirer.List( "region", message="Select region for {environment}", choices=[ ("US East (N. Virginia)", "us-east-1"), ("EU (Ireland)", "eu-west-1"), ("Asia Pacific (Tokyo)", "ap-northeast-1"), ], ), ] answers = inquirer.prompt(questions) # answers = {'environment': 'production', 'region': 'us-east-1'} ``` -------------------------------- ### Editor Shortcut Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Shortcut function to create an editor question, allowing multi-line input. ```APIDOC ## inquirer.shortcuts.editor(message, render=None, **kwargs) ``` -------------------------------- ### Path Question with Directory Validation Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md Use the Path question type to validate directory paths. Set `path_type` to `Path.DIRECTORY` to enforce that the provided path is a directory. ```python Path('log_file', 'Where should be log files located?', path_type=Path.DIRECTORY) ``` -------------------------------- ### inquirer.List Source: https://context7.com/magmax/python-inquirer/llms.txt Displays a single-select list where the user navigates with arrow keys and confirms with Enter. Choices can be strings, (label, value) tuples, or a callable. Carousel mode wraps selection at the ends. ```APIDOC ## `inquirer.List(name, message, choices, default=None, carousel=False, other=False, hints=None, autocomplete=None, validate=True, ignore=False)` Displays a single-select list. The user navigates with arrow keys and confirms with Enter. `choices` can be a list of strings, `(label, value)` tuples, or a callable returning such a list. `carousel=True` wraps selection at the ends. ```python import inquirer def get_envs(answers): return ["development", "staging", "production"] questions = [ inquirer.List( "environment", message="Select deployment environment", choices=get_envs, default="staging", carousel=True, ), inquirer.List( "region", message="Select region for {environment}", choices=[ ("US East (N. Virginia)", "us-east-1"), ("EU (Ireland)", "eu-west-1"), ("Asia Pacific (Tokyo)", "ap-northeast-1"), ], ), ] answers = inquirer.prompt(questions) # answers = {'environment': 'production', 'region': 'us-east-1'} ``` ``` -------------------------------- ### Prompt User for Answers Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md Call the `inquirer.prompt` function with a list of question objects to interact with the user and collect their answers. ```python answers = inquirer.prompt(questions) ``` -------------------------------- ### inquirer.questions.Path Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md Represents a path input question type with validation for files or directories. ```APIDOC ## Path Question ### Description A question type for collecting file or directory paths from the user, with built-in validation options. ### Attributes - **kind** (str): Always 'path'. ### Constants - **Path.ANY**: Matches any path. - **Path.DIRECTORY**: Matches a directory. - **Path.FILE**: Matches a file. ### Methods - **validate(path, type)**: Validates if the given path is of the specified type. ``` -------------------------------- ### BaseConsoleRender Class Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.render.console.md The base class for console renderers, providing fundamental methods for handling questions and rendering output. ```APIDOC ## Class: BaseConsoleRender ### Description Provides a base implementation for console rendering, including methods for getting current values, headers, hints, options, and handling input and validation errors. ### Methods - **get_current_value()**: Retrieves the current value of the prompt. - **get_header()**: Returns the header for the prompt. - **get_hint()**: Returns the hint message for the prompt. - **get_options()**: Retrieves the available options for a choice-based prompt. - **handle_validation_error(error)**: Handles and displays validation errors. - **other_input()**: Processes other types of user input. - **process_input(pressed)**: Processes a specific key press. ### Properties - **title_inline** (boolean): Indicates if the title should be rendered inline. ``` -------------------------------- ### inquirer.questions.Question Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md Base class for all question types. Provides common attributes and methods. ```APIDOC ## Question Class ### Description The base class for defining interactive questions. It includes common properties like message, default value, validation, and choice management. ### Attributes - **message** (str): The question to display to the user. - **choices** (list, optional): A list of choices for the user to select from. Defaults to None. - **default** (any, optional): The default value for the question. Defaults to None. - **validate** (callable, optional): A function to validate the user's input. Defaults to None. - **ignore** (callable, optional): A function to determine if the question should be skipped. Defaults to None. - **kind** (str): The type of the question (e.g., 'text', 'list'). - **choices_generator** (callable, optional): A function to dynamically generate choices. ### Methods - **add_choice(choice)**: Adds a choice to the question. ``` -------------------------------- ### Text Input with Autocomplete and Validation Source: https://context7.com/magmax/python-inquirer/llms.txt The Text prompt type supports default values, autocomplete suggestions triggered by TAB, and custom validation logic. Ensure the validation function returns True or raises an error. ```python import inquirer suggestions = ["alice", "bob", "carol", "dave"] def autocomplete(text, state): matches = [s for s in suggestions if s.startswith(text)] return matches[state % len(matches)] if matches else text questions = [ inquirer.Text( "username", message="Enter your username", default="alice", show_default=True, autocomplete=autocomplete, validate=lambda _, v: len(v) >= 3 or (_ and False), # min 3 chars ) ] answers = inquirer.prompt(questions) # answers = {'username': 'alice'} ``` -------------------------------- ### Text Question Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Represents a standard text input question. It inherits from the base Question class and includes options for default values and autocompletion. ```APIDOC ## class inquirer.questions.Text(name, message='', default=None, autocomplete=None, **kwargs) Bases: [`Question`](#inquirer.questions.Question) #### kind *= 'text' ``` -------------------------------- ### Confirm Prompt for Yes/No Questions Source: https://context7.com/magmax/python-inquirer/llms.txt The Confirm prompt type asks a simple yes/no question. It accepts 'y'/'Y' for True and 'n'/'N' for False. The default value can pre-select an option. Conditional skipping is possible using the 'ignore' parameter. ```python import inquirer questions = [ inquirer.Confirm("proceed", message="Do you want to continue?", default=True), inquirer.Confirm( "delete_all", message="This will delete everything. Are you sure?", default=False, ignore=lambda ans: not ans["proceed"], # skip if user said no above ), ] answers = inquirer.prompt(questions) # answers = {'proceed': True, 'delete_all': False} ``` -------------------------------- ### inquirer.Checkbox Source: https://context7.com/magmax/python-inquirer/llms.txt Displays a multi-select list where users toggle selections with Space and confirm with Enter. Supports keyboard shortcuts for select all, deselect all, and invert selection. Choices can be locked to prevent deselection. ```APIDOC ## `inquirer.Checkbox(name, message, choices, default=None, locked=None, carousel=False, other=False, hints=None, autocomplete=None, validate=True, ignore=False)` Displays a multi-select list. The user toggles selections with Space and confirms with Enter. `locked` is a list of choices that cannot be deselected. Keyboard shortcuts: Ctrl+A (select all), Ctrl+R (deselect all), Ctrl+I (invert selection). ```python import inquirer questions = [ inquirer.Checkbox( "features", message="Which features should be enabled?", choices=[ ("Authentication", "auth"), ("Rate Limiting", "rate_limit"), ("Caching", "cache"), ("Logging", "logging"), ("Monitoring", "monitoring"), ], default=["auth", "logging"], # pre-selected values locked=["auth"], # 'auth' cannot be deselected carousel=True, hints={ "auth": "OAuth2 / JWT support", "rate_limit": "Throttle requests per IP", "cache": "Redis-backed response cache", "logging": "Structured JSON logging", "monitoring": "Prometheus metrics endpoint", }, ) ] answers = inquirer.prompt(questions) # answers = {'features': ['auth', 'cache', 'logging']} ``` ``` -------------------------------- ### inquirer.themes Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md Module for managing and applying themes to the inquirer interface. ```APIDOC ## Themes Module ### Description This module provides functionality for defining, loading, and applying visual themes to the inquirer prompts. ### Classes - **Theme**: Base class for all themes. - **Default**: The default theme. - **BlueComposure**: A predefined theme. - **GreenPassion**: A predefined theme. - **RedSolace**: A predefined theme. ### Functions - **load_theme_from_dict(data)**: Loads a theme from a dictionary. - **load_theme_from_json(json_string)**: Loads a theme from a JSON string. ``` -------------------------------- ### Path Question with Existence Validation Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md Use the Path question type to validate if a path exists. Set `exists` to `True` to ensure the path exists, or `False` to ensure it does not. `path_type` can also be specified. ```python Path('config_file', 'Point me to your configuration file.', exists=True, path_type=Path.File) ``` -------------------------------- ### Password Question Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md Represents a password input question. It inherits from the Text question type and uses a default echo character. ```APIDOC ## class inquirer.questions.Password(name, echo='*', **kwargs) Bases: [`Text`](#inquirer.questions.Text) #### kind *= 'password' ``` -------------------------------- ### inquirer.errors Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md Module containing custom exception classes for inquirer. ```APIDOC ## Errors Module ### Description This module defines custom exception types used within the inquirer library to handle specific error conditions. ### Exception Classes - **EndOfInput**: Raised when input ends unexpectedly. - **ThemeError**: Raised for errors related to theme loading or application. - **UnknownQuestionTypeError**: Raised when an unrecognized question type is encountered. - **ValidationError**: Raised when user input fails validation. ``` -------------------------------- ### Base Question Class Source: https://github.com/magmax/python-inquirer/blob/main/docs/inquirer.md The base class for all question types, providing common attributes like name, message, choices, and validation. ```APIDOC ## class inquirer.questions.Question(name, message='', choices=None, default=None, ignore=False, validate=True, show_default=False, hints=None, other=False) Bases: `object` #### add_choice(choice) #### *property* choices #### *property* choices_generator #### *property* default #### *property* ignore #### kind *= 'base question' #### *property* message #### validate(current) ``` -------------------------------- ### inquirer.questions.List Source: https://github.com/magmax/python-inquirer/blob/main/docs/modules.md Represents a list question type, allowing a single selection from a list. ```APIDOC ## List Question ### Description A question type that presents a list of options and allows the user to select only one. ### Attributes - **kind** (str): Always 'list'. ``` -------------------------------- ### Editor Prompt for Multi-line Input Source: https://context7.com/magmax/python-inquirer/llms.txt The Editor prompt type opens an external text editor for multi-line input, suitable for longer text like commit messages. The input is collected after the editor is closed. ```python import inquirer questions = [ inquirer.Editor( "description", message="Describe the bug (opens editor)", default="Steps to reproduce:\n1. \n2. \n", ) ] answers = inquirer.prompt(questions) # answers = {'description': ''} print(answers["description"]) ``` -------------------------------- ### inquirer.Confirm Source: https://context7.com/magmax/python-inquirer/llms.txt Asks a yes/no question. Accepts 'y'/'Y' for True and 'n'/'N' for False. The default option is pre-selected. ```APIDOC ## inquirer.Confirm(name, message, default=False, ignore=False) ### Description Asks a yes/no question. Accepts `y`/`Y` for True and `n`/`N` for False. The `default` determines which option is pre-selected. ### Parameters - **name** (str) - The name of the question. - **message** (str) - The message to display to the user. - **default** (bool) - The default answer (True for yes, False for no). - **ignore** (callable or bool) - A condition to ignore the question. ### Request Example ```python import inquirer questions = [ inquirer.Confirm("proceed", message="Do you want to continue?", default=True), inquirer.Confirm( "delete_all", message="This will delete everything. Are you sure?", default=False, ignore=lambda ans: not ans["proceed"], # skip if user said no above ), ] answers = inquirer.prompt(questions) # answers = {'proceed': True, 'delete_all': False} ``` ``` -------------------------------- ### Define Text Question with Function Message Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md The message for a `Text` question can be dynamically generated using a function that receives previous answers. ```python from inquirer import text def get_message(answers): return "What's your name?" text(name='name', message= get_message) ``` -------------------------------- ### Lambda Validation for Age Source: https://github.com/magmax/python-inquirer/blob/main/docs/usage.md A concise way to define validation logic using a lambda function for simple checks like age range. ```python text('age', "How old are you?", validate=lambda _, c: 0 <= int(c) < 120) ``` -------------------------------- ### Conditional questions with ignore Source: https://context7.com/magmax/python-inquirer/llms.txt Questions can be conditionally skipped using the `ignore` parameter, which accepts a boolean or a callable. The callable receives the current answers and returns True to skip the question. ```APIDOC ## Conditional questions with `ignore` Questions can be conditionally hidden by passing a boolean or a callable to `ignore`. The callable receives the dict of answers collected so far and should return `True` to skip the question (returning the default value silently). ```python import inquirer questions = [ inquirer.Confirm("has_proxy", message="Do you use a proxy?", default=False), inquirer.Text( "proxy_host", message="Proxy host", ignore=lambda ans: not ans.get("has_proxy"), ), inquirer.Text( "proxy_port", message="Proxy port", default="8080", ignore=lambda ans: not ans.get("has_proxy"), validate=lambda _, v: v.isdigit(), ), ] answers = inquirer.prompt(questions) ``` ```