cmd2.utils

Settings

class cmd2.utils.Settable(name: str, val_type: Union[Type[Any], Callable[[Any], Any]], description: str, settable_object: object, *, settable_attrib_name: Optional[str] = None, onchange_cb: Optional[Callable[[str, _T, _T], Any]] = None, choices: Optional[Iterable[Any]] = None, choices_provider: Union[cmd2.argparse_custom.ChoicesProviderFuncBase, cmd2.argparse_custom.ChoicesProviderFuncWithTokens, None] = None, completer: Union[cmd2.argparse_custom.CompleterFuncBase, cmd2.argparse_custom.CompleterFuncWithTokens, None] = None)

Used to configure an attribute to be settable via the set command in the CLI

__init__(name: str, val_type: Union[Type[Any], Callable[[Any], Any]], description: str, settable_object: object, *, settable_attrib_name: Optional[str] = None, onchange_cb: Optional[Callable[[str, _T, _T], Any]] = None, choices: Optional[Iterable[Any]] = None, choices_provider: Union[cmd2.argparse_custom.ChoicesProviderFuncBase, cmd2.argparse_custom.ChoicesProviderFuncWithTokens, None] = None, completer: Union[cmd2.argparse_custom.CompleterFuncBase, cmd2.argparse_custom.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 str_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: Union[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.

clear() → None

Clear the internal contents

getbytes() → bytes

Get the internal contents as bytes

getvalue() → str

Get the internal contents as a str

isatty() → bool

StdSim only considered an interactive stream if echo is True and inner_stream is a tty.

line_buffering

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.

read(size: Optional[int] = -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

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
class cmd2.utils.ByteBuf(std_sim_instance: cmd2.utils.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: subprocess.Popen, stdout: Union[cmd2.utils.StdSim, TextIO], stderr: Union[cmd2.utils.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

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: argparse.ArgumentParser, *, preserve_quotes: bool = False)

Used by cmd2.Cmd.complete() to tab complete strings other than command arguments

__init__(parser: argparse.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

Horizontal text alignment

CENTER = 2
LEFT = 1
RIGHT = 3
cmd2.utils.align_text(text: str, alignment: cmd2.utils.TextAlignment, *, fill_char: str = ' ', width: Optional[int] = 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: Optional[int] = 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: Optional[int] = 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: Optional[int] = 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.str_to_bool(val: str) → bool

Converts a string to a boolean based on its value.

Parameters:val – string being converted
Returns:boolean value expressed in the string
Raises:ValueError if the string does not contain a value corresponding to a boolean value
cmd2.utils.categorize(func: Union[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