Skip to content

API Documentation

A Python library of interactive CLI elements you have been looking for

Class KeyBindings

@dataclass
class KeyBindings(metaclass=_InstanceOnly)

[view_source]

Keybindings used by the elements. Pass an instance via Config(keys=KeyBindings(...)).

Attributes:

escape(List[Union[Tuple[int, ...], str]]): Keys that escape the current context. select(List[Union[Tuple[int, ...], str]]): Keys that trigger list element selection. confirm(List[Union[Tuple[int, ...], str]]): Keys that trigger list confirmation. backspace(List[Union[Tuple[int, ...], str]]): Keys that trigger deletion of the previous character. delete(List[Union[Tuple[int, ...], str]]): Keys that trigger deletion of the next character. down(List[Union[Tuple[int, ...], str]]): Keys that select the element below. up(List[Union[Tuple[int, ...], str]]): Keys that select the element above. left(List[Union[Tuple[int, ...], str]]): Keys that select the element to the left. right(List[Union[Tuple[int, ...], str]]): Keys that select the element to the right. tab(List[Union[Tuple[int, ...], str]]): Keys that complete the current selection in confirm. home(List[Union[Tuple[int, ...], str]]): Keys that move to the beginning of the context. end(List[Union[Tuple[int, ...], str]]): Keys that move to the end of the context. interrupt(List[Union[Tuple[int, ...], str]]): Keys that interrupt the current context. select_all(List[Union[Tuple[int, ...], str]]): Keys that tick/untick all options in select_multiple.

Class Config

@dataclass
class Config(metaclass=_InstanceOnly)

[view_source]

Configuration of the elements. Create an instance and pass it via the config= argument.

Attributes:

  • raise_on_interrupt(bool) - If True, functions will raise KeyboardInterrupt whenever Ctrl+C is pressed when waiting for input, otherwise, they will return some sane alternative to their usual return. For select, prompt and confirm this means None, while for select_multiple it means an empty list - []. Defaults to True.
  • raise_on_escape(bool) - If True, functions will raise Abort whenever the escape key is encountered when waiting for input, otherwise, they will return some sane alternative to their usual return. For select, prompt and confirm this means None, while for select_multiple it means an empty list - []. Defaults to False.
  • transient(bool) - If False, elements will remain displayed after their context has ended. Defaults to True.
  • console(rich.console.Console) - Console the elements are rendered to. Pass your own to share it with other Rich output, e.g. a rich.live.Live. Defaults to Console(stderr=True, highlight=False).
  • keys(KeyBindings) - Keybindings used by the elements. Defaults to KeyBindings().

prompt

def prompt(prompt: str,
           *,
           target_type: Type[Any] = str,
           validator: Callable[[Any], bool] = lambda input: True,
           secure: bool = False,
           raise_validation_fail: bool = True,
           raise_type_conversion_fail: bool = True,
           initial_value: Optional[str] = None,
           completion: Optional[Callable[[str], List[str]]] = None,
           instructions: Optional[str] = _CONFIRM_INSTRUCTIONS,
           config: Optional[Config] = None) -> Any

[view_source]

Function that prompts the user for written input

Arguments:

  • prompt str - The prompt that will be displayed
  • target_type Union[Type[T], Type[str]], optional - Type to convert the answer to. Defaults to str.
  • validator Callable[[Any], bool], optional - Optional function to validate the input. Defaults to lambda input: True.
  • secure bool, optional - If True, input will be hidden. Defaults to False.
  • raise_validation_fail bool, optional - If True, invalid inputs will raise ValidationError, else the error will be reported onto the console. Defaults to True.
  • raise_type_conversion_fail bool, optional - If True, invalid inputs will raise ConversionError, else the error will be reported onto the console. Defaults to True.
  • initial_value str, optional - If present, the value is placed in the prompt as the default value.
  • completion Callable[[str], List[str]], optional - Returns completion options for the current input.
  • instructions str, optional - Rich friendly text shown below the input. Pass None to hide it. Defaults to '([bold]enter[/bold] to confirm)'.
  • config Config, optional - Configuration to use. Defaults to Config().

Raises:

  • ValidationError - Raised if validation with provided validator fails
  • ConversionError - Raised if the value cannot be converted to provided type
  • KeyboardInterrupt - Raised when keyboard interrupt is encountered and config.raise_on_interrupt is True

Returns:

  • Optional[T] - The input converted to target_type (a string by default), or None if the prompt was aborted (Esc, or Ctrl+C when config.raise_on_interrupt is False)

select

