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.cmd2.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.center_text(msg: str, *, pad: str = ' ') → str

Centers text horizontally for display within the current terminal, optionally padding both sides.

Parameters:
  • msg – message to display in the center
  • pad – if provided, the first character will be used to pad both sides of the message
Returns:

centered message, optionally padded on both sides with pad_char

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.cast(current: Any, new: str) → Any

Tries to force a new value into the same type as the current when trying to set the value for a parameter.

Parameters:
  • current – current value for the parameter, type varies
  • new – new value
Returns:

new value with same type as current, or the current value if there was an error casting

cmd2.utils.which(editor: str) → Optional[str]

Find the full path of a given editor.

Return the full path of the given editor, or None if the editor can not be found.

Parameters:editor – filename of the editor to check, ie ‘notepad.exe’ or ‘vi’
Returns:a full path or None
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