cmd2.utils

Settings

class cmd2.utils.Settable(name: str, val_type: Callable, description: str, *, onchange_cb: Callable[[str, Any, Any], Any] = None, choices: Iterable[T_co] = None, choices_function: Optional[Callable] = None, choices_method: Optional[Callable] = None, completer_function: Optional[Callable] = None, completer_method: Optional[Callable] = None)

Used to configure a cmd2 instance member to be settable via the set command in the CLI

__init__(name: str, val_type: Callable, description: str, *, onchange_cb: Callable[[str, Any, Any], Any] = None, choices: Iterable[T_co] = None, choices_function: Optional[Callable] = None, choices_method: Optional[Callable] = None, completer_function: Optional[Callable] = None, completer_method: Optional[Callable] = 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
  • 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_function – function that provides choices for this argument
  • choices_method – cmd2-app method that provides choices for this argument (See note below)
  • completer_function – tab completion function that provides choices for this argument
  • completer_method – cmd2-app tab completion method that provides choices for this argument (See note below)

Note: For choices_method and completer_method, do not set them to a bound method. This is because ArgparseCompleter passes the self argument explicitly to these functions.

Therefore instead of passing something like self.path_complete, pass cmd2.Cmd.path_complete.

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

IO Handling

class cmd2.utils.StdSim(inner_stream, *, 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

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

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.CompletionError(*args, apply_style: bool = True, **kwargs)

Raised during tab completion operations to report any sort of error you want printed. This can also be used just to display a message, even if it’s not an error. For instance, ArgparseCompleter raises CompletionErrors to display tab completion hints and sets apply_style to False so hints aren’t colored like error text.

Example use cases

  • Reading a database to retrieve a tab completion data set failed
  • A previous command line argument that determines the data set being completed is invalid
  • Tab completion hints
cmd2.utils.basic_complete(text: str, line: str, begidx: int, endidx: int, match_against: Iterable[T_co]) → List[str]

Basic tab completion function that matches against a list of strings without considering line contents or cursor position. The args required by this function are defined in the header of Python’s cmd.py.

Parameters:
  • text – the string prefix we are attempting to match (all matches must begin with it)
  • line – the current input line with leading whitespace removed
  • begidx – the beginning index of the prefix text
  • endidx – the ending index of the prefix text
  • match_against – the strings being matched against
Returns:

a list of possible tab completions

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_string(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.namedtuple_with_defaults(typename: str, field_names: Union[str, List[str]], default_values: collections.abc.Iterable = ())

Convenience function for defining a namedtuple with default values

From: https://stackoverflow.com/questions/11351032/namedtuple-and-default-values-for-optional-keyword-arguments

Examples:
>>> Node = namedtuple_with_defaults('Node', 'val left right')
>>> Node()
Node(val=None, left=None, right=None)
>>> Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3])
>>> Node()
Node(val=1, left=2, right=3)
>>> Node = namedtuple_with_defaults('Node', 'val left right', {'right':7})
>>> Node()
Node(val=None, left=None, right=7)
>>> Node(4)
Node(val=4, left=None, right=7)
cmd2.utils.categorize(func: Union[Callable, Iterable[Callable]], 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