### Setup for Running InquirerPy Examples Source: https://github.com/kazhala/inquirerpy/blob/master/docs/index.md Provides a sequence of shell commands to set up the environment for running InquirerPy examples. This includes cloning the repository, navigating into it, creating and activating a Python virtual environment, and installing necessary dependencies from a requirements file. ```Shell git clone https://github.com/kazhala/InquirerPy.git cd InquirerPy python3 -m venv venv source venv/bin/activate pip3 install -r examples/requirements.txt ``` -------------------------------- ### Listing and Executing InquirerPy Examples Source: https://github.com/kazhala/inquirerpy/blob/master/docs/index.md Shows how to list available example scripts within the InquirerPy repository and demonstrates two ways to execute a specific example using the Python interpreter. ```Shell ls examples/*.py ls examples/classic/*.py ls examples/alternate/*.py python3 -m examples.classic.rawlist # or python3 examples/classic/rawlist ``` -------------------------------- ### Install InquirerPy Library Source: https://github.com/kazhala/inquirerpy/blob/master/docs/index.md Instructions to install the InquirerPy Python library using pip. This command will download and install the package from PyPI. ```Shell pip3 install InquirerPy ``` -------------------------------- ### Example of Asynchronous Prompting with InquirerPy Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompt.md This Python example demonstrates how to use `prompt_async` from `InquirerPy` to collect multiple user inputs asynchronously. It sets up a list of question dictionaries and runs the asynchronous prompt within an `asyncio` event loop, ensuring non-blocking I/O. ```python import asyncio from InquirerPy import inquirer, prompt_async async def main(): questions = [ {"type": "input", "message": "Name:"}, {"type": "number", "message": "Number:"}, {"type": "confirm", "message": "Confirm?"}, ] result = await prompt_async(questions) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Registering a Keybinding to Print Output Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/kb.md A simple example showing how to bind 'alt-a' to a function that prints 'Hello World' using `patched_print` without affecting the prompt's execution flow. ```python from InquirerPy import inquirer from InquirerPy.utils import patched_print as print name_prompt = inquirer.text(message="Name:") kb_activate = True @name_prompt.register_kb("alt-a") def _(_): print("Hello World") name = name_prompt.execute() ``` -------------------------------- ### InquirerPy Select Prompt Alternate Syntax Example Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/list.md Illustrates an alternative, more concise syntax for the `select` prompt in InquirerPy. This approach streamlines the definition and execution of a list selection prompt, making it more direct. ```python from InquirerPy import inquirer result = inquirer.select( message="Select an option:", choices=["Option 1", "Option 2", "Option 3"] ).execute() ``` -------------------------------- ### Install InquirerPy via pip Source: https://github.com/kazhala/inquirerpy/blob/master/README.md Instructions to install the InquirerPy library using pip, the Python package installer. This command adds InquirerPy to your Python environment. ```shell pip3 install InquirerPy ``` -------------------------------- ### InquirerPy Select Prompt Classic Syntax Example Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/list.md Demonstrates the classic syntax for using the `select` prompt in InquirerPy, often resembling PyInquirer's structure. This snippet illustrates how to define questions and retrieve answers for a basic list selection prompt. ```python from PyInquirer import prompt questions = [ { 'type': 'list', 'name': 'theme', 'message': 'What do you want to do?', 'choices': ['Order a pizza', 'Make a reservation', 'Ask for opening hours'] } ] answers = prompt(questions) ``` -------------------------------- ### Define Custom Keybindings with InquirerPy Inquirer (Alternate Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/kb.md This example illustrates an alternative syntax for defining custom keybindings in InquirerPy using the `inquirer.select` method. It achieves the same functionality as the classic prompt example, allowing users to bind key sequences to actions like 'skip', 'interrupt', and 'toggle-all' for a multiselect prompt. ```python from InquirerPy import inquirer keybindings = { "skip": [{"key": "c-c"}], "interrupt": [{"key": "c-d"}], "toggle-all": [{"key": ["c-a", "space"]}], } result = inquirer.select( message="Select one:", choices=["Fruit", "Meat", "Drinks", "Vegetable"], keybindings=keybindings, multiselect=True ).execute() ``` -------------------------------- ### Apply Basic Foreground Color Style Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/style.md Shows a simple dictionary example for applying a basic foreground color to a prompt component, specifically setting the `questionmark` to 'blue'. This demonstrates the simplest form of color styling. ```python { "questionmark": "blue" } ``` -------------------------------- ### Define Choices for InquirerPy Expand Prompt Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/expand.md This Python example demonstrates how to create a list of choices for the InquirerPy expand prompt using the `ExpandChoice` class. Each choice is associated with a unique single-character key for quick selection, which is recommended for this prompt type. ```python from InquirerPy.prompts.expand import ExpandChoice choices = [ ExpandChoice("Apple", key="a"), ExpandChoice("Cherry", key="c"), ExpandChoice("Orange", key="o"), ExpandChoice("Peach", key="p"), ExpandChoice("Melon", key="m"), ExpandChoice("Strawberry", key="s"), ExpandChoice("Grapes", key="g"), ] ``` -------------------------------- ### Example of patched_print with InquirerPy Prompt Keybinding Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/patched_print.md This Python example demonstrates how to integrate `patched_print` with an `InquirerPy` text prompt. It configures a keybinding (alt-b) that, when pressed, calls `patched_print` to display 'Hello World' above the prompt, showcasing its non-interfering nature. ```python from InquirerPy.utils import patched_print from InquirerPy import inquirer prompt = inquirer.text(message="Name:") @prompt.register_kb("alt-b") def _(_): patched_print("Hello World") name = prompt.execute() ``` -------------------------------- ### Basic Usage with InquirerPy Alternate Syntax Source: https://github.com/kazhala/inquirerpy/blob/master/docs/index.md Illustrates the recommended alternate syntax for InquirerPy, which offers more flexibility and IDE type hinting. It directly interacts with individual prompt classes like `inquirer.text`, `inquirer.select`, and `inquirer.confirm`, executing each prompt separately to get user input. ```Python from InquirerPy import inquirer name = inquirer.text(message="What's your name:").execute() fav_lang = inquirer.select( message="What's your favourite programming language:", choices=["Go", "Python", "Rust", "JavaScript"], ).execute() confirm = inquirer.confirm(message="Confirm?").execute() ``` -------------------------------- ### Python Example: Integrating color_print with InquirerPy Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/color_print.md This Python example demonstrates how to import and utilize the `color_print` utility function. It shows two use cases: printing colored text within a custom keyboard shortcut (`alt-b`) registered to an `InquirerPy` text prompt, and a direct call to `color_print` with a custom style definition. ```python from InquirerPy.utils import color_print from InquirerPy import inquirer prompt = inquirer.text(message="Name:") @prompt.register_kb("alt-b") def _(_): color_print([("#e5c07b", "Hello"), ("#ffffff", "World")]) name = prompt.execute() color_print([("class:aaa", "fooboo")], style={"aaa": "#000000"}) ``` -------------------------------- ### Customize InquirerPy Expand Prompt Help Message and Key Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/expand.md These Python examples illustrate how to customize the expansion key and help message displayed for the InquirerPy expand prompt using the `ExpandHelp` class. It shows both the classic `prompt` function syntax and the alternate `inquirer.expand` syntax for configuring the prompt's behavior. ```python from InquirerPy import prompt from InquirerPy.prompts.expand import ExpandHelp questions = [ { "type": "expand", "message": "Select one:", "choices": [{"key": "a", "value": "1", "name": "1"}], "expand_help": ExpandHelp(key="o", message="Help"), } ] result = prompt(questions=questions) ``` ```python from InquirerPy import inquirer from InquirerPy.prompts.expand import ExpandHelp result = inquirer.expand( message="Select one:", choices=[{"key": "a", "value": "1", "name": "1"}], expand_help=ExpandHelp(key="o", message="Help"), ).execute() ``` -------------------------------- ### Apply Custom Style to InquirerPy Prompt (Classic Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/style.md Demonstrates how to apply custom styling to an InquirerPy prompt using the `style` parameter with a dictionary. This example sets the `questionmark` component's color to orange and bold, while retaining default styles for other components. ```python from InquirerPy import prompt result = prompt( {"message": "Confirm order?", "type": "confirm", "default": False}, style={"questionmark": "#ff9d00 bold"}, vi_mode=True, style_override=False, ) ``` -------------------------------- ### InquirerPy Prompt with `choices` Parameter (Alternate Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/dynamic.md Illustrates using the `choices` parameter with `InquirerPy.inquirer.select` through the more concise alternate syntax. This example also includes `Choice` objects and `Separator` instances for a multiselect prompt, demonstrating a streamlined way to define interactive selections. ```python from InquirerPy import inquirer from InquirerPy.base.control import Choice from InquirerPy.separator import Separator region = inquirer.select( message="Select regions:", choices=[ Choice("ap-southeast-2", name="Sydney"), Choice("ap-southeast-1", name="Singapore"), Separator(), "us-east-1", "us-east-2", ], multiselect=True, transformer=lambda result: f"{len(result)} region{'s' if len(result) > 1 else ''} selected", ).execute() ``` -------------------------------- ### Unit Testing InquirerPy Alternate Syntax Inquirer Class Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/faq.md This example illustrates how to unit test a Python function that uses the `InquirerPy.inquirer` object (alternate syntax). It provides a function definition using `inquirer.text().execute()` and then shows how to mock the `inquirer.text` method within a `unittest.TestCase` to simulate user input for testing. ```python from InquirerPy import inquirer def get_name(): return inquirer.text(message="Name:").execute() ``` ```python import unittest from unittest.mock import patch from Module.somefunction import get_name class TestPrompt(unittest.TestCase): @patch("Module.somefunction.inquirer.text") def test_get_name(self, mocked_prompt): mocked_prompt.return_value = "hello" result = get_name() self.assertEqual(result, "hello") ``` -------------------------------- ### Comprehensive InquirerPy Prompt Example Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/inquirer.md Demonstrates various prompt types (text, confirm, list, secret, filepath) using the `inquirer` module's `prompt` function, showcasing a full interactive session for collecting multiple user inputs. ```python from InquirerPy import inquirer, prompt def main(): questions = [ {"type": "text", "message": "What's your name?", "name": "name"}, {"type": "confirm", "message": "Do you like Python?", "name": "likes_python", "default": True}, {"type": "list", "message": "Favorite color?", "choices": ["Red", "Green", "Blue"], "name": "color"}, {"type": "secret", "message": "Enter a secret:", "name": "secret"}, {"type": "filepath", "message": "Select a file:", "name": "file_path"} ] result = prompt(questions=questions) print("Results:", result) if __name__ == "__main__": main() ``` -------------------------------- ### Configure Keybinding to Toggle Fuzzy/Exact Match Algorithm Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/fuzzy.md These Python examples show how to add a keybinding (Ctrl+T in this case) to allow users to dynamically toggle between fuzzy and exact sub-string matching algorithms within the fuzzy prompt. This enhances user control over search behavior. ```python from InquirerPy import prompt questions = [ { "type": "fuzzy", "message": "Select actions:", "choices": ["hello", "weather", "what", "whoa", "hey", "yo"], "keybindings": {"toggle-exact": [{"key": "c-t"}]} } ] result = prompt(questions=questions) ``` ```python from InquirerPy import inquirer result = inquirer.fuzzy( message="Select actions:", choices=["hello", "weather", "what", "whoa", "hey", "yo"], keybindings={"toggle-exact": [{"key": "c-t"}]} ).execute() ``` -------------------------------- ### Create List Prompt with Separator (Alternate Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/separator.md Illustrates the usage of `InquirerPy.separator.Separator` with the alternate `InquirerPy.inquirer.select` syntax. This example also demonstrates adding a separator to visually group choices in a multi-select list prompt, including a transformer function for custom output. ```python """ ? Select regions: █ Sydney ► Singapore --------------- <- Separator us-east-1 us-east-2 """ from InquirerPy import inquirer from InquirerPy.base.control import Choice from InquirerPy.separator import Separator region = inquirer.select( message="Select regions:", choices=[ Choice("ap-southeast-2", name="Sydney"), Choice("ap-southeast-1", name="Singapore"), Separator(), "us-east-1", "us-east-2", ], multiselect=True, transformer=lambda result: f"{len(result)} region{'s' if len(result) > 1 else ''} selected", ).execute() ``` -------------------------------- ### Configure InquirerPy Keybinding (vi_mode) via Environment Variable (Alternate Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/env.md This example shows how to activate vi-mode keybindings for InquirerPy's `inquirer` object using an environment variable. It highlights the transition from passing `vi_mode=True` as a parameter to relying on the `INQUIRERPY_VI_MODE` environment variable. ```python from InquirerPy import inquirer # before result = inquirer.text(message="Name:", vi_mode=True).execute() # after import os os.environ["INQUIRERPY_VI_MODE"] = "true" result = inquirer.text(message="Name").execute() ``` -------------------------------- ### InquirerPy Select Prompt Multiple Selection Example Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/list.md Demonstrates how to enable multiple selection in the `InquirerPy` select prompt using the `multiselect=True` parameter. It also illustrates how to pre-select certain choices by setting the `enabled=True` attribute on `Choice` instances or within dictionary representations of choices. ```python from InquirerPy import inquirer from InquirerPy.base.control import Choice choices = [ Choice(1, enabled=True), Choice(2, enabled=True), 3, 4, ] result = inquirer.select( message="Selct one:", choices=choices, multiselect=True ).execute() ``` -------------------------------- ### API Reference: InquirerPy.containers.validation Module Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/api.md Documents the API for the 'validation' container, which manages and displays validation feedback for user input, guiding users to correct entries. ```APIDOC .. automodule:: InquirerPy.containers.validation :members: ``` -------------------------------- ### Customize KeyboardInterrupt Keybindings with Classic InquirerPy Syntax Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/raise_kbi.md Shows how to customize `KeyboardInterrupt` and skip keybindings using the `keybindings` parameter in InquirerPy's `prompt` function. This example reassigns `ctrl-c` to skip and `ctrl-d` to interrupt. ```python from InquirerPy import prompt result = prompt( questions=[ { "type": "list", "message": "Select one:", "choices": ["Fruit", "Meat", "Drinks", "Vegetable"], "mandatory_message": "Prompt is mandatory, terminate the program using ctrl-d", }, ], keybindings={"skip": [{"key": "c-c"}], "interrupt": [{"key": "c-d"}]}, ) ``` -------------------------------- ### Customize KeyboardInterrupt Keybindings with InquirerPy Inquirer Syntax Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/raise_kbi.md Demonstrates customizing `KeyboardInterrupt` and skip keybindings using the `keybindings` parameter in InquirerPy's `inquirer` fluent API. This example reassigns `ctrl-c` to skip and `ctrl-d` to interrupt. ```python from InquirerPy import inquirer result = inquirer.select( message="Select one:", choices=["Fruit", "Meat", "Drinks", "Vegetable"], mandatory_message="Prompt is mandatory, terminate the program using ctrl-d", keybindings={"skip": [{"key": "c-c"}], "interrupt": [{"key": "c-d"}]}, ).execute() ``` -------------------------------- ### Implement Custom prompt_toolkit Validator for InquirerPy Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/validator.md Shows how to create a custom validator by inheriting from `prompt_toolkit.validation.Validator`. This example validates for non-empty input and raises a `ValidationError` with a custom message if validation fails, removing the need for `invalid_message`. ```python from prompt_toolkit.validation import ValidationError, Validator class EmptyInputValidator(Validator): def validate(self, document): if not len(document.text) > 0: raise ValidationError( message="Input cannot be empty.", cursor_position=document.cursor_position, ) ``` -------------------------------- ### Apply `prompt_toolkit.filters.base.Condition` to InquirerPy Keybindings Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/kb.md This example illustrates how to use a `prompt_toolkit.filters.base.Condition` object as a dynamic filter for InquirerPy keybindings. By decorating a function with `@Condition`, you can define custom logic that determines whether specific key actions, such as 'down' and 'up', are active at runtime. ```python from prompt_toolkit.filters.base import Condition @Condition def special_vim(): # logic ... return True keybindings = { "down": [ {"key": "c-j", "filter": special_vim}, ], "up": [ {"key": "c-k", "filter": special_vim}, ], "toggle-all-false": [{"key": "alt-x"}], } # .... ``` -------------------------------- ### Customizing Confirm/Reject Letters - Classic Syntax (PyInquirer) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/confirm.md Demonstrates how to customize the confirmation and rejection letters (e.g., 's' for 'Sim', 'n' for 'Não') and use a `transformer` function to change the displayed output based on the result. This example uses the classic PyInquirer syntax for prompt definition. ```python from InquirerPy import prompt questions = [ { "type": "confirm", "default": True, "message": "Proceed?", "confirm_letter": "s", "reject_letter": "n", "transformer": lambda result: "SIm" if result else "Não", } ] result = prompt(questions=questions) ``` -------------------------------- ### InquirerPy Select Prompt Default Choice Example Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/list.md Illustrates how to set a default highlighted choice in the `InquirerPy` select prompt using the `default` parameter. It also clarifies the distinction between the `default` parameter and the `enabled` parameter of `Choice` objects, which is used for pre-selection in multiselect mode. ```python from InquirerPy.base import Choice choices = [ Choice(1, enabled=True), # enabled by default Choice(2) # not enabled ] ``` -------------------------------- ### InquirerPy Prompt with `filter` Parameter (Classic Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/dynamic.md Demonstrates using the `filter` parameter with `InquirerPy.prompt` in the classic syntax. This example shows how to convert a string input (age) to an integer using a lambda function as the filter, combined with a `NumberValidator` for input validation. ```python from InquirerPy import prompt from InquirerPy.validator import NumberValidator questions = [ { "type": "input", "message": "Age:", "filter": lambda result: int(result), "validate": NumberValidator() } ] result = prompt(questions=questions) ``` -------------------------------- ### Enable Exact Sub-String Matching in Fuzzy Prompt Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/fuzzy.md These Python examples demonstrate how to configure the fuzzy prompt to use exact sub-string matching instead of the default fzy algorithm. The `match_exact` parameter enables this feature, and `exact_symbol` sets an indicator for exact matches in the prompt's display. ```python from InquirerPy import prompt questions = [ { "type": "fuzzy", "message": "Select actions:", "choices": ["hello", "weather", "what", "whoa", "hey", "yo"], "match_exact": True, "exact_symbol": " E" # indicator of exact match } ] result = prompt(questions=questions) ``` ```python from InquirerPy import inquirer result = inquirer.fuzzy( message="Select actions:", choices=["hello", "weather", "what", "whoa", "hey", "yo"], match_exact=True, exact_symbol=" E" # indicator of exact match ).execute() ``` -------------------------------- ### Configure Default Value for InquirerPy Number Prompt Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/number.md Demonstrates how to set the initial value of the number prompt. By default, it's '0', but setting the `default` parameter to `None` allows the input buffer to start empty, providing flexibility for user input. ```python from InquirerPy import prompt questions = [ { "type": "number", "message": "Number:", "default": None, } ] result = prompt(questions) ``` ```python from InquirerPy import inquirer result = inquirer.number(message="Number:", default=None).execute() ``` -------------------------------- ### Configure InquirerPy Style via Environment Variable (Alternate Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/env.md This example illustrates how to apply styling to InquirerPy's `inquirer` object using an environment variable. It contrasts direct parameter passing with setting the `INQUIRERPY_STYLE_QUESTIONMARK` environment variable, achieving the same styling effect without modifying the `inquirer` call. ```python from InquirerPy import inquirer from InquirerPy import get_style # before result = inquirer.confirm(message="Confirm?", style=get_style({"questionmark": "#ffffff"})).execute() # after import os os.environ["INQUIRERPY_STYLE_QUESTIONMARK"] = "#ffffff" result = inquirer.confirm(message="Confirm?").execute() ``` -------------------------------- ### InquirerPy Prompt Configuration with raise_keyboard_interrupt Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/raise_kbi.md These examples demonstrate how to configure InquirerPy prompts using the `raise_keyboard_interrupt` parameter set to `False`. This changes the default `ctrl-c` behavior to skip the prompt and enables `ctrl-d` to raise a `KeyboardInterrupt`, providing a Python REPL-like interaction experience. ```python from InquirerPy import prompt result = prompt( questions=[ { "type": "list", "message": "Select one:", "choices": ["Fruit", "Meat", "Drinks", "Vegetable"], "mandatory_message": "Prompt is mandatory, terminate the program using ctrl-d", }, ], raise_keyboard_interrupt=False, ) ``` ```python from InquirerPy import inquirer result = inquirer.select( message="Select one:", choices=["Fruit", "Meat", "Drinks", "Vegetable"], raise_keyboard_interrupt=False, mandatory_message="Prompt is mandatory, terminate the program using ctrl-d", ).execute() ``` -------------------------------- ### Dynamic Prompt Parameters with InquirerPy Classic Syntax Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/dynamic.md Demonstrates how to dynamically set 'default' and 'message' parameters in InquirerPy's classic syntax using functions that receive the session result. The example shows chaining prompts where subsequent prompts depend on previous answers. ```python from InquirerPy import prompt from InquirerPy.validator import NumberValidator def get_message(result): return f"Hi {result['confirm_name']}, enter your age:" questions = [ { "type": "input", "message": "Name:", "name": "name", }, { "type": "input", "message": "Confirm Name:", "name": 'confirm_name', "default": lambda result: result["name"], # inline lambda to make the code shorter }, { "type": "input", "message": get_message, # use a named function for more complex logic "name": 'age', "validate": NumberValidator(), }, ] result = prompt(questions) ``` -------------------------------- ### InquirerPy.prompts.expand.ExpandHelp Class Reference Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/expand.md API documentation for the `ExpandHelp` class, which allows customization of the expansion key and help message displayed for the InquirerPy expand prompt. This class provides control over the user interface elements related to the expand functionality. ```APIDOC InquirerPy.prompts.expand.ExpandHelp ``` -------------------------------- ### Apply Transformer to Checkbox Prompt Output in Python Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/dynamic.md Demonstrates how to use the `transformer` parameter with `InquirerPy` checkbox prompts to visually modify the displayed output. Instead of showing a list of selected regions, the transformer function converts the list into a concise string indicating the number of regions selected. This example showcases both the classic `prompt` syntax and the alternate `inquirer` syntax. ```python """ Without transformer: ? Select regions: ["us-east-1", "us-west-1"] With transformer: ? Select regions: 2 regions selected """ from InquirerPy import prompt from InquirerPy.base.control import Choice choices = [ Choice("ap-southeast-2", name="Sydney", enabled=True), Choice("ap-southeast-1", name="Singapore", enabled=False), "us-east-1", "us-east-2", ] questions = [ { "type": "checkbox", "message": "Select regions:", "choices": choices, "cycle": False, "transformer": lambda result: f"{len(result)} region{'s' if len(result) > 1 else ''} selected", } ] result = prompt(questions=questions) ``` ```python """ Without transformer: ? Select regions: ["us-east-1", "us-west-1"] With transformer: ? Select regions: 2 regions selected """ from InquirerPy import inquirer from InquirerPy.base.control import Choice choices = [ Choice("ap-southeast-2", name="Sydney", enabled=True), Choice("ap-southeast-1", name="Singapore", enabled=False), "us-east-1", "us-east-2", ] regions = inquirer.checkbox( message="Select regions:", choices=choices, cycle=False, transformer=lambda result: f"{len(result)} region{'s' if len(result) > 1 else ''} selected", ).execute() ``` -------------------------------- ### Basic Usage with InquirerPy Classic Syntax Source: https://github.com/kazhala/inquirerpy/blob/master/docs/index.md Demonstrates how to use InquirerPy's classic syntax, similar to PyInquirer, to create interactive command-line prompts. It defines a list of question dictionaries, each specifying the prompt type, message, and optional choices or name, then uses the `prompt()` function to collect user input. ```Python from InquirerPy import prompt questions = [ {"type": "input", "message": "What's your name:", "name": "name"}, { "type": "list", "message": "What's your favourite programming language:", "choices": ["Go", "Python", "Rust", "JavaScript"], }, {"type": "confirm", "message": "Confirm?"}, ] result = prompt(questions) name = result["name"] fav_lang = result[1] confirm = result[2] ``` -------------------------------- ### InquirerPy Available Key Syntax Reference Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/kb.md This API documentation lists the various special keys and their corresponding syntax recognized by InquirerPy for defining custom keybindings. It serves as a reference for developers to understand the available key combinations for prompt interactions. ```APIDOC Name | Possible keys ------------------ | ------------------------------------------------------- Escape | `escape` Arrows | `left`, `right`, `up`, `down` Navigation | `home`, `end`, `delete`, `pageup`, `pagedown`, `insert` Control+lowercase | `c-a`, `c-b` ... `c-y`, `c-z` Control+uppercase | `c-A`, `c-B` ... `c-Y`, `c-Z` Control + arrow | `c-left`, `c-right`, `c-up`, `c-down` Other control keys | `c-@`, `c-\`, `c-]`, `c-^`, `c-\_`, `c-delete` Shift + arrow | s-left, s-right, s-up, s-down Other shift keys | `s-delete`, `s-tab` F-keys | `f1`, `f2`, .... `f23`, `f24` Alt+lowercase | `alt-a`, `alt-b` ... `alt-y`, `alt-z` Alt+uppercase | `alt-A`, `alt-B` ... `alt-Y`, `alt-Z` ``` -------------------------------- ### Define Custom Callable Validator for InquirerPy Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/validator.md Provides an example of a Python function that can be used as a custom callable validator for InquirerPy prompts. It checks if the input result has a length greater than zero, returning a boolean. ```python def validator(result) -> bool: """Ensure the input is not empty.""" return len(result) > 0 ``` -------------------------------- ### InquirerPy ListPrompt Class API Reference Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/list.md Provides API documentation for the `InquirerPy.prompts.list.ListPrompt` class. This reference outlines the structure and purpose of the class responsible for handling list selection prompts within the InquirerPy library. ```APIDOC InquirerPy.prompts.list.ListPrompt: # No methods or properties explicitly documented in the provided text. ``` -------------------------------- ### API Reference: InquirerPy.resolver.prompt Function Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompt.md Documents the `prompt` function from `InquirerPy.resolver`, which is the primary entry point for the Classic Syntax (PyInquirer) in InquirerPy. This function orchestrates the interactive question-and-answer flow. ```APIDOC InquirerPy.resolver.prompt ``` -------------------------------- ### Validate Number with InquirerPy Alternate Inquirer Syntax Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/validator.md Example demonstrating the alternate `inquirer.text` syntax for validating numeric inputs using `NumberValidator`. This streamlined approach simplifies the definition of number validation for text prompts. ```python from InquirerPy import inquirer from InquirerPy.validator import NumberValidator result = inquirer.text(message="Age:", validate=NumberValidator()).execute() ``` -------------------------------- ### Configure Keybinding for Completion Popup Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/input.md Demonstrates the JSON configuration to force a completion window popup using 'c-space' (ctrl-space) keybinding for InquirerPy prompts. ```json { "completion": [{"key": "c-space"}] # force completion popup } ``` -------------------------------- ### InquirerPy.prompts.expand.ExpandPrompt Class Reference Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/expand.md API documentation for the `ExpandPrompt` class, representing the core expand prompt type within InquirerPy. This class defines the behavior and structure of the expandable choice selection prompt. ```APIDOC InquirerPy.prompts.expand.ExpandPrompt ``` -------------------------------- ### Validate Number with InquirerPy Classic Prompt Syntax Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/validator.md Example demonstrating how to use `NumberValidator` with the classic `prompt` function in InquirerPy to ensure user input is a valid number. The `float_allowed` parameter can be set to `False` to restrict input to integers only. ```python from InquirerPy import prompt from InquirerPy.validator import NumberValidator result = prompt( [ { "type": "text", "message": "Age:", "validate": NumberValidator( message="Input should be number", float_allowed=False ), } ] ) ``` -------------------------------- ### Configure InquirerPy FilePath Prompt Keybindings Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/filepath.md This JSON snippet demonstrates how to configure custom keybindings for the InquirerPy filepath prompt. Specifically, it shows how to force the completion window to pop up using the 'ctrl-space' key combination. ```json { "completion": [{"key": "c-space"}] } ``` -------------------------------- ### Validate Password with InquirerPy Alternate Inquirer Syntax Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/validator.md Example demonstrating the alternate `inquirer.secret` syntax for validating passwords using `PasswordValidator`. This approach provides a more concise way to define the prompt and validation rules, directly chaining the validation logic. ```python from InquirerPy import inquirer from InquirerPy.validator import PasswordValidator result = inquirer.secret( message="New Password:", validate=PasswordValidator( length=8, cap=True, special=True, number=True, message="Password does not meet compliance", ), ).execute() ``` -------------------------------- ### InquirerPy.prompts.expand.ExpandChoice Class Reference Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/expand.md API documentation for the `ExpandChoice` class, used to define individual choices for the InquirerPy expand prompt. It allows specifying a display name, a value, and a unique single-character key for direct selection. ```APIDOC InquirerPy.prompts.expand.ExpandChoice ``` -------------------------------- ### API Reference: InquirerPy.prompts.input.InputPrompt Class Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/input.md API documentation for the `InputPrompt` class within InquirerPy, which serves as the core implementation for text input prompts. ```APIDOC InquirerPy.prompts.input.InputPrompt ``` -------------------------------- ### Prompting with InquirerPy (Classic Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/README.md Demonstrates the classic PyInquirer-like syntax for creating interactive command-line prompts using InquirerPy. It defines a list of question dictionaries, specifying type, message, and name, then uses the `prompt` function to collect user input. ```python from InquirerPy import prompt questions = [ {"type": "input", "message": "What's your name:", "name": "name"}, {"type": "confirm", "message": "Confirm?", "name": "confirm"} ] result = prompt(questions) name = result["name"] confirm = result["confirm"] ``` -------------------------------- ### Python: Prompting with Multiple Questions Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompt.md Demonstrates how to use the `InquirerPy.prompt` function to ask multiple questions sequentially. The `questions` parameter is provided as a list of dictionaries, each representing a distinct prompt type with its message. ```python from InquirerPy import prompt questions = [ { "type": "input", "message": "Enter your name:", }, { "type": "Confirm", "message": "Confirm?", } ] result = prompt(questions=questions) ``` -------------------------------- ### InquirerPy.prompts.confirm.ConfirmPrompt Class Reference Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/confirm.md API documentation for the `ConfirmPrompt` class, which handles the 'confirm' prompt type in InquirerPy. It outlines the key parameters available for configuring the prompt's behavior and appearance. ```APIDOC ConfirmPrompt: __init__( message: str, default: bool = False, confirm_letter: str = 'y', reject_letter: str = 'n', transformer: callable = None, **kwargs ) Parameters: message: (str) The message to display for the prompt. default: (bool) The default value for the prompt (True/False). Affects initial capitalization of confirm/reject letters and the value returned on Enter. confirm_letter: (str) The single character key that confirms the prompt. Defaults to 'y'. reject_letter: (str) The single character key that rejects the prompt. Defaults to 'n'. transformer: (callable) A function that takes the boolean result (True/False) and returns a string to be displayed as the prompt's current value. Useful for localization. ``` -------------------------------- ### API Reference: InquirerPy.containers.instruction Module Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/api.md Details the API for the 'instruction' container, used to display helpful instructions or hints to the user during a prompt interaction. ```APIDOC .. automodule:: InquirerPy.containers.instruction :members: ``` -------------------------------- ### InquirerPy API Migration: EditorPrompt Support Source: https://github.com/kazhala/inquirerpy/blob/master/README.md Notes on the `EditorPrompt` feature during migration from PyInquirer. InquirerPy currently does not support this specific prompt type, indicating a functional difference from its predecessor. ```APIDOC EditorPrompt: InquirerPy does not support editor prompt as of now. ``` -------------------------------- ### InquirerPy API Migration: CheckboxPrompt Parameter Mapping Source: https://github.com/kazhala/inquirerpy/blob/master/README.md Details the mapping of incompatible parameters for `CheckboxPrompt` when migrating from PyInquirer to InquirerPy. This table clarifies how old parameter names correspond to their new equivalents in InquirerPy. ```APIDOC CheckboxPrompt Parameter Mapping: - PyInquirer: pointer_sign -> InquirerPy: pointer - PyInquirer: selected_sign -> InquirerPy: enabled_symbol - PyInquirer: unselected_sign -> InquirerPy: disabled_symbol ``` -------------------------------- ### Unit Testing InquirerPy Classic Syntax Prompt Function Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/faq.md This snippet demonstrates how to unit test a Python function that utilizes the `InquirerPy.prompt` function (classic syntax). It shows how to define a function that uses `prompt` and then how to mock `prompt` in a `unittest.TestCase` to control its return value for testing purposes. ```python from InquirerPy import prompt def get_name(): return prompt({"type": "input", "message": "Name:"}) ``` ```python import unittest from unittest.mock import patch from Module.somefunction import get_name class TestPrompt(unittest.TestCase): @patch("Module.somefunction.prompt") def test_get_name(self, mocked_prompt): mocked_prompt.return_value = "hello" result = get_name() self.assertEqual(result, "hello") ``` -------------------------------- ### Configure InquirerPy Keyboard Interrupt Behavior via Environment Variable (Alternate Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/env.md This example illustrates how to suppress `KeyboardInterrupt` exceptions for InquirerPy's `inquirer` object using an environment variable. It shows the transition from passing `raise_keyboard_interrupt=False` to relying on the `INQUIRERPY_NO_RAISE_KBI` environment variable. ```python from InquirerPy import inquirer # before result = inquirer.text(message="Name:", vi_mode=True).execute(raise_keyboard_interrupt=False) # after import os os.environ["INQUIRERPY_NO_RAISE_KBI"] = "true" result = inquirer.text(message="Name").execute() ``` -------------------------------- ### Prompting with InquirerPy (Alternate Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/README.md Illustrates an alternative, more direct syntax for creating interactive command-line prompts with InquirerPy. This approach uses the `inquirer` object's methods like `text` and `confirm` directly, chaining the `.execute()` call to retrieve the input. ```python from InquirerPy import inquirer name = inquirer.text(message="What's your name:").execute() confirm = inquirer.confirm(message="Confirm?").execute() ``` -------------------------------- ### Default InquirerPy Keybindings Structure Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/kb.md Illustrates the default keybinding structure for InquirerPy prompts, showing common actions like 'answer', 'interrupt', and 'skip' mapped to their respective key combinations. ```python { "answer": [{"key": "enter"}], # answer the prompt "interrupt": [{"key": "c-c"}], # raise KeyboardInterrupt "skip": [{"key": "c-z"}], # skip the prompt } ``` -------------------------------- ### InquirerPy API Migration: Style Key Mapping Source: https://github.com/kazhala/inquirerpy/blob/master/README.md Outlines the mapping of incompatible style keys when migrating from PyInquirer to InquirerPy. While InquirerPy supports most PyInquirer style keys, this entry highlights specific changes and notes that overall styling behavior may differ, recommending a review of the InquirerPy Style documentation. ```APIDOC Style Key Mapping: - PyInquirer: selected -> InquirerPy: pointer Note: InquirerPy supports all PyInquirer style keys, but styling works slightly differently. Please refer to the InquirerPy Style documentation for detailed information. ``` -------------------------------- ### Enable Vim Mode for InquirerPy Prompt (Alternate Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/kb.md Shows how to enable Vim keybindings for an InquirerPy select prompt using the `inquirer.select` function with the `vi_mode=True` parameter, providing a more concise way to define prompts. ```python from InquirerPy import inquirer result = inquirer.select( message="Select one:", choices=["Fruit", "Meat", "Drinks", "Vegetable"], vi_mode=True, ).execute() ``` -------------------------------- ### Validate Minimum Selections in InquirerPy Prompt (Classic Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/validator.md Illustrates how to use a lambda function with the 'validate' parameter to ensure at least 2 options are selected in a 'list' type multiselect prompt using InquirerPy's classic prompt syntax. An 'invalid_message' guides the user. ```python from InquirerPy import prompt result = prompt( [ { "type": "list", "message": "Select toppings:", "choices": ["Bacon", "Chicken", "Cheese", "Pineapple"], "multiselect": True, "validate": lambda selection: len(selection) >= 2, "invalid_message": "Select at least 2 toppings." } ] ) ``` -------------------------------- ### Validate Password with InquirerPy Classic Prompt Syntax Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/validator.md Example demonstrating how to use `PasswordValidator` with the classic `prompt` function in InquirerPy to validate user-entered passwords against specified criteria like minimum length, uppercase, special characters, and numbers. The validation message is displayed if the input does not meet compliance. ```python from InquirerPy import prompt from InquirerPy.validator import PasswordValidator result = prompt( [ { "type": "secret", "message": "New Password:", "validate": PasswordValidator( length=8, cap=True, special=True, number=True, message="Password does not meet compliance", ), } ] ) ``` -------------------------------- ### Apply Foreground and Background Color Style Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/style.md Demonstrates how to specify both foreground (`fg`) and background (`bg`) colors using hexadecimal notation within the style dictionary for a prompt component like `questionmark`. This allows for more precise color control. ```python { "questionmark": "fg:#e5c07b bg:#ffffff" } ``` -------------------------------- ### InquirerPy Keybinding Parameter to Environment Variable Mapping Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/env.md This API documentation outlines the mapping for InquirerPy's keybinding parameters to their corresponding environment variables. It specifically details how to enable vi-mode using an environment variable. ```APIDOC Parameter | Environment Variable ---------------|-------------------- `vi_mode=True` | INQUIRERPY_VI_MODE ``` -------------------------------- ### Enable Auto-Completion with Alternate InquirerPy Syntax Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/input.md Shows how to integrate a dictionary-based completer with the `inquirer.text` method in InquirerPy's alternate syntax. The completer offers nested suggestions like 'hello' -> 'world', 'foo' -> 'boo', and 'fizz' -> 'bazz'. ```python from InquirerPy import inquirer completer = { "hello": { "world": None }, "foo": { "boo": None }, "fizz": { "bazz": None } } result = inquirer.text(message="FooBoo:", completer=completer).execute() ``` -------------------------------- ### InquirerPy `keybindings` Parameter API Reference Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/kb.md API documentation for the `keybindings` parameter, detailing its expected dictionary structure where keys represent actions and values are lists of binding dictionaries, each containing 'key' and 'filter' properties. ```APIDOC keybindings: type: Dict[str, List[Dict[str, Union[str, "FilterOrBool", List[str]]]]] description: A dictionary where the `key` is the **action** and the `value` should be a list of keys that will be the **bindings** to trigger it. binding_properties: - name: key type: Union[str, List[str]] description: The key combination for the binding. - name: filter type: Union[Filter, bool] description: A filter or boolean to apply to the binding. ``` -------------------------------- ### Define Custom Keybindings with InquirerPy Prompt (Classic Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/kb.md This Python snippet demonstrates how to set up custom keybindings for an InquirerPy prompt using the classic `prompt` function. It shows how to map specific key sequences, like 'ctrl-a' followed by 'space', to actions such as 'toggle-all' for a multiselect list, along with 'skip' and 'interrupt' actions. ```python from InquirerPy import prompt keybindings = { "skip": [{"key": "c-c"}], "interrupt": [{"key": "c-d"}], "toggle-all": [{"key": ["c-a", "space"]}], } result = prompt( questions=[ { "type": "list", "message": "Select one:", "choices": ["Fruit", "Meat", "Drinks", "Vegetable"], "multiselect": True }, ], keybindings=keybindings, ) ``` -------------------------------- ### Configure InquirerPy Style via Environment Variable (Classic Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/env.md This snippet demonstrates how to set a specific style for InquirerPy prompts using an environment variable. It shows the 'before' state where style is passed as a parameter to `prompt`, and the 'after' state where the style is configured via `INQUIRERPY_STYLE_QUESTIONMARK` environment variable, making the `prompt` call cleaner. ```python from InquirerPy import prompt from InquirerPy import get_style # before result = prompt(questions=[{"type": "confirm", "message": "Confirm?"}], style={"questionmark": "#ffffff"}) # after import os os.environ["INQUIRERPY_STYLE_QUESTIONMARK"] = "#ffffff" result = prompt(questions=[{"type": "confirm", "message": "Confirm?"}]) ``` -------------------------------- ### Enable Vim Mode for InquirerPy Prompt (Classic Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/kb.md Demonstrates how to enable Vim keybindings for an InquirerPy list prompt using the classic `prompt` function by setting the `vi_mode` parameter to `True`. ```python from InquirerPy import prompt result = prompt( questions=[ { "type": "list", "message": "Select one:", "choices": ["Fruit", "Meat", "Drinks", "Vegetable"], }, ], vi_mode=True, ) ``` -------------------------------- ### Configure Keybinding for Toggling Exact Match Algorithm Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/fuzzy.md This JSON snippet illustrates the configuration structure for defining keybindings, specifically for toggling the string matching algorithm between fuzzy and exact modes within the InquirerPy fuzzy prompt. ```json { "toggle-exact": [] # toggle string matching algorithm between fuzzy or exact } ``` -------------------------------- ### Configure InquirerPy Keybinding (vi_mode) via Environment Variable (Classic Syntax) Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/env.md This snippet demonstrates how to enable vi-mode keybindings for InquirerPy prompts using an environment variable. It contrasts setting `vi_mode=True` directly with using the `INQUIRERPY_VI_MODE` environment variable for global configuration. ```python from InquirerPy import prompt # before result = prompt(questions=[{"type": "input", "message": "Name:"}], vi_mode=True) # after import os os.environ["INQUIRERPY_VI_MODE"] = "true" result = prompt(questions=[{"type": "input", "message": "Name:"}]) ``` -------------------------------- ### InquirerPy Select Prompt Default Keybindings Source: https://github.com/kazhala/inquirerpy/blob/master/docs/pages/prompts/list.md Defines the default keybindings for navigation and selection within the `InquirerPy` select prompt. This Python dictionary maps common actions like moving up/down, toggling choices, and toggling all choices to specific key combinations. ```python { "down": [ {"key": "down"}, {"key": "c-n"} # move down ], "up": [ {"key": "up"}, {"key": "c-p"} # move up ], "toggle": [ {"key": "space"} # toggle choices ], "toggle-down": [ {"key": "c-i"} # toggle choice and move down (tab) ], "toggle-up": [ {"key": "s-tab"} # toggle choice and move up (shift+tab) ], "toggle-all": [ {"key": "alt-r"}, # toggle all choices {"key": "c-r"} ], "toggle-all-true": [ {"key": "alt-a"}, # toggle all choices true {"key": "c-a"} ], "toggle-all-false": [] # toggle all choices false } ```