Utility Functions

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_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.decorators.categorize(func: Union[Callable, Iterable[Callable]], category: str) → None

Categorize a function.

The help command output will group this function under the specified category heading

Parameters:
  • func – function or list of functions to categorize
  • category – category to put it in
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 a 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) ValueError if text or fill_char contains an unprintable character 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 a 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) ValueError if text or fill_char contains an unprintable character 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 a 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) ValueError if text or fill_char contains an unprintable character 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 a 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) ValueError if text or fill_char contains an unprintable character 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.

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 new line ValueError if max_width is less than 1

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.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.which(exe_name: str) → Optional[str]

Find the full path of a given executable on a Linux or Mac machine

Parameters:exe_name – name of the executable to check, ie ‘vi’ or ‘ls’
Returns:a full path or None if exe not found
cmd2.utils.is_text_file(file_path: str) → bool

Returns if a file contains only ASCII or UTF-8 encoded text.

Parameters:file_path – path to the file being checked
Returns:True if the file is a text file, False if it is binary.
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.norm_fold(astr: str) → str

Normalize and casefold Unicode strings for saner comparisons.

Parameters:astr – input unicode string
Returns:a normalized and case-folded version of the input string
cmd2.utils.try_int_or_force_to_lower_case(input_str: str) → Union[int, str]

Tries to convert the passed-in string to an integer. If that fails, it converts it to lower case using norm_fold. :param input_str: string to convert :return: the string as an integer or a lower case version of the string

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.unquote_specific_tokens(args: List[str], tokens_to_unquote: List[str]) → None

Unquote a specific tokens in a list of command-line arguments This is used when certain tokens have to be passed to another command :param args: the command line args :param tokens_to_unquote: the tokens, which if present in args, to unquote

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.natural_keys(input_str: str) → List[Union[int, str]]

Converts a string into a list of integers and strings to support natural sorting (see natural_sort).

For example: natural_keys(‘abc123def’) -> [‘abc’, ‘123’, ‘def’] :param input_str: string to convert :return: list of strings and integers

cmd2.utils.expand_user_in_tokens(tokens: List[str]) → None

Call expand_user() on all tokens in a list of strings :param tokens: tokens to expand

cmd2.utils.expand_user(token: str) → str

Wrap os.expanduser() to support expanding ~ in quoted strings :param token: the string to expand

cmd2.utils.find_editor() → str

Find a reasonable editor to use by default for the system that the cmd2 application is running on.

cmd2.utils.get_exes_in_path(starts_with: str) → List[str]

Returns names of executables in a user’s path

Parameters:starts_with – what the exes should start with. leave blank for all exes in path.
Returns:a list of matching exe names
cmd2.utils.files_from_glob_patterns(patterns: List[str], access=0) → List[str]

Return a list of file paths based on a list of glob patterns.

Only files are returned, not directories, and optionally only files for which the user has a specified access to.

Parameters:
  • patterns – list of file names and/or glob patterns
  • access – file access type to verify (os.* where * is F_OK, R_OK, W_OK, or X_OK)
Returns:

list of files matching the names and/or glob patterns

cmd2.utils.files_from_glob_pattern(pattern: str, access=0) → List[str]

Return a list of file paths based on a glob pattern.

Only files are returned, not directories, and optionally only files for which the user has a specified access to.

Parameters:
  • pattern – file name or glob pattern
  • access – file access type to verify (os.* where * is F_OK, R_OK, W_OK, or X_OK)
Returns:

list of files matching the name or glob pattern