commandmenu¶
Overview¶
A readline <https://docs.python.org/readline> completer that implements an interactive menu for use in a text console. Whenever the user starts typing input that is part of a menu command, pressing <TAB> completes the command.
Classes¶
- class pymisclib.commandmenu.CommandItem(name: str, default: bool = False)¶
An item for a command menu.
- __init__(name: str, default: bool = False)¶
- class pymisclib.commandmenu.CommandMenu(vocabulary: dict[str, list[str]] = {'quit': []}, prompt: str = '> ', terminal_word: str = 'quit')¶
Interactive text console menu.
- __init__(vocabulary: dict[str, list[str]] = {'quit': []}, prompt: str = '> ', terminal_word: str = 'quit')¶
Initialize the instance.
- Parameters:
vocabulary (dict[str, list[str]]) – A dictionary of primary terms with a list of secondary terms specific to the primary term.
prompt (str) – The prompt displayed to tell the user that input is expected.
terminal_word (str) – The primary term that will terminate the menu.
- complete(text, state)¶
Command-line completion of the user text in the given state.
- input_generator() → str¶
Yield user input whenever an entry is confirmed.
Automatically quits if terminal_word is typed.
- Returns:
The line of user input.
- Return type:
str
Example¶
import readline
import pymisclib.commandmenu as cm
# Register our completer function
menu = cm.CommandMenu({
'list': ['files', 'directories'],
'print': ['byname', 'bysize'],
'stop': [],
}, ':> ', 'stop')
readline.set_completer(menu.complete)
# Use the tab key for completion
readline.parse_and_bind('tab: complete') # Works on Linux
readline.parse_and_bind('bind ^I rl_complete') # Works on macOS
readline.parse_and_bind('set editing-mode vi')
# Prompt the user for text
for line in menu.input_generator():
print(f'Input was: {line}')