cmd2.utils
cmd2.utils
Shared utility functions.
Settable
Settable(name, val_type, description, settable_object, *, settable_attrib_name=None, onchange_cb=None, choices=None, choices_provider=None, completer=None)
Used to configure an attribute to be settable via the set command in the CLI.
Settable Initializer.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
The user-facing name for this setting in the CLI.
TYPE:
|
val_type
|
A callable used to cast the string value from the CLI into its proper type and validate it. This function should raise an exception (like ValueError or TypeError) if the conversion or validation fails, which will be caught and displayed to the user by the set command. For example, setting this to int ensures the input is a valid integer. Specifying bool automatically provides tab completion for 'true' and 'false' and uses a built-in function for conversion and validation.
TYPE:
|
description
|
A concise string that describes the purpose of this setting.
TYPE:
|
settable_object
|
The object that owns the attribute being made settable (e.g. self).
TYPE:
|
settable_attrib_name
|
The name of the attribute on the settable_object that will be modified. This defaults to the value of the name parameter if not specified.
TYPE:
|
onchange_cb
|
An optional function or method to call when the value of this setting is altered by the set command. The callback is invoked only if the new value is different from the old one. It receives three arguments: param_name: str - name of the parameter old_value: Any - the parameter's old value new_value: Any - the parameter's new value 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.
TYPE:
|
choices
|
iterable of accepted values
TYPE:
|
choices_provider
|
function that provides choices for this argument
TYPE:
|
completer
|
tab completion function that provides choices for this argument
TYPE:
|
Source code in cmd2/utils.py
settable_attrib_name
instance-attribute
StdSim
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.
StdSim Initializer.
| PARAMETER | DESCRIPTION |
|---|---|
inner_stream
|
the wrapped stream. Should be a TextIO or StdSim instance.
TYPE:
|
echo
|
if True, then all input will be echoed to inner_stream
TYPE:
|
encoding
|
codec for encoding/decoding strings (defaults to utf-8)
TYPE:
|
errors
|
how to handle encoding/decoding errors (defaults to replace)
TYPE:
|
Source code in cmd2/utils.py
line_buffering
property
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.
write
Add str to internal bytes buffer and if echo is True, echo contents to inner stream.
| PARAMETER | DESCRIPTION |
|---|---|
s
|
String to write to the stream
TYPE:
|
Source code in cmd2/utils.py
getvalue
getbytes
read
Read from the internal contents as a str and then clear them out.
| PARAMETER | DESCRIPTION |
|---|---|
size
|
Number of bytes to read from the stream
TYPE:
|
Source code in cmd2/utils.py
readbytes
clear
isatty
StdSim only considered an interactive stream if echo is True and inner_stream is a tty.
ByteBuf
Used by StdSim to write binary data and stores the actual bytes written.
Initialize the ByteBuf instance.
Source code in cmd2/utils.py
write
Add bytes to internal bytes buffer and if echo is True, echo contents to inner stream.
Source code in cmd2/utils.py
ProcReader
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.
ProcReader initializer.
| PARAMETER | DESCRIPTION |
|---|---|
proc
|
the Popen process being read from
TYPE:
|
stdout
|
the stream to write captured stdout
TYPE:
|
stderr
|
the stream to write captured stderr.
TYPE:
|
Source code in cmd2/utils.py
send_sigint
Send a SIGINT to the process similar to if
Source code in cmd2/utils.py
terminate
wait
Wait for the process to finish.
Source code in cmd2/utils.py
ContextFlag
A context manager which is also used as a boolean flag value within the default sigint handler.
Its main use is as a flag to prevent the SIGINT handler in cmd2 from raising a KeyboardInterrupt while a critical code section has set the flag to True. Because signal handling is always done on the main thread, this class is not thread-safe since there is no need.
When this flag has a positive value, it is considered set. When it is 0, it is not set.
It should never go below 0.
Source code in cmd2/utils.py
RedirectionSavedState
Created by each command to store information required to restore state after redirection.
RedirectionSavedState initializer.
| PARAMETER | DESCRIPTION |
|---|---|
self_stdout
|
saved value of Cmd.stdout
TYPE:
|
stdouts_match
|
True if Cmd.stdout is equal to sys.stdout
TYPE:
|
pipe_proc_reader
|
saved value of Cmd._cur_pipe_proc_reader
TYPE:
|
saved_redirecting
|
saved value of Cmd._redirecting.
TYPE:
|
Source code in cmd2/utils.py
CompletionMode
CustomCompletionSettings
Used by cmd2.Cmd.complete() to tab complete strings other than command arguments.
CustomCompletionSettings initializer.
| PARAMETER | DESCRIPTION |
|---|---|
parser
|
arg parser defining format of string being tab completed
TYPE:
|
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.
TYPE:
|
Source code in cmd2/utils.py
to_bool
Convert 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()
| PARAMETER | DESCRIPTION |
|---|---|
val
|
value being converted
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
boolean value expressed in the passed in value |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if the string does not contain a value corresponding to a boolean value |
Source code in cmd2/utils.py
is_text_file
Return if a file contains only ASCII or UTF-8 encoded text and isn't empty.
| PARAMETER | DESCRIPTION |
|---|---|
file_path
|
path to the file being checked
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the file is a non-empty text file, otherwise False |
| RAISES | DESCRIPTION |
|---|---|
OSError
|
if file can't be read |
Source code in cmd2/utils.py
remove_duplicates
Remove duplicates from a list while preserving order of the items.
| PARAMETER | DESCRIPTION |
|---|---|
list_to_prune
|
the list being pruned of duplicates
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[_T]
|
The pruned list |
Source code in cmd2/utils.py
alphabetical_sort
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)
| PARAMETER | DESCRIPTION |
|---|---|
list_to_sort
|
the list being sorted
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
the sorted list |
Source code in cmd2/utils.py
try_int_or_force_to_lower_case
Try to convert the passed-in string to an integer. If that fails, it converts it to lower case using norm_fold.
| PARAMETER | DESCRIPTION |
|---|---|
input_str
|
string to convert
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int | str
|
the string as an integer or a lower case version of the string. |
Source code in cmd2/utils.py
natural_keys
Convert a string into a list of integers and strings to support natural sorting (see natural_sort).
For example: natural_keys('abc123def') -> ['abc', '123', 'def']
| PARAMETER | DESCRIPTION |
|---|---|
input_str
|
string to convert
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[int | str]
|
list of strings and integers |
Source code in cmd2/utils.py
natural_sort
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)
| PARAMETER | DESCRIPTION |
|---|---|
list_to_sort
|
the list being sorted
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
the list sorted naturally |
Source code in cmd2/utils.py
quote_specific_tokens
Quote specific tokens in a list.
| PARAMETER | DESCRIPTION |
|---|---|
tokens
|
token list being edited
TYPE:
|
tokens_to_quote
|
the tokens, which if present in tokens, to quote
TYPE:
|
Source code in cmd2/utils.py
unquote_specific_tokens
Unquote specific tokens in a list.
| PARAMETER | DESCRIPTION |
|---|---|
tokens
|
token list being edited
TYPE:
|
tokens_to_unquote
|
the tokens, which if present in tokens, to unquote
TYPE:
|
Source code in cmd2/utils.py
expand_user
Wrap os.expanduser() to support expanding ~ in quoted strings.
| PARAMETER | DESCRIPTION |
|---|---|
token
|
the string to expand
TYPE:
|
Source code in cmd2/utils.py
expand_user_in_tokens
Call expand_user() on all tokens in a list of strings.
| PARAMETER | DESCRIPTION |
|---|---|
tokens
|
tokens to expand.
TYPE:
|
find_editor
Set cmd2.Cmd.DEFAULT_EDITOR. If EDITOR env variable is set, that will be used.
Otherwise the function will look for a known editor in directories specified by PATH env variable.
| RETURNS | DESCRIPTION |
|---|---|
str | None
|
Default editor or None. |
Source code in cmd2/utils.py
files_from_glob_pattern
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.
| PARAMETER | DESCRIPTION |
|---|---|
pattern
|
file name or glob pattern
TYPE:
|
access
|
file access type to verify (os.* where * is F_OK, R_OK, W_OK, or X_OK)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
list of files matching the name or glob pattern |
Source code in cmd2/utils.py
files_from_glob_patterns
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.
| PARAMETER | DESCRIPTION |
|---|---|
patterns
|
list of file names and/or glob patterns
TYPE:
|
access
|
file access type to verify (os.* where * is F_OK, R_OK, W_OK, or X_OK)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
list of files matching the names and/or glob patterns |
Source code in cmd2/utils.py
get_exes_in_path
Return names of executables in a user's path.
| PARAMETER | DESCRIPTION |
|---|---|
starts_with
|
what the exes should start with. leave blank for all exes in path.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
a list of matching exe names |
Source code in cmd2/utils.py
categorize
Categorize a function.
The help command output will group the passed function under the specified category heading
| PARAMETER | DESCRIPTION |
|---|---|
func
|
function or list of functions to categorize
TYPE:
|
category
|
category to put it in Example:
TYPE:
|
Source code in cmd2/utils.py
get_defining_class
Attempt to resolve the class that defined a method.
Inspired by implementation published here: https://stackoverflow.com/a/25959545/1956611
| PARAMETER | DESCRIPTION |
|---|---|
meth
|
method to inspect
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
type[Any] | None
|
class type in which the supplied method was defined. None if it couldn't be resolved. |
Source code in cmd2/utils.py
strip_doc_annotations
Strip annotations from a docstring leaving only the text description.
| PARAMETER | DESCRIPTION |
|---|---|
doc
|
documentation string
TYPE:
|
Source code in cmd2/utils.py
similarity_function
Ratio from s1,s2 may be different to s2,s1. We keep the max.
See https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.ratio
Source code in cmd2/utils.py
suggest_similar
Given a requested command and an iterable of possible options returns the most similar (if any is similar).
| PARAMETER | DESCRIPTION |
|---|---|
requested_command
|
The command entered by the user
TYPE:
|
options
|
The list of available commands to search for the most similar
TYPE:
|
similarity_function_to_use
|
An optional callable to use to compare commands
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str | None
|
The most similar command or None if no one is similar |
Source code in cmd2/utils.py
get_types
Use inspect.get_annotations() to extract type hints for parameters and return value.
This is a thin convenience wrapper around inspect.get_annotations() that treats the return value annotation separately.
| PARAMETER | DESCRIPTION |
|---|---|
func_or_method
|
Function or method to return the type hints for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[dict[str, Any], Any]
|
tuple with first element being dictionary mapping param names to type hints and second element being the return type hint or None if there is no return value type hint |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if the |