### Install example dependencies Source: https://inquirerpy.readthedocs.io/en/latest/_sources/index.md.txt Installs the dependencies required by the example scripts. ```bash pip3 install -r examples/requirements.txt ``` -------------------------------- ### Run an example script Source: https://inquirerpy.readthedocs.io/en/latest/_sources/index.md.txt Shows two equivalent ways to run an example, using the `rawlist` example as an illustration. ```bash python3 -m examples.classic.rawlist # or python3 examples/classic/rawlist ``` -------------------------------- ### List all available examples Source: https://inquirerpy.readthedocs.io/en/latest/_sources/index.md.txt Lists the example Python files in the main examples directory and its classic and alternate subdirectories. Note: `demo_alternate.py` and `demo_classic.py` require the boto3 package and AWS credentials. ```bash ls examples/*.py ls examples/classic/*.py ls examples/alternate/*.py ``` -------------------------------- ### Classic Syntax Example Source: https://inquirerpy.readthedocs.io/en/latest/pages/dynamic.html Example using classic PyInquirer-style syntax with prompt(questions=...). ```APIDOC ```python from InquirerPy import prompt from InquirerPy.base.control import Choice from InquirerPy.separator import Separator questions = [ { "type": "list", "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", }, ] result = prompt(questions=questions) ``` ``` -------------------------------- ### Synchronous prompt execution with execute() Source: https://inquirerpy.readthedocs.io/en/latest/_sources/pages/inquirer.md.txt Each prompt contains a function `execute` to start the prompt synchronously. This example shows a text prompt and prints the result. ```python from InquirerPy import inquirer def main(): result = inquirer.text(message="Name:").execute() if __name__ == "__main__": main() ``` -------------------------------- ### Asynchronous prompt execution with execute_async() Source: https://inquirerpy.readthedocs.io/en/latest/_sources/pages/inquirer.md.txt Each prompt contains a function `execute_async` to start the prompt asynchronously. This example shows an async text prompt and runs it with asyncio. ```python import asyncio from InquirerPy import inquirer async def main(): result = await inquirer.text(message="Name:").execute_async() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Asynchronous execution setup Source: https://inquirerpy.readthedocs.io/en/latest/_sources/pages/prompt.md.txt Initializes the asynchronous prompt functionality using prompt_async. ```python import asyncio from InquirerPy import inquirer, prompt_async ``` -------------------------------- ### Basic Expand Prompt Usage Source: https://inquirerpy.readthedocs.io/en/latest/_modules/InquirerPy/prompts/expand.html A simple example demonstrating how to initialize and execute an expand prompt with a single choice. ```python >>> from InquirerPy import inquirer >>> result = inquirer.expand(message="Select one:", choices=[{"name": "1", "value": "1", "key": "a"}]).execute() >>> print(result) "1" ``` -------------------------------- ### Create a Virtual Environment Source: https://inquirerpy.readthedocs.io/en/latest/_sources/index.md.txt Creates and activates a Python virtual environment, which is recommended before installing dependencies. ```bash python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Classic Syntax (PyInquirer) fuzzy prompt example Source: https://inquirerpy.readthedocs.io/en/latest/pages/prompts/fuzzy.html Uses the classic PyInquirer syntax with the prompt() function. The example downloads a sample file and demonstrates searching with 100k words. It includes a dynamic choices function and a multiselect question with validation. ```python import urllib.request from contextlib import ExitStack from pathlib import Path from InquirerPy import prompt def get_choices(_): p = Path(__file__).resolve().parent.joinpath("sample.txt") choices = [] result = [] with ExitStack() as stack: if not p.exists(): file = stack.enter_context(p.open("w+")) sample = stack.enter_context( urllib.request.urlopen( "https://assets.kazhala.me/InquirerPy/sample.txt" ) ) file.write(sample.read().decode()) file.seek(0, 0) else: file = stack.enter_context(p.open("r")) for line in file.readlines(): choices.append(line[:-1]) for choice in choices: if not choice: continue result.append(choice) return result def main(): questions = [ { "type": "fuzzy", "message": "Select actions:", "choices": ["hello", "weather", "what", "whoa", "hey", "yo"], "default": "he", "max_height": "70%", }, { "type": "fuzzy", "message": "Select preferred words:", "choices": get_choices, "multiselect": True, "validate": lambda result: len(result) > 1, "invalid_message": "minimum 2 selection", "max_height": "70%", }, ] result = prompt(questions=questions) if __name__ == "__main__": main() ``` -------------------------------- ### Basic number prompt usage Source: https://inquirerpy.readthedocs.io/en/latest/_modules/InquirerPy/prompts/number.html A simple example demonstrating how to initialize and execute a number prompt to capture user input. ```python >>> from InquirerPy import inquirer >>> result = inquirer.number(message="Enter number:").execute() >>> print(result) 0 ``` -------------------------------- ### InquirerPy filepath prompt usage example Source: https://inquirerpy.readthedocs.io/en/latest/_modules/InquirerPy/prompts/filepath.html Example showing how to use the filepath prompt from InquirerPy. It prompts the user for a path and prints the result, which is a string like '/home/ubuntu/README.md'. ```python >>> from InquirerPy import inquirer >>> result = inquirer.filepath(message="Enter a path:").execute() >>> print(result) /home/ubuntu/README.md ``` -------------------------------- ### Classic Syntax (PyInquirer) example Source: https://inquirerpy.readthedocs.io/en/latest/_sources/pages/prompts/list.md.txt Example using the classic PyInquirer syntax for the select prompt. The code is included via a literalinclude directive, so the actual code is not visible on this page. ```python .. literalinclude :: ../../../examples/classic/list.py :language: python ``` -------------------------------- ### Printing output on keypress with patched_print Source: https://inquirerpy.readthedocs.io/en/latest/_sources/pages/kb.md.txt A simple example that prints 'Hello World' to the terminal when 'alt-a' is pressed during a text prompt. ```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() ``` -------------------------------- ### ConfirmPrompt Source: https://inquirerpy.readthedocs.io/en/latest/pages/api.html Documentation for the ConfirmPrompt class, including constructor parameters and an example. ```APIDOC ## ConfirmPrompt ### Description Creates a confirm prompt that provides two options (confirm/deny) and is controlled via a single keypress. It is a wrapper class around `PromptSession`. ### Class `InquirerPy.prompts.confirm.ConfirmPrompt` ### Constructor Parameters - **message** (Union[str, Callable[[InquirerPySessionResult], str]]) - Required - The question to ask the user. - **style** (Optional[InquirerPyStyle]) - Optional - An `InquirerPyStyle` instance. - **vi_mode** (bool) - Optional - Used for compatibility. - **default** (Union[Any, Callable[[InquirerPySessionResult], Any]]) - Optional - Set the default value of the prompt, should be either True or False. - **qmark** (str) - Optional - Question mark symbol displayed in front of the question before it is answered. - **amark** (str) - Optional - Answer mark symbol displayed in front of the question after it is answered. - **instruction** (str) - Optional - Short instruction to display next to the question. - **long_instruction** (str) - Optional - Long instructions to display at the bottom of the prompt. - **transformer** (Optional[Callable[[bool], Any]]) - Optional - A function that performs additional transformation on the value printed to the terminal. - **filter** (Optional[Callable[[bool], Any]]) - Optional - A function that performs additional transformation on the result. - **keybindings** (Optional[Dict[str, List[Dict[str, Union[str, FilterOrBool, List[str]]]]]]) - Optional - Customise the builtin keybindings. - **wrap_lines** (bool) - Optional - Soft wrap question lines when question exceeds terminal width. - **confirm_letter** (str) - Optional - Letter used to confirm the prompt. Default is 'y'. - **reject_letter** (str) - Optional - Letter used to reject the prompt. Default is 'n'. - **raise_keyboard_interrupt** (bool) - Optional - Raise `KeyboardInterrupt` when ctrl-c is pressed. - **mandatory** (bool) - Optional - Indicate if the prompt is mandatory. - **mandatory_message** (str) - Optional - Error message to show when user attempts to skip mandatory prompt. - **session_result** (Optional[Dict[Union[str, int], Optional[Union[str, bool, List[Any]]]]]) - Optional - Used internally for Classic Syntax (PyInquirer). - **input** (Optional[Input]) - Optional - Used internally and will be removed in future updates. - **output** (Optional[Output]) - Optional - Used internally and will be removed in future updates. ### Return Type None ### Example ```python >>> from InquirerPy import inquirer >>> result = inquirer.confirm(message="Confirm?").execute() >>> print(result) True ``` ``` -------------------------------- ### Alternate Syntax Keybindings Source: https://inquirerpy.readthedocs.io/en/latest/_sources/pages/kb.md.txt Example using the inquirer.select builder pattern to define custom keybindings. ```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() ``` -------------------------------- ### FilePathCompleter.get_completions Source: https://inquirerpy.readthedocs.io/en/latest/pages/api.html Get a list of valid system paths. ```APIDOC ## FilePathCompleter.get_completions ### Description Get a list of valid system paths. ### Method Method ### Signature get_completions(document, complete_event) ### Parameters - **document** - Required - The document to complete. - **complete_event** - Required - The completion event. ### Return Type Generator[prompt_toolkit.completion.base.Completion, None, None] ``` -------------------------------- ### Classic Syntax Keybindings Source: https://inquirerpy.readthedocs.io/en/latest/_sources/pages/kb.md.txt Example using the classic prompt function to define custom keybindings for skipping, interrupting, and toggling selections. ```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, ) ``` -------------------------------- ### Separator usage example Source: https://inquirerpy.readthedocs.io/en/latest/pages/api.html Demonstrates using the Separator class to add a visual separator between choices in a select prompt. ```python >>> from InquirerPy import inquirer >>> choices = [1, 2, Separator(), 3] >>> inquirer.select(message="", choices=choices) ``` -------------------------------- ### Create a text input prompt with inquirer.text Source: https://inquirerpy.readthedocs.io/en/latest/pages/api.html Shows how to create a text prompt using the inquirer.text method, execute it, and print the result. The example outputs 'Name: Michael' when the user enters 'Michael'. ```python >>> from InquirerPy import inquirer >>> result = inquirer.text(message="Enter your name:").execute() >>> print(f"Name: {result}") Name: Michael ``` -------------------------------- ### Use SPINNERS.dots with inquirer.select Source: https://inquirerpy.readthedocs.io/en/latest/pages/api.html Shows how to use the SPINNERS preset with the select prompt. The spinner_pattern parameter accepts a SPINNERS preset, such as SPINNERS.dots. This example is from the SPINNERS class documentation. ```python >>> from InquirerPy import inquirer >>> from InquirerPy.spinner import SPINNERS >>> inquirer.select(message="", choices=lambda _: [1, 2, 3], spinner_pattern=SPINNERS.dots) ``` -------------------------------- ### color_print() examples Source: https://inquirerpy.readthedocs.io/en/latest/pages/api.html Prints colored text using print_formatted_text() without interrupting the prompt. The formatted_text is a list of tuples (style_class, text) and the style dictionary maps class names to colors. The second call shows a simpler form without an explicit style. ```python >>> color_print(formatted_text=[("class:aa", "hello "), ("class:bb", "world")], style={"aa": "red", "bb": "blue"}) >>> color_print([("red", "yes"), ("", " "), ("blue", "no")]) ``` -------------------------------- ### patched_print() example Source: https://inquirerpy.readthedocs.io/en/latest/pages/api.html Prints values without interrupting the current prompt. This is a patched version of print() that can be used safely while a prompt is active. ```python >>> patched_print("Hello World") ``` -------------------------------- ### InquirerPy fuzzy prompt usage example Source: https://inquirerpy.readthedocs.io/en/latest/_modules/InquirerPy/prompts/fuzzy.html Example usage of the fuzzy prompt using the high-level inquirer interface. It shows creating the prompt with a message and choices, then executing it to get the result. ```python >>> from InquirerPy import inquirer >>> result = inquirer.fuzzy(message="Select one:", choices=[1, 2, 3]).execute() >>> print(result) 1 ``` -------------------------------- ### BaseSimplePrompt __init__ method Source: https://inquirerpy.readthedocs.io/en/latest/_modules/InquirerPy/base/simple.html Initializes the prompt with parameters for message, style, vi_mode, qmark, amark, instruction, validation, transformer, filter, default, wrap_lines, raise_keyboard_interrupt, mandatory, mandatory_message, and session_result. Sets up keybindings, editing mode, validator, and keyboard maps. ```python def __init__( self, message: InquirerPyMessage, style: Optional[InquirerPyStyle] = None, vi_mode: bool = False, qmark: str = "?", amark: str = "?", instruction: str = "", validate: Optional[InquirerPyValidate] = None, invalid_message: str = "Invalid input", transformer: Optional[Callable[[Any], Any]] = None, filter: Optional[Callable[[Any], Any]] = None, default: Any = "", wrap_lines: bool = True, raise_keyboard_interrupt: bool = True, mandatory: bool = True, mandatory_message: str = "Mandatory prompt", session_result: Optional[InquirerPySessionResult] = None, ) -> None: self._mandatory = mandatory self._mandatory_message = mandatory_message self._result = session_result or {} self._message = ( message if not isinstance(message, Callable) else cast(Callable, message)(self._result) ) self._instruction = instruction self._default = ( default if not isinstance(default, Callable) else default(self._result) ) self._style = Style.from_dict(style.dict if style else get_style().dict) self._qmark = qmark self._amark = amark self._status = {"answered": False, "result": None, "skipped": False} self._kb = KeyBindings() self._lexer = "class:input" self._transformer = transformer self._filter = filter self._wrap_lines = wrap_lines self._editing_mode = ( EditingMode.VI if vi_mode or bool(os.getenv("INQUIRERPY_VI_MODE", False)) else EditingMode.EMACS ) if isinstance(validate, Validator): self._validator = validate else: self._validator = Validator.from_callable( validate if validate else lambda _: True, invalid_message, move_cursor_to_end=True, ) self._raise_kbi = not os.getenv( "INQUIRERPY_NO_RAISE_KBI", not raise_keyboard_interrupt ) self._is_rasing_kbi = Condition(lambda: self._raise_kbi) self._kb_maps = { "answer": [{"key": Keys.Enter}], "interrupt": [ {"key": "c-c", "filter": self._is_rasing_kbi}, {"key": "c-d", "filter": ~self._is_rasing_kbi}, ], "skip": [{"key": "c-z"}, {"key": "c-c", "filter": ~self._is_rasing_kbi}], } self._kb_func_lookup = { "answer": [{"func": self._handle_enter}], "interrupt": [{"func": self._handle_interrupt}], "skip": [{"func": self._handle_skip}], } ``` -------------------------------- ### Alternate Syntax Example Source: https://inquirerpy.readthedocs.io/en/latest/pages/dynamic.html Example using the alternate inquirer syntax. ```APIDOC ```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() ``` ``` -------------------------------- ### calculate_height usage example Source: https://inquirerpy.readthedocs.io/en/latest/_modules/InquirerPy/utils.html Example usage of calculate_height with height='60%' and max_height='100%'. ```python >>> calculate_height(height="60%", max_height="100%") ``` -------------------------------- ### patched_print usage example Source: https://inquirerpy.readthedocs.io/en/latest/_modules/InquirerPy/utils.html Example usage of patched_print printing 'Hello World'. ```python >>> patched_print("Hello World") ``` -------------------------------- ### FilePathPrompt.__init__ Source: https://inquirerpy.readthedocs.io/en/latest/pages/prompts/filepath.html Creates a FilePathPrompt instance with auto-completion for system filepaths. It accepts various parameters to customize the prompt behavior, validation, and appearance. ```APIDOC ## FilePathPrompt.__init__ ### Description Creates a prompt that provides auto completion for system filepaths. A wrapper class around PromptSession. ### Method Constructor ### Signature FilePathPrompt(message, style=None, vi_mode=False, default='', qmark='?', amark='?', instruction='', long_instruction='', multicolumn_complete=False, validate=None, invalid_message='Invalid input', only_directories=False, only_files=False, transformer=None, filter=None, keybindings=None, wrap_lines=True, raise_keyboard_interrupt=True, mandatory=True, mandatory_message='Mandatory prompt', session_result=None, input=None, output=None) ### Parameters - **message** (Union[str, Callable[[InquirerPySessionResult], str]]) - Required - The question to ask the user. - **style** (Optional[InquirerPyStyle]) - Optional - An InquirerPyStyle instance. - **vi_mode** (bool) - Optional - Use vim keybinding for the prompt. - **default** (Union[Any, Callable[[InquirerPySessionResult], Any]]) - Optional - Set the default text value of the prompt. - **qmark** (str) - Optional - Question mark symbol displayed in front of the question before it is answered. - **amark** (str) - Optional - Answer mark symbol displayed in front of the question after it is answered. - **instruction** (str) - Optional - Short instruction to display next to the question. - **long_instruction** (str) - Optional - Long instructions to display at the bottom of the prompt. - **multicolumn_complete** (bool) - Optional - Change the auto-completion UI to a multi column display. - **validate** (Optional[Union[Callable[[Any], bool], Validator]]) - Optional - Add validation to user input. - **invalid_message** (str) - Optional - Error message to display when user input is invalid. - **transformer** (Optional[Callable[[str], Any]]) - Optional - A function which performs additional transformation on the value that gets printed to the terminal. - **filter** (Optional[Callable[[str], Any]]) - Optional - A function which performs additional transformation on the result. - **keybindings** (Optional[Dict[str, List[Dict[str, Union[str, FilterOrBool, List[str]]]]]]) - Optional - Customise the builtin keybindings. - **wrap_lines** (bool) - Optional - Soft wrap question lines when question exceeds the terminal width. - **only_directories** (bool) - Optional - Only complete directories. - **only_files** (bool) - Optional - Only complete files. - **raise_keyboard_interrupt** (bool) - Optional - Raise the KeyboardInterrupt exception when ctrl-c is pressed. - **mandatory** (bool) - Optional - Indicate if the prompt is mandatory. - **mandatory_message** (str) - Optional - Error message to show when user attempts to skip mandatory prompt. - **session_result** (Optional[Dict[Union[str, int], Optional[Union[str, bool, List[Any]]]]]) - Optional - Used internally for Classic Syntax (PyInquirer). - **input** (Optional[Input]) - Optional - Used internally and will be removed in future updates. - **output** (Optional[Output]) - Optional - Used internally and will be removed in future updates. ### Return Type None ### Example ```python >>> from InquirerPy import inquirer >>> result = inquirer.filepath(message="Enter a path:").execute() >>> print(result) /home/ubuntu/README.md ``` ``` -------------------------------- ### prompt_async(questions) Source: https://inquirerpy.readthedocs.io/en/latest/_sources/pages/prompt.md.txt Asynchronous entry point for the Classic Syntax. Accepts a list or single dictionary of questions and returns the result of the prompt session asynchronously. ```APIDOC ## prompt_async(questions) ### Description Asynchronous entry point for the Classic Syntax. Accepts a list or single dictionary of questions and returns the result of the prompt session asynchronously. ### Parameters #### questions - **type**: `Union[List[Dict[str, Any]], Dict[str, Any]]` - Required - A list of question dictionaries or a single question dictionary. ### Request Example ```python import asyncio from InquirerPy import inquirer, prompt_async async def main(): result = await prompt_async(questions=[{"type": "input", "message": "Enter your name:"}]) asyncio.run(main()) ``` ### Response Returns the result of the prompt session as a dictionary. ``` -------------------------------- ### Install InquirerPy with pip3 Source: https://inquirerpy.readthedocs.io/en/latest/_sources/index.md.txt Installs the InquirerPy package. Requires Python 3.7 or higher. ```bash pip3 install InquirerPy ``` -------------------------------- ### InquirerPyListPrompt __init__ method Source: https://inquirerpy.readthedocs.io/en/latest/_modules/InquirerPy/prompts/list.html Initializes the list prompt with all configurable options, sets up the content control, layout, and application. It handles optional border, cursor display, and dimension calculations. ```python def __init__( self, message: InquirerPyMessage, choices: InquirerPyListChoices, default: InquirerPyDefault = None, style: Optional[InquirerPyStyle] = None, vi_mode: bool = False, qmark: str = "?", amark: str = "?", pointer: str = INQUIRERPY_POINTER_SEQUENCE, instruction: str = "", long_instruction: str = "", transformer: Optional[Callable[[Any], Any]] = None, filter: Optional[Callable[[Any], Any]] = None, height: Optional[Union[int, str]] = None, max_height: Optional[Union[int, str]] = None, multiselect: bool = False, marker: str = INQUIRERPY_POINTER_SEQUENCE, marker_pl: str = " ", border: bool = False, validate: Optional[InquirerPyValidate] = None, invalid_message: str = "Invalid input", keybindings: Optional[InquirerPyKeybindings] = None, show_cursor: bool = True, cycle: bool = True, wrap_lines: bool = True, raise_keyboard_interrupt: bool = True, mandatory: bool = True, mandatory_message: str = "Mandatory prompt", session_result: Optional[InquirerPySessionResult] = None, ) -> None: if not hasattr(self, "_content_control"): self.content_control = InquirerPyListControl( choices=choices, default=default, pointer=pointer, marker=marker, session_result=session_result, multiselect=multiselect, marker_pl=marker_pl, ) super().__init__( message=message, style=style, border=border, vi_mode=vi_mode, qmark=qmark, amark=amark, instruction=instruction, long_instruction=long_instruction, transformer=transformer, filter=filter, validate=validate, invalid_message=invalid_message, multiselect=multiselect, keybindings=keybindings, cycle=cycle, wrap_lines=wrap_lines, raise_keyboard_interrupt=raise_keyboard_interrupt, mandatory=mandatory, mandatory_message=mandatory_message, session_result=session_result, ) self._show_cursor = show_cursor self._dimmension_height, self._dimmension_max_height = calculate_height( height, max_height, height_offset=self.height_offset ) main_content_window = Window( content=self.content_control, height=Dimension( max=self._dimmension_max_height, preferred=self._dimmension_height, ), dont_extend_height=True, ) if self._border: main_content_window = Frame(main_content_window) self._layout = FloatContainer( content=HSplit( [ MessageWindow( message=self._get_prompt_message_with_cursor if self._show_cursor else self._get_prompt_message, filter=True, wrap_lines=self._wrap_lines, show_cursor=self._show_cursor, ), ConditionalContainer(main_content_window, filter=~IsDone()), ConditionalContainer( Window(content=DummyControl()), filter=~IsDone() & self._is_displaying_long_instruction, ), InstructionWindow( message=self._long_instruction, filter=~IsDone() & self._is_displaying_long_instruction, wrap_lines=self._wrap_lines, ), ] ), floats=[ ValidationFloat( invalid_message=self._get_error_message, filter=self._is_invalid & ~IsDone(), wrap_lines=self._wrap_lines, left=0, bottom=self._validation_window_bottom_offset, ), ], ) self.application = Application( layout=Layout(self._layout), style=self._style, key_bindings=self._kb, after_render=self._after_render, ) ``` -------------------------------- ### color_print usage examples Source: https://inquirerpy.readthedocs.io/en/latest/_modules/InquirerPy/utils.html Two example usages of color_print: one with a style dictionary and one without. ```python >>> color_print(formatted_text=[("class:aa", "hello "), ("class:bb", "world")], style={"aa": "red", "bb": "blue"}) ``` ```python >>> color_print([("red", "yes"), ("", " "), ("blue", "no")]) ``` -------------------------------- ### Classic Syntax (PyInquirer) example using message, choices, and multiselect Source: https://inquirerpy.readthedocs.io/en/latest/_sources/pages/dynamic.md.txt Shows how to use the prompt() function with a list prompt, including Choice, Separator, and a transformer. The result is stored in the 'result' variable. ```python from InquirerPy import prompt from InquirerPy.base.control import Choice from InquirerPy.separator import Separator questions = [ { "type": "list", "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", }, ] result = prompt(questions=questions) ``` -------------------------------- ### Alternate Syntax rawlist example Source: https://inquirerpy.readthedocs.io/en/latest/_sources/pages/prompts/rawlist.md.txt Example of using rawlist with alternate syntax. The code is included from an external file and is not displayed on this page. ```python .. literalinclude :: ../../../examples/alternate/rawlist.py :language: python ``` -------------------------------- ### SecretPrompt usage example Source: https://inquirerpy.readthedocs.io/en/latest/pages/prompts/secret.html Example usage of the SecretPrompt via the inquirer.secret method. It prompts for a password and prints the result, which is masked as asterisks during input. ```python >>> from InquirerPy import inquirer >>> result = inquirer.secret(message="Password:").execute() >>> print(f"Password: {result}") Password: asdf123 ```