cmd2.utils
Settings
cmd2.utils.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
|
name of the instance attribute being made settable
TYPE:
|
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 to_bool(). The val_type function should raise an exception if it fails. This exception will be caught and printed by Cmd.do_set().
TYPE:
|
description
|
string describing this setting
TYPE:
|
settable_object
|
object to which the instance attribute belongs (e.g. self)
TYPE:
|
settable_attrib_name
|
name which displays to the user in the output of the set command. Defaults to
TYPE:
|
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.
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
get_value
set_value
Set the settable attribute on the specified destination object.
PARAMETER | DESCRIPTION |
---|---|
value
|
new value to set
TYPE:
|
Source code in cmd2/utils.py
Quote Handling
cmd2.utils.is_quoted
Checks if a string is quoted
PARAMETER | DESCRIPTION |
---|---|
arg
|
the string being checked for quotes
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
bool
|
True if a string is quoted |
cmd2.utils.quote_string
cmd2.utils.quote_string_if_needed
cmd2.utils.strip_quotes
Strip outer quotes from a string.
Applies to both single and double quotes.
PARAMETER | DESCRIPTION |
---|---|
arg
|
string to strip outer quotes from
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
same string with potentially outer quotes stripped |
Source code in cmd2/utils.py
IO Handling
cmd2.utils.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.
cmd2.utils.ByteBuf
Used by StdSim to write binary data and stores the actual bytes written
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
cmd2.utils.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
Tab Completion
cmd2.utils.CompletionMode
cmd2.utils.CustomCompletionSettings
Used by cmd2.Cmd.complete() to tab complete strings other than command arguments
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
Text Alignment
cmd2.utils.TextAlignment
cmd2.utils.align_text
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()
PARAMETER | DESCRIPTION |
---|---|
text
|
text to align (can contain multiple lines)
TYPE:
|
alignment
|
how to align the text
TYPE:
|
fill_char
|
character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
TYPE:
|
width
|
display width of the aligned text. Defaults to width of the terminal.
TYPE:
|
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.
TYPE:
|
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.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
aligned text |
RAISES | DESCRIPTION |
---|---|
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 |
Source code in cmd2/utils.py
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 |
|
cmd2.utils.align_left
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.
PARAMETER | DESCRIPTION |
---|---|
text
|
text to left align (can contain multiple lines)
TYPE:
|
fill_char
|
character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
TYPE:
|
width
|
display width of the aligned text. Defaults to width of the terminal.
TYPE:
|
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.
TYPE:
|
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.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
left-aligned text |
RAISES | DESCRIPTION |
---|---|
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 |
Source code in cmd2/utils.py
cmd2.utils.align_right
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.
PARAMETER | DESCRIPTION |
---|---|
text
|
text to right align (can contain multiple lines)
TYPE:
|
fill_char
|
character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
TYPE:
|
width
|
display width of the aligned text. Defaults to width of the terminal.
TYPE:
|
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.
TYPE:
|
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.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
right-aligned text |
RAISES | DESCRIPTION |
---|---|
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 |
Source code in cmd2/utils.py
cmd2.utils.align_center
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.
PARAMETER | DESCRIPTION |
---|---|
text
|
text to center (can contain multiple lines)
TYPE:
|
fill_char
|
character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
TYPE:
|
width
|
display width of the aligned text. Defaults to width of the terminal.
TYPE:
|
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.
TYPE:
|
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.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
centered text |
RAISES | DESCRIPTION |
---|---|
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 |
Source code in cmd2/utils.py
cmd2.utils.truncate_line
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.
PARAMETER | DESCRIPTION |
---|---|
line
|
text to truncate
TYPE:
|
max_width
|
the maximum display width the resulting string is allowed to have
TYPE:
|
tab_width
|
any tabs in the text will be replaced with this many spaces
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
line that has a display width less than or equal to width |
RAISES | DESCRIPTION |
---|---|
ValueError
|
if text contains an unprintable character like a newline |
ValueError
|
if max_width is less than 1 |
Source code in cmd2/utils.py
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 |
|
Miscellaneous
cmd2.utils.to_bool
Converts 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
cmd2.utils.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
cmd2.utils.remove_duplicates
Removes 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
cmd2.utils.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
cmd2.utils.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
cmd2.utils.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 |
---|---|
Optional[str]
|
The most similar command or None if no one is similar |