cmd2.utils
Settings
- class cmd2.utils.Settable(name: str, val_type: Type[Any] | Callable[[Any], Any], description: str, settable_object: object, *, settable_attrib_name: str | None = None, onchange_cb: Callable[[str, _T, _T], Any] | None = None, choices: Iterable[Any] | None = None, choices_provider: ChoicesProviderFuncBase | ChoicesProviderFuncWithTokens | None = None, completer: CompleterFuncBase | CompleterFuncWithTokens | None = None)
Used to configure an attribute to be settable via the set command in the CLI
- __init__(name: str, val_type: Type[Any] | Callable[[Any], Any], description: str, settable_object: object, *, settable_attrib_name: str | None = None, onchange_cb: Callable[[str, _T, _T], Any] | None = None, choices: Iterable[Any] | None = None, choices_provider: ChoicesProviderFuncBase | ChoicesProviderFuncWithTokens | None = None, completer: CompleterFuncBase | CompleterFuncWithTokens | None = None) None
Settable Initializer
- Parameters:
name – name of the instance attribute being made settable
val_type – callable used to cast the string value from the command line into its proper type and even validate its value. Setting this to bool provides tab completion for true/false and validation using to_bool(). The val_type function should raise an exception if it fails. This exception will be caught and printed by Cmd.do_set().
description – string describing this setting
settable_object – object to which the instance attribute belongs (e.g. self)
settable_attrib_name – name which displays to the user in the output of the set command. Defaults to name if not specified.
onchange_cb –
optional function or method to call when the value of this settable is altered by the set command. (e.g. onchange_cb=self.debug_changed)
- Cmd.do_set() passes the following 3 arguments to onchange_cb:
param_name: str - name of the changed parameter old_value: Any - the value before being changed new_value: Any - the value after being changed
The following optional settings provide tab completion for a parameter’s values. They correspond to the same settings in argparse-based tab completion. A maximum of one of these should be provided.
- Parameters:
choices – iterable of accepted values
choices_provider – function that provides choices for this argument
completer – tab completion function that provides choices for this argument
- get_value() Any
Get the value of the settable attribute :return:
- set_value(value: Any) Any
Set the settable attribute on the specified destination object :param value: New value to set :return: New value that the attribute was set to
Quote Handling
- cmd2.utils.is_quoted(arg: str) bool
Checks if a string is quoted
- Parameters:
arg – the string being checked for quotes
- Returns:
True if a string is quoted
- cmd2.utils.quote_string(arg: str) str
Quote a string
- cmd2.utils.quote_string_if_needed(arg: str) str
Quote a string if it contains spaces and isn’t already quoted
- cmd2.utils.strip_quotes(arg: str) str
Strip outer quotes from a string.
Applies to both single and double quotes.
- Parameters:
arg – string to strip outer quotes from
- Returns:
same string with potentially outer quotes stripped
- cmd2.utils.quote_specific_tokens(tokens: List[str], tokens_to_quote: List[str]) None
Quote specific tokens in a list
- Parameters:
tokens – token list being edited
tokens_to_quote – the tokens, which if present in tokens, to quote
- cmd2.utils.unquote_specific_tokens(tokens: List[str], tokens_to_unquote: List[str]) None
Unquote specific tokens in a list
- Parameters:
tokens – token list being edited
tokens_to_unquote – the tokens, which if present in tokens, to unquote
IO Handling
- class cmd2.utils.StdSim(inner_stream: TextIO | StdSim, *, echo: bool = False, encoding: str = 'utf-8', errors: str = 'replace')
Class to simulate behavior of sys.stdout or sys.stderr. Stores contents in internal buffer and optionally echos to the inner stream it is simulating.
- write(s: str) None
Add str to internal bytes buffer and if echo is True, echo contents to inner stream
- Parameters:
s – String to write to the stream
- getvalue() str
Get the internal contents as a str
- getbytes() bytes
Get the internal contents as bytes
- read(size: int | None = -1) str
Read from the internal contents as a str and then clear them out
- Parameters:
size – Number of bytes to read from the stream
- readbytes() bytes
Read from the internal contents as bytes and then clear them out
- clear() None
Clear the internal contents
- isatty() bool
StdSim only considered an interactive stream if echo is True and inner_stream is a tty.
- property line_buffering: bool
Handle when the inner stream doesn’t have a line_buffering attribute which is the case when running unit tests because pytest sets stdout to a pytest EncodedFile object.
- class cmd2.utils.ByteBuf(std_sim_instance: StdSim)
Used by StdSim to write binary data and stores the actual bytes written
- write(b: bytes) None
Add bytes to internal bytes buffer and if echo is True, echo contents to inner stream.
- class cmd2.utils.ProcReader(proc: Popen, stdout: StdSim | TextIO, stderr: StdSim | TextIO)
Used to capture stdout and stderr from a Popen process if any of those were set to subprocess.PIPE. If neither are pipes, then the process will run normally and no output will be captured.
- send_sigint() None
Send a SIGINT to the process similar to if <Ctrl>+C were pressed
- terminate() None
Terminate the process
- wait() None
Wait for the process to finish
Tab Completion
- class cmd2.utils.CompletionMode(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
Enum for what type of tab completion to perform in cmd2.Cmd.read_input()
- NONE
Tab completion will be disabled during read_input() call. Use of custom up-arrow history supported.
- COMMANDS
read_input() will tab complete cmd2 commands and their arguments. cmd2’s command line history will be used for up arrow if history is not provided. Otherwise use of custom up-arrow history supported.
- CUSTOM
read_input() will tab complete based on one of its following parameters (choices, choices_provider, completer, parser). Use of custom up-arrow history supported
- class cmd2.utils.CustomCompletionSettings(parser: ArgumentParser, *, preserve_quotes: bool = False)
Used by cmd2.Cmd.complete() to tab complete strings other than command arguments
- __init__(parser: ArgumentParser, *, preserve_quotes: bool = False) None
Initializer
- Parameters:
parser – arg parser defining format of string being tab completed
preserve_quotes – if True, then quoted tokens will keep their quotes when processed by ArgparseCompleter. This is helpful in cases when you’re tab completing flag-like tokens (e.g. -o, –option) and you don’t want them to be treated as argparse flags when quoted. Set this to True if you plan on passing the string to argparse with the tokens still quoted.
Text Alignment
- class cmd2.utils.TextAlignment(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
Horizontal text alignment
- LEFT = 1
- CENTER = 2
- RIGHT = 3
- cmd2.utils.align_text(text: str, alignment: TextAlignment, *, fill_char: str = ' ', width: int | None = None, tab_width: int = 4, truncate: bool = False) str
Align text for display within a given width. Supports characters with display widths greater than 1. ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned independently.
There are convenience wrappers around this function: align_left(), align_center(), and align_right()
- Parameters:
text – text to align (can contain multiple lines)
alignment – how to align the text
fill_char – character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
width – display width of the aligned text. Defaults to width of the terminal.
tab_width – any tabs in the text will be replaced with this many spaces. if fill_char is a tab, then it will be converted to one space.
truncate – if True, then each line will be shortened to fit within the display width. The truncated portions are replaced by a ‘…’ character. Defaults to False.
- Returns:
aligned text
- Raises:
TypeError if fill_char is more than one character (not including ANSI style sequences)
- Raises:
ValueError if text or fill_char contains an unprintable character
- Raises:
ValueError if width is less than 1
- cmd2.utils.align_left(text: str, *, fill_char: str = ' ', width: int | None = None, tab_width: int = 4, truncate: bool = False) str
Left align text for display within a given width. Supports characters with display widths greater than 1. ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned independently.
- Parameters:
text – text to left align (can contain multiple lines)
fill_char – character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
width – display width of the aligned text. Defaults to width of the terminal.
tab_width – any tabs in the text will be replaced with this many spaces. if fill_char is a tab, then it will be converted to one space.
truncate – if True, then text will be shortened to fit within the display width. The truncated portion is replaced by a ‘…’ character. Defaults to False.
- Returns:
left-aligned text
- Raises:
TypeError if fill_char is more than one character (not including ANSI style sequences)
- Raises:
ValueError if text or fill_char contains an unprintable character
- Raises:
ValueError if width is less than 1
- cmd2.utils.align_right(text: str, *, fill_char: str = ' ', width: int | None = None, tab_width: int = 4, truncate: bool = False) str
Right align text for display within a given width. Supports characters with display widths greater than 1. ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned independently.
- Parameters:
text – text to right align (can contain multiple lines)
fill_char – character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
width – display width of the aligned text. Defaults to width of the terminal.
tab_width – any tabs in the text will be replaced with this many spaces. if fill_char is a tab, then it will be converted to one space.
truncate – if True, then text will be shortened to fit within the display width. The truncated portion is replaced by a ‘…’ character. Defaults to False.
- Returns:
right-aligned text
- Raises:
TypeError if fill_char is more than one character (not including ANSI style sequences)
- Raises:
ValueError if text or fill_char contains an unprintable character
- Raises:
ValueError if width is less than 1
- cmd2.utils.align_center(text: str, *, fill_char: str = ' ', width: int | None = None, tab_width: int = 4, truncate: bool = False) str
Center text for display within a given width. Supports characters with display widths greater than 1. ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned independently.
- Parameters:
text – text to center (can contain multiple lines)
fill_char – character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
width – display width of the aligned text. Defaults to width of the terminal.
tab_width – any tabs in the text will be replaced with this many spaces. if fill_char is a tab, then it will be converted to one space.
truncate – if True, then text will be shortened to fit within the display width. The truncated portion is replaced by a ‘…’ character. Defaults to False.
- Returns:
centered text
- Raises:
TypeError if fill_char is more than one character (not including ANSI style sequences)
- Raises:
ValueError if text or fill_char contains an unprintable character
- Raises:
ValueError if width is less than 1
- cmd2.utils.truncate_line(line: str, max_width: int, *, tab_width: int = 4) str
Truncate a single line to fit within a given display width. Any portion of the string that is truncated is replaced by a ‘…’ character. Supports characters with display widths greater than 1. ANSI style sequences do not count toward the display width.
If there are ANSI style sequences in the string after where truncation occurs, this function will append them to the returned string.
This is done to prevent issues caused in cases like: truncate_line(Fg.BLUE + hello + Fg.RESET, 3) In this case, “hello” would be truncated before Fg.RESET resets the color from blue. Appending the remaining style sequences makes sure the style is in the same state had the entire string been printed. align_text() relies on this behavior when preserving style over multiple lines.
- Parameters:
line – text to truncate
max_width – the maximum display width the resulting string is allowed to have
tab_width – any tabs in the text will be replaced with this many spaces
- Returns:
line that has a display width less than or equal to width
- Raises:
ValueError if text contains an unprintable character like a newline
- Raises:
ValueError if max_width is less than 1
Miscellaneous
- cmd2.utils.to_bool(val: Any) bool
Converts anything to a boolean based on its value.
Strings like “True”, “true”, “False”, and “false” return True, True, False, and False respectively. All other values are converted using bool()
- Parameters:
val – value being converted
- Returns:
boolean value expressed in the passed in value
- Raises:
ValueError if the string does not contain a value corresponding to a boolean value
- cmd2.utils.categorize(func: Callable[[...], Any] | Iterable[Callable[[...], Any]], category: str) None
Categorize a function.
The help command output will group the passed function under the specified category heading
- Parameters:
func – function or list of functions to categorize
category – category to put it in
- Example:
>>> import cmd2 >>> class MyApp(cmd2.Cmd): >>> def do_echo(self, arglist): >>> self.poutput(' '.join(arglist) >>> >>> cmd2.utils.categorize(do_echo, "Text Processing")
For an alternative approach to categorizing commands using a decorator, see
with_category()
- cmd2.utils.remove_duplicates(list_to_prune: List[_T]) List[_T]
Removes duplicates from a list while preserving order of the items.
- Parameters:
list_to_prune – the list being pruned of duplicates
- Returns:
The pruned list
- cmd2.utils.alphabetical_sort(list_to_sort: Iterable[str]) List[str]
Sorts a list of strings alphabetically.
For example: [‘a1’, ‘A11’, ‘A2’, ‘a22’, ‘a3’]
To sort a list in place, don’t call this method, which makes a copy. Instead, do this:
my_list.sort(key=norm_fold)
- Parameters:
list_to_sort – the list being sorted
- Returns:
the sorted list
- cmd2.utils.natural_sort(list_to_sort: Iterable[str]) List[str]
Sorts a list of strings case insensitively as well as numerically.
For example: [‘a1’, ‘A2’, ‘a3’, ‘A11’, ‘a22’]
To sort a list in place, don’t call this method, which makes a copy. Instead, do this:
my_list.sort(key=natural_keys)
- Parameters:
list_to_sort – the list being sorted
- Returns:
the list sorted naturally
- cmd2.utils.suggest_similar(requested_command: str, options: Iterable[str], similarity_function_to_use: Callable[[str, str], float] | None = None) str | None
Given a requested command and an iterable of possible options returns the most similar (if any is similar)
- Parameters:
requested_command – The command entered by the user
options – The list of available commands to search for the most similar
similarity_function_to_use – An optional callable to use to compare commands
- Returns:
The most similar command or None if no one is similar