def select(options: Options,
           *,
           preprocessor: Callable[[T], str] = lambda val: str(val),
           cursor: str = '>',
           cursor_style: str = 'pink1',
           cursor_index: Optional[Index] = None,
           return_index: bool = False,
           strict: bool = True,
           page_size: Optional[int] = None,
           title: str = '',
           instructions: Optional[str] = _CONFIRM_INSTRUCTIONS,
           filterable: bool = False,
           config: Optional[Config] = None) -> Any

[view_source]

A prompt that allows selecting one option from a list of options

Arguments:

  • options Union[Sequence[T], Mapping[str, Sequence[T]]] - A sequence of options to select from. If preprocessor is left as default (not passed), it needs to be a list of strings or objects with a __str__ method. Otherwise, you can pass a preprocessor to create a string representation of arbitrary data-structures. Pass a dict of {section_name: options} to show options in sections.
  • preprocessor Callable[[T], str] - A callable that can be used to preprocess the list of options prior to printing. For example, if you passed a Person object with name attribute, preprocessor could be lambda person: person.name to just show the content of name attribute in the select dialog. Defaults to lambda val: val
  • cursor str, optional - Cursor that is going to appear in front of currently selected option. Defaults to '> '.
  • cursor_style str, optional - Rich friendly style for the cursor. Defaults to 'pink1'.
  • cursor_index Union[int, Tuple[str, int]], optional - Option can be preselected based on its list index. For sectioned options, it must be (section_name, index_in_section). Defaults to the first option.
  • return_index bool, optional - If True, select will return the index of selected element in options. For sectioned options, it's (section_name, index_in_section). Defaults to False.
  • strict bool, optional - If True and options is empty, ValueError is raised; if False, None is returned instead. Defaults to True.
  • page_size Optional[int], optional - Number of options to show on a single page. If None, the page size is derived from the terminal height, and pagination is only used when the options don't fit. If set, options are always paginated with this many per page. Defaults to None.
  • title str, optional - Rich friendly text shown above the options. Defaults to ''.
  • instructions str, optional - Rich friendly text shown below the options. Pass None to hide it. Defaults to '([bold]enter[/bold] to confirm)'.
  • filterable bool, optional - If True, typing filters the options (case-insensitive substring of the displayed text) and backspace edits the filter. Keys bound in config.keys keep their action. Defaults to False.
  • config Config, optional - Configuration to use. Defaults to Config().

Raises:

  • ValueError - Thrown if no options are provided and strict is True, or if an option or section name is blank
  • KeyboardInterrupt - Raised when keyboard interrupt is encountered and config.raise_on_interrupt is True

Returns:

Union[int, Tuple[str, int], str, None]: Selected value or the index of a selected option or None

select_multiple

def select_multiple(
        options: Options,
        *,
        preprocessor: Callable[[T], str] = lambda val: str(val),
        tick_character: str = '✓',
        tick_style: str = 'pink1',
        cursor_style: str = 'pink1',
        ticked_indices: Optional[Sequence[Index]] = None,
        cursor_index: Optional[Index] = None,
        minimal_count: int = 0,
        maximal_count: Optional[int] = None,
        return_indices: bool = False,
        strict: bool = True,
        page_size: Optional[int] = None,
        title: str = '',
        instructions: Optional[str] = _SELECT_MULTIPLE_INSTRUCTIONS,
        filterable: bool = False,
        config: Optional[Config] = None) -> List[Any]

[view_source]

A prompt that allows selecting multiple options from a list of options

Arguments:

  • options Union[Sequence[T], Mapping[str, Sequence[T]]] - A sequence of options to select from. If preprocessor is left as default (not passed), it needs to be a list of strings or objects with a __str__ method. Otherwise, you can pass a preprocessor to create a string representation of arbitrary data-structures. Pass a dict of {section_name: options} to show options in sections.
  • preprocessor Callable[[T], str] - A callable that can be used to preprocess the list of options prior to printing. For example, if you passed a Person object with name attribute, preprocessor could be lambda person: person.name to just show the content of name attribute in the select_multiple dialog. Defaults to lambda val: val
  • tick_character str, optional - Character that will be used as a tick in a checkbox. Defaults to 'x'.
  • tick_style str, optional - Rich friendly style for the tick character. Defaults to 'pink1'.
  • cursor_style str, optional - Rich friendly style for the option when the cursor is currently on it. Defaults to 'pink1'.
  • ticked_indices Optional[List[Union[int, Tuple[str, int]]]], optional - Indices of options that are pre-ticked when the prompt appears. For sectioned options, they must be (section_name, index_in_section). Defaults to None.
  • cursor_index Union[int, Tuple[str, int]], optional - Index of the option cursor starts at. For sectioned options, it must be (section_name, index_in_section). Defaults to the first option.
  • minimal_count int, optional - Minimal count of options that need to be selected. Defaults to 0.
  • maximal_count Optional[int], optional - Maximal count of options that need to be selected. Defaults to None.
  • return_indices bool, optional - If True, select_multiple will return the indices of ticked elements in options. For sectioned options, they are (section_name, index_in_section). Defaults to False.
  • strict bool, optional - If True and options is empty, ValueError is raised; if False, an empty list is returned instead. Defaults to True.
  • page_size Optional[int], optional - Number of options to show on a single page. If None, the page size is derived from the terminal height, and pagination is only used when the options don't fit. If set, options are always paginated with this many per page. Defaults to None.
  • title str, optional - Rich friendly text shown above the options. Defaults to ''.
  • instructions str, optional - Rich friendly text shown below the options. Pass None to hide it.
  • filterable bool, optional - If True, typing filters the options (case-insensitive substring of the displayed text) and backspace edits the filter. Keys bound in config.keys keep their action, so space still ticks. Defaults to False.
  • config Config, optional - Configuration to use. Defaults to Config().

Raises:

  • ValueError - Thrown if no options are provided and strict is True, or if an option or section name is blank
  • KeyboardInterrupt - Raised when keyboard interrupt is encountered and config.raise_on_interrupt is True

Returns:

Union[List[str], List[int], List[Tuple[str, int]]]: A list of selected values or indices of selected options

confirm

def confirm(question: str,
            *,
            yes_text: str = 'Yes',
            no_text: str = 'No',
            has_to_match_case: bool = False,
            enter_empty_confirms: bool = True,
            default_is_yes: bool = False,
            cursor: str = '>',
            cursor_style: str = 'pink1',
            char_prompt: bool = True,
            instructions: Optional[str] = _CONFIRM_INSTRUCTIONS,
            config: Optional[Config] = None) -> Optional[bool]

[view_source]

A prompt that asks a question and offers two responses

Arguments:

  • question str - Question to be asked
  • yes_text str, optional - Text of the positive response. Defaults to 'Yes'.
  • no_text str, optional - Text of the negative response. Defaults to 'No'.
  • has_to_match_case bool, optional - Check if typed response matches case. Defaults to False.
  • enter_empty_confirms bool, optional - No response is confirmation. Defaults to True.
  • default_is_yes bool, optional - Default is Yes. Defaults to False.
  • cursor str, optional - What character(s) to use as a cursor. Defaults to '> '.
  • cursor_style str, optional - Rich friendly style for the cursor. Defaults to 'pink1'.
  • char_prompt bool, optional - Print [Y/n] after the question. Defaults to True.
  • instructions str, optional - Rich friendly text shown below the responses. Pass None to hide it. Defaults to '([bold]enter[/bold] to confirm)'.
  • config Config, optional - Configuration to use. Defaults to Config().

Raises:

  • ValueError - Thrown if yes_text or no_text is blank, or if char_prompt is on and they start with the same letter
  • KeyboardInterrupt - Raised when keyboard interrupt is encountered and config.raise_on_interrupt is True

Returns:

Optional[bool]

Class Spinner

class Spinner()

[view_source]

__init__

def __init__(spinner_characters: Sequence[str] = DOTS,
             *,
             text: str = 'Loading...',
             refresh_per_second: float = 10,
             transient: bool = True,
             console: Optional[Console] = None)

[view_source]

Creates a spinner which can be used to provide some user feedback during long processing

Can be used as a context manager, which also stops the spinner if the body raises: with Spinner(DOTS, text='Working...'): do_work()

Arguments:

  • spinner_characters Sequence[str] - Strings that will be displayed in sequence by a spinner. Defaults to DOTS.
  • text str - Static text that will be shown after the spinner. Defaults to Loading...
  • refresh_per_second float, optional - Number of refreshes the spinner will do a second, this will affect the fluidity of the "animation". Defaults to 10.
  • transient bool, optional - If the spinner will disappear after it's done, otherwise not. Defaults to True.
  • console rich.console.Console, optional - Console to render to, e.g. the one passed to elements via Config. Defaults to Rich's global console.

Raises:

  • ValueError - Raised when no spinner_characters are provided in

start

def start() -> None

[view_source]

Starts the spinner

stop

def stop() -> None

[view_source]

Stops the spinner