InquirerPy Documentation

repository·master·Indexed 19 days ago

https://github.com/kazhala/inquirerpy

A Python port of Inquirer.js providing a collection of interactive command-line user interfaces. InquirerPy is a re-implementation of PyInquirer designed to fix known issues and offer more customization options. It supports multiple prompt types including InputPrompt, SecretPrompt, FilepathPrompt, ConfirmPrompt, ListPrompt, RawListPrompt, ExpandPrompt, and FuzzyPrompt, and offers both a Classic Syntax for PyInquirer compatibility and a fluent Alternate Syntax.

Tokens
22K
Snippets
78
Records
117
Agent score
66%

What's inside InquirerPy

  1. Use Containers for UI elements

    master

    InquirerPy provides several container types to manage UI state and display information:

    • spinner: For displaying loading indicators.
    • message: For displaying text messages.
    • validation: For displaying validation error/success states.
    • instruction: For displaying guidance to the user.
  2. How dynamic values work in InquirerPy

    master

    InquirerPy allows you to pass callables (functions or lambdas) to certain prompt parameters to generate values dynamically. These are categorized by when they are evaluated:

    1. Before Rendered: Evaluated before the prompt is displayed. These allow you to customize the prompt (like message, default, or choices) based on the results of previous questions. When using the prompt() (Classic Syntax) method, the callable receives an InquirerPySessionResult object as its argument.

    2. After Answered: Evaluated after the user provides an answer. These allow you to transform the data (filter) or change how the result is visually displayed in the terminal (transformer).

  3. Use prompt_toolkit Validators for custom error handling

    master

    For more advanced validation, you can provide an instance of prompt_toolkit.validation.Validator. Unlike using a callable with invalid_message, a prompt_toolkit validator handles its own error messaging by raising a ValidationError.

    Note: For prompts that do not return a string type (like checkbox), you must access the input via document.text within the validate method.

    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,
                )
  4. Control KeyboardInterrupt behavior

    master

    You can control how KeyboardInterrupt (typically triggered by ctrl-c) is handled in InquirerPy using two primary methods: keybindings or raise_keyboard_interrupt.

    Method 1: Using raise_keyboard_interrupt

    If you want behavior similar to a Python REPL (where ctrl-c skips the prompt and ctrl-d terminates the program), set raise_keyboard_interrupt=False.

    Note: When using this method, it is recommended to inform the user how to terminate the program via mandatory_message or long_instruction.

    Method 2: Using keybindings

    You can explicitly map specific keys to skip or interrupt actions.

    Warning: Do not use raise_keyboard_interrupt and keybindings together, as both attempt to modify the same underlying key mappings and may cause conflicts.

    # Example using raise_keyboard_interrupt for REPL-like behavior
    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()
    
    # Example using explicit keybindings
    from InquirerPy import inquirer
    
    result = inquirer.select(
        message="Select one:",
        choices=["Fruit", "Meat", "Drinks", "Vegetable"],
        keybindings={"skip": [{"key": "c-c"}], "interrupt": [{"key": "c-d"}]},
    ).execute()
  5. Use the ExpandPrompt for compact selection

    master

    The expand prompt is a compact UI element that allows users to select from a list of choices using single-character shortcuts. Users can press a specific key assigned to a choice to select it immediately, or use an expansion key (defaulting to h) to view the full list of available choices and their associated keys.

    from InquirerPy import inquirer
    
    result = inquirer.expand(
        message="Select one:",
        choices=[
            {"key": "a", "value": "1", "name": "Apple"},
            {"key": "b", "value": "2", "name": "Banana"},
        ],
    ).execute()
  6. Use Separator to group choices visually

    master

    You can use InquirerPy.separator.Separator to visually group choices within prompts that involve a list of options. This is useful for creating logical sections in your user interface.

    Supported prompt types that accept Separator in their choices list include:

    • ListPrompt
    • RawlistPrompt
    • ExpandPrompt
    • CheckboxPrompt
    from InquirerPy import inquirer
    from InquirerPy.base.control import Choice
    from InquirerPy.separator import Separator
    
    # Example using the inquirer API
    result = 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,
    ).execute()
  7. Handle environment variables in FilePathPrompt

    master

    The FilePathPrompt natively handles the tilde ~ character to trigger completion for the home directory. However, it does not automatically handle environment variables like $HOME.

    To support environment variable completion, you must use InquirerPy.prompts.input.InputPrompt with a custom completer class. You can implement this by creating a custom completion class based on prompt_toolkit documentation and passing it to the completer parameter.

  8. Use the FuzzyPrompt for fuzzy searching choices

    master

    The fuzzy prompt allows users to select from a list of choices while providing a fuzzy search interface similar to fzf. It uses the fzy fuzzy match algorithm by default.

    Important Constraints:

    • This prompt does not accept choices containing Separator instances.
    • When vi_mode is enabled, j/k navigation is disabled because the input buffer enters vim input mode.
    • The space key for toggling choices is disabled to allow users to type spaces in the search buffer.
    from InquirerPy import inquirer
    
    result = inquirer.fuzzy(
        message="Select actions:",
        choices=["hello", "weather", "what", "whoa", "hey", "yo"],
    ).execute()
  9. Use RawlistPrompt for indexed choice selection

    master

    The RawlistPrompt displays a list of choices where users can use index numbers (1-9) as key jump shortcuts to quickly navigate to a specific choice.

    Constraint: Because shortcuts are mapped to keys 1-9, the total number of choices in a RawlistPrompt cannot exceed 10.

    from InquirerPy import inquirer
    
    answer = inquirer.rawlist(
        message="Select an option",
        choices=["Option 1", "Option 2", "Option 3"],
    ).execute()
  10. Configure the default value for ConfirmPrompt

    master

    The default parameter (boolean) controls two behaviors:

    1. Display: It determines which letter is capitalized in the prompt instruction. If default is True, the confirm_letter is capitalized (e.g., (Y/n)). If default is False, the reject_letter is capitalized (e.g., (y/N)).
    2. Input: It determines the value returned if the user presses Enter without typing a specific letter.
  11. Run InquirerPy examples

    master

    To explore the library's capabilities, you can run the provided examples from the repository.

    1. Clone the repository:
      git clone https://github.com/kazhala/InquirerPy.git
      cd InquirerPy
    2. Create and activate a virtual environment:
      python3 -m venv venv
      source venv/bin/activate
    3. Install example dependencies:
      pip3 install -r examples/requirements.txt
    4. Run an example (e.g., rawlist in the classic style):
      python3 -m examples.classic.rawlist

    Note: demo_alternate.py and demo_classic.py require the boto3 package and configured AWS credentials.

    git clone https://github.com/kazhala/InquirerPy.git
    cd InquirerPy
    python3 -m venv venv
    source venv/bin/activate
    pip3 install -r examples/requirements.txt
    python3 -m examples.classic.rawlist
  12. Pre-select choices in a CheckboxPrompt

    master

    To have certain items pre-selected (ticked) when the prompt appears, you must use InquirerPy.base.Choice objects instead of raw strings. Set the enabled parameter to True for the items you want pre-selected.

    Note: The default parameter in CheckboxPrompt controls which item is highlighted (focused) by default, not which ones are selected.

    from InquirerPy.base import Choice
    from InquirerPy import inquirer
    
    choices = [
        Choice("selected", enabled=True),
        Choice("notselected", enabled=False),
        "notselected2"
    ]
    
    selected = inquirer.checkbox(
        message="Choose options",
        choices=choices
    )