API Documentation
A Python library of interactive CLI elements you have been looking for
Class KeyBindings
@dataclass
class KeyBindings(metaclass=_InstanceOnly)
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)
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. Forselect,promptandconfirmthis meansNone, while forselect_multipleit 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. Forselect,promptandconfirmthis meansNone, while forselect_multipleit 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. arich.live.Live. Defaults toConsole(stderr=True, highlight=False).keys(KeyBindings)- Keybindings used by the elements. Defaults toKeyBindings().
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
Function that prompts the user for written input
Arguments:
promptstr - The prompt that will be displayedtarget_typeUnion[Type[T], Type[str]], optional - Type to convert the answer to. Defaults to str.validatorCallable[[Any], bool], optional - Optional function to validate the input. Defaults to lambda input: True.securebool, optional - If True, input will be hidden. Defaults to False.raise_validation_failbool, optional - If True, invalid inputs will raiseValidationError, else the error will be reported onto the console. Defaults to True.raise_type_conversion_failbool, optional - If True, invalid inputs will raiseConversionError, else the error will be reported onto the console. Defaults to True.initial_valuestr, optional - If present, the value is placed in the prompt as the default value.completionCallable[[str], List[str]], optional - Returns completion options for the current input.instructionsstr, optional - Rich friendly text shown below the input. PassNoneto hide it. Defaults to '([bold]enter[/bold] to confirm)'.configConfig, optional - Configuration to use. Defaults toConfig().
Raises:
ValidationError- Raised if validation with provided validator failsConversionError- Raised if the value cannot be converted to provided typeKeyboardInterrupt- Raised when keyboard interrupt is encountered andconfig.raise_on_interruptis True
Returns:
Optional[T]- The input converted totarget_type(a string by default), orNoneif the prompt was aborted (Esc, or Ctrl+C whenconfig.raise_on_interruptis 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
A prompt that allows selecting one option from a list of options
Arguments:
optionsUnion[Sequence[T], Mapping[str, Sequence[T]]] - A sequence of options to select from. Ifpreprocessoris left as default (not passed), it needs to be a list of strings or objects with a__str__method. Otherwise, you can pass apreprocessorto create a string representation of arbitrary data-structures. Pass a dict of{section_name: options}to show options in sections.preprocessorCallable[[T], str] - A callable that can be used to preprocess the list of options prior to printing. For example, if you passed aPersonobject withnameattribute, preprocessor could belambda person: person.nameto just show the content ofnameattribute in the select dialog. Defaults tolambda val: valcursorstr, optional - Cursor that is going to appear in front of currently selected option. Defaults to '> '.cursor_stylestr, optional - Rich friendly style for the cursor. Defaults to 'pink1'.cursor_indexUnion[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_indexbool, optional - IfTrue,selectwill return the index of selected element in options. For sectioned options, it's(section_name, index_in_section). Defaults toFalse.strictbool, optional - IfTrueandoptionsis empty,ValueErroris raised; ifFalse,Noneis returned instead. Defaults to True.page_sizeOptional[int], optional - Number of options to show on a single page. IfNone, 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.titlestr, optional - Rich friendly text shown above the options. Defaults to ''.instructionsstr, optional - Rich friendly text shown below the options. PassNoneto hide it. Defaults to '([bold]enter[/bold] to confirm)'.filterablebool, optional - IfTrue, typing filters the options (case-insensitive substring of the displayed text) and backspace edits the filter. Keys bound inconfig.keyskeep their action. Defaults to False.configConfig, optional - Configuration to use. Defaults toConfig().
Raises:
ValueError- Thrown if nooptionsare provided and strict isTrue, or if an option or section name is blankKeyboardInterrupt- Raised when keyboard interrupt is encountered andconfig.raise_on_interruptis 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]
A prompt that allows selecting multiple options from a list of options
Arguments:
optionsUnion[Sequence[T], Mapping[str, Sequence[T]]] - A sequence of options to select from. Ifpreprocessoris left as default (not passed), it needs to be a list of strings or objects with a__str__method. Otherwise, you can pass apreprocessorto create a string representation of arbitrary data-structures. Pass a dict of{section_name: options}to show options in sections.preprocessorCallable[[T], str] - A callable that can be used to preprocess the list of options prior to printing. For example, if you passed aPersonobject withnameattribute, preprocessor could belambda person: person.nameto just show the content ofnameattribute in the select_multiple dialog. Defaults tolambda val: valtick_characterstr, optional - Character that will be used as a tick in a checkbox. Defaults to 'x'.tick_stylestr, optional - Rich friendly style for the tick character. Defaults to 'pink1'.cursor_stylestr, optional - Rich friendly style for the option when the cursor is currently on it. Defaults to 'pink1'.ticked_indicesOptional[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_indexUnion[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_countint, optional - Minimal count of options that need to be selected. Defaults to 0.maximal_countOptional[int], optional - Maximal count of options that need to be selected. Defaults to None.return_indicesbool, optional - IfTrue,select_multiplewill return the indices of ticked elements in options. For sectioned options, they are(section_name, index_in_section). Defaults toFalse.strictbool, optional - IfTrueandoptionsis empty,ValueErroris raised; ifFalse, an empty list is returned instead. Defaults to True.page_sizeOptional[int], optional - Number of options to show on a single page. IfNone, 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.titlestr, optional - Rich friendly text shown above the options. Defaults to ''.instructionsstr, optional - Rich friendly text shown below the options. PassNoneto hide it.filterablebool, optional - IfTrue, typing filters the options (case-insensitive substring of the displayed text) and backspace edits the filter. Keys bound inconfig.keyskeep their action, so space still ticks. Defaults to False.configConfig, optional - Configuration to use. Defaults toConfig().
Raises:
ValueError- Thrown if nooptionsare provided and strict isTrue, or if an option or section name is blankKeyboardInterrupt- Raised when keyboard interrupt is encountered andconfig.raise_on_interruptis 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]
A prompt that asks a question and offers two responses
Arguments:
questionstr - Question to be askedyes_textstr, optional - Text of the positive response. Defaults to 'Yes'.no_textstr, optional - Text of the negative response. Defaults to 'No'.has_to_match_casebool, optional - Check if typed response matches case. Defaults to False.enter_empty_confirmsbool, optional - No response is confirmation. Defaults to True.default_is_yesbool, optional - Default is Yes. Defaults to False.cursorstr, optional - What character(s) to use as a cursor. Defaults to '> '.cursor_stylestr, optional - Rich friendly style for the cursor. Defaults to 'pink1'.char_promptbool, optional - Print [Y/n] after the question. Defaults to True.instructionsstr, optional - Rich friendly text shown below the responses. PassNoneto hide it. Defaults to '([bold]enter[/bold] to confirm)'.configConfig, optional - Configuration to use. Defaults toConfig().
Raises:
ValueError- Thrown ifyes_textorno_textis blank, or ifchar_promptis on and they start with the same letterKeyboardInterrupt- Raised when keyboard interrupt is encountered andconfig.raise_on_interruptis True
Returns:
Optional[bool]
Class Spinner
class Spinner()
__init__
def __init__(spinner_characters: Sequence[str] = DOTS,
*,
text: str = 'Loading...',
refresh_per_second: float = 10,
transient: bool = True,
console: Optional[Console] = None)
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_charactersSequence[str] - Strings that will be displayed in sequence by a spinner. Defaults toDOTS.textstr - Static text that will be shown after the spinner. Defaults toLoading...refresh_per_secondfloat, optional - Number of refreshes the spinner will do a second, this will affect the fluidity of the "animation". Defaults to 10.transientbool, optional - If the spinner will disappear after it's done, otherwise not. Defaults to True.consolerich.console.Console, optional - Console to render to, e.g. the one passed to elements viaConfig. Defaults to Rich's global console.
Raises:
ValueError- Raised when nospinner_charactersare provided in
start
def start() -> None
Starts the spinner
stop
def stop() -> None
Stops the spinner