cmd2.Cmd¶
- class cmd2.Cmd(completekey: str = 'tab', stdin: Optional[TextIO] = None, stdout: Optional[TextIO] = None, *, persistent_history_file: str = '', persistent_history_length: int = 1000, startup_script: str = '', silence_startup_script: bool = False, include_py: bool = False, include_ipy: bool = False, allow_cli_args: bool = True, transcript_files: Optional[List[str]] = None, allow_redirection: bool = True, multiline_commands: Optional[List[str]] = None, terminators: Optional[List[str]] = None, shortcuts: Optional[Dict[str, str]] = None, command_sets: Optional[Iterable[cmd2.command_definition.CommandSet]] = None, auto_load_commands: bool = True)¶
An easy but powerful framework for writing line-oriented command interpreters.
Extends the Python Standard Library’s cmd package by adding a lot of useful features to the out of the box configuration.
Line-oriented command interpreters are often useful for test harnesses, internal tools, and rapid prototypes.
- __init__(completekey: str = 'tab', stdin: Optional[TextIO] = None, stdout: Optional[TextIO] = None, *, persistent_history_file: str = '', persistent_history_length: int = 1000, startup_script: str = '', silence_startup_script: bool = False, include_py: bool = False, include_ipy: bool = False, allow_cli_args: bool = True, transcript_files: Optional[List[str]] = None, allow_redirection: bool = True, multiline_commands: Optional[List[str]] = None, terminators: Optional[List[str]] = None, shortcuts: Optional[Dict[str, str]] = None, command_sets: Optional[Iterable[cmd2.command_definition.CommandSet]] = None, auto_load_commands: bool = True) → None¶
An easy but powerful framework for writing line-oriented command interpreters. Extends Python’s cmd package.
- Parameters
completekey – readline name of a completion key, default to Tab
stdin – alternate input file object, if not specified, sys.stdin is used
stdout – alternate output file object, if not specified, sys.stdout is used
persistent_history_file – file path to load a persistent cmd2 command history from
persistent_history_length – max number of history items to write to the persistent history file
startup_script – file path to a script to execute at startup
silence_startup_script – if
True
, then the startup script’s output will be suppressed. Anything written to stderr will still display.include_py – should the “py” command be included for an embedded Python shell
include_ipy – should the “ipy” command be included for an embedded IPython shell
allow_cli_args – if
True
, thencmd2.Cmd.__init__()
will process command line arguments as either commands to be run or, if-t
or--test
are given, transcript files to run. This should be set toFalse
if your application parses its own command line arguments.transcript_files – pass a list of transcript files to be run on initialization. This allows running transcript tests when
allow_cli_args
isFalse
. Ifallow_cli_args
isTrue
this parameter is ignored.allow_redirection – If
False
, prevent output redirection and piping to shell commands. This parameter prevents redirection and piping, but does not alter parsing behavior. A user can still type redirection and piping tokens, and they will be parsed as such but they won’t do anything.multiline_commands – list of commands allowed to accept multi-line input
terminators – list of characters that terminate a command. These are mainly intended for terminating multiline commands, but will also terminate single-line commands. If not supplied, the default is a semicolon. If your app only contains single-line commands and you want terminators to be treated as literals by the parser, then set this to an empty list.
shortcuts – dictionary containing shortcuts for commands. If not supplied, then defaults to constants.DEFAULT_SHORTCUTS. If you do not want any shortcuts, pass an empty dictionary.
command_sets – Provide CommandSet instances to load during cmd2 initialization. This allows CommandSets with custom constructor parameters to be loaded. This also allows the a set of CommandSets to be provided when auto_load_commands is set to False
auto_load_commands – If True, cmd2 will check for all subclasses of CommandSet that are currently loaded by Python and automatically instantiate and register all commands. If False, CommandSets must be manually installed with register_command_set.
- default_error¶
The error message displayed when a non-existent command is run. Default:
{} is not a recognized command, alias, or macro
- help_error¶
The error message displayed to the user when they request help for a command with no help defined. Default:
No help on {}
- prompt¶
The prompt issued to solicit input. The default value is
(Cmd)
. See Prompt for more information.
- continuation_prompt¶
The prompt issued to solicit input for the 2nd and subsequent lines of a multiline command Default:
>
.
- echo¶
If
True
, output the prompt and user input before executing the command. When redirecting a series of commands to an output file, this allows you to see the command in the output.
- settable¶
This dictionary contains the name and description of all settings available to users.
Users use the set command to view and modify settings. Settings are stored in instance attributes with the same name as the setting.
- history¶
A record of previously entered commands.
This attribute is an instance of
cmd2.history.History
, and each command is an instance ofcmd2.Statement
.
- statement_parser¶
An instance of
cmd2.parsing.StatementParser
initialized and configured appropriately for parsing user input.
- intro¶
Set an introduction message which is displayed to the user before the Command Processing Loop begins.
- py_bridge_name¶
The symbol name which Python Scripts run using the run_pyscript command can use to reference the parent
cmd2
application.
- ALPHABETICAL_SORT_KEY() → 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
- NATURAL_SORT_KEY() → List[Union[str, int]]¶
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
- find_commandsets(commandset_type: Type[cmd2.command_definition.CommandSet], *, subclass_match: bool = False) → List[cmd2.command_definition.CommandSet]¶
Find all CommandSets that match the provided CommandSet type. By default, locates a CommandSet that is an exact type match but may optionally return all CommandSets that are sub-classes of the provided type :param commandset_type: CommandSet sub-class type to search for :param subclass_match: If True, return all sub-classes of provided type, otherwise only search for exact match :return: Matching CommandSets
- find_commandset_for_command(command_name: str) → Optional[cmd2.command_definition.CommandSet]¶
Finds the CommandSet that registered the command name :param command_name: command name to search :return: CommandSet that provided the command
- register_command_set(cmdset: cmd2.command_definition.CommandSet) → None¶
Installs a CommandSet, loading all commands defined in the CommandSet
- Parameters
cmdset – CommandSet to load
- unregister_command_set(cmdset: cmd2.command_definition.CommandSet) → None¶
Uninstalls a CommandSet and unloads all associated commands
- Parameters
cmdset – CommandSet to uninstall
- property always_prefix_settables: bool¶
Flags whether CommandSet settable values should always be prefixed
- Returns
True if CommandSet settable values will always be prefixed. False if not.
- property settables: Mapping[str, cmd2.utils.Settable]¶
Get all available user-settable attributes. This includes settables defined in installed CommandSets
- Returns
Mapping from attribute-name to Settable of all user-settable attributes from
- add_settable(settable: cmd2.utils.Settable) → None¶
Add a settable parameter to
self.settables
- Parameters
settable – Settable object being added
- remove_settable(name: str) → None¶
Convenience method for removing a settable parameter from
self.settables
- Parameters
name – name of the settable being removed
- Raises
KeyError if the Settable matches this name
- build_settables() → None¶
Create the dictionary of user-settable parameters
- property allow_style: str¶
Read-only property needed to support do_set when it reads allow_style
- property visible_prompt: str¶
Read-only property to get the visible prompt with any ANSI style escape codes stripped.
Used by transcript testing to make it easier and more reliable when users are doing things like coloring the prompt using ANSI color codes.
- Returns
prompt stripped of any ANSI escape codes
- poutput(msg: Any = '', *, end: str = '\n') → None¶
Print message to self.stdout and appends a newline by default
Also handles BrokenPipeError exceptions for when a command’s output has been piped to another process and that process terminates before the cmd2 command is finished executing.
- Parameters
msg – message to print (anything convertible to a str)
end – string appended after the end of the message, default a newline
- perror(msg: Any = '', *, end: str = '\n', apply_style: bool = True) → None¶
Print message to sys.stderr
- Parameters
msg – message to print (anything convertible to a str)
end – string appended after the end of the message, default a newline
apply_style – If True, then ansi.style_error will be applied to the message text. Set to False in cases where the message text already has the desired style. Defaults to True.
- pwarning(msg: Any = '', *, end: str = '\n', apply_style: bool = True) → None¶
Wraps perror, but applies ansi.style_warning by default
- Parameters
msg – message to print (anything convertible to a str)
end – string appended after the end of the message, default a newline
apply_style – If True, then ansi.style_warning will be applied to the message text. Set to False in cases where the message text already has the desired style. Defaults to True.
- pexcept(msg: Any, *, end: str = '\n', apply_style: bool = True) → None¶
Print Exception message to sys.stderr. If debug is true, print exception traceback if one exists.
- Parameters
msg – message or Exception to print
end – string appended after the end of the message, default a newline
apply_style – If True, then ansi.style_error will be applied to the message text. Set to False in cases where the message text already has the desired style. Defaults to True.
- pfeedback(msg: Any, *, end: str = '\n') → None¶
For printing nonessential feedback. Can be silenced with quiet. Inclusion in redirected output is controlled by feedback_to_output.
- Parameters
msg – message to print (anything convertible to a str)
end – string appended after the end of the message, default a newline
- ppaged(msg: Any, *, end: str = '\n', chop: bool = False) → None¶
Print output using a pager if it would go off screen and stdout isn’t currently being redirected.
Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when stdout or stdin are not a fully functional terminal.
- Parameters
msg – message to print to current stdout (anything convertible to a str)
end – string appended after the end of the message, default a newline
chop –
- True -> causes lines longer than the screen width to be chopped (truncated) rather than wrapped
truncated text is still accessible by scrolling with the right & left arrow keys
chopping is ideal for displaying wide tabular data as is done in utilities like pgcli
- False -> causes lines longer than the screen width to wrap to the next line
wrapping is ideal when you want to keep users from having to use horizontal scrolling
WARNING: On Windows, the text always wraps regardless of what the chop argument is set to
- tokens_for_completion(line: str, begidx: int, endidx: int) → Tuple[List[str], List[str]]¶
Used by tab completion functions to get all tokens through the one being completed.
- Parameters
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
- Returns
A 2 item tuple where the items are On Success - tokens: list of unquoted tokens - this is generally the list needed for tab completion functions - raw_tokens: list of tokens with any quotes preserved = this can be used to know if a token was quoted or is missing a closing quote Both lists are guaranteed to have at least 1 item. The last item in both lists is the token being tab completed On Failure - Two empty lists
- basic_complete(text: str, line: str, begidx: int, endidx: int, match_against: Iterable[str]) → 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
- delimiter_complete(text: str, line: str, begidx: int, endidx: int, match_against: Iterable[str], delimiter: str) → List[str]¶
Performs tab completion against a list but each match is split on a delimiter and only the portion of the match being tab completed is shown as the completion suggestions. This is useful if you match against strings that are hierarchical in nature and have a common delimiter.
An easy way to illustrate this concept is path completion since paths are just directories/files delimited by a slash. If you are tab completing items in /home/user you don’t get the following as suggestions:
/home/user/file.txt /home/user/program.c /home/user/maps/ /home/user/cmd2.py
Instead you are shown:
file.txt program.c maps/ cmd2.py
For a large set of data, this can be visually more pleasing and easier to search.
Another example would be strings formatted with the following syntax: company::department::name In this case the delimiter would be :: and the user could easily narrow down what they are looking for if they were only shown suggestions in the category they are at in the string.
- 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 list being matched against
delimiter – what delimits each portion of the matches (ex: paths are delimited by a slash)
- Returns
a list of possible tab completions
- flag_based_complete(text: str, line: str, begidx: int, endidx: int, flag_dict: Dict[str, Union[Iterable[str], cmd2.argparse_custom.CompleterFuncBase, cmd2.argparse_custom.CompleterFuncWithTokens]], *, all_else: Union[None, Iterable[str], cmd2.argparse_custom.CompleterFuncBase, cmd2.argparse_custom.CompleterFuncWithTokens] = None) → List[str]¶
Tab completes based on a particular flag preceding the token being completed.
- 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
flag_dict – dictionary whose structure is the following: keys - flags (ex: -c, –create) that result in tab completion for the next argument in the command line values - there are two types of values: 1. iterable list of strings to match against (dictionaries, lists, etc.) 2. function that performs tab completion (ex: path_complete)
all_else – an optional parameter for tab completing any token that isn’t preceded by a flag in flag_dict
- Returns
a list of possible tab completions
- index_based_complete(text: str, line: str, begidx: int, endidx: int, index_dict: Mapping[int, Union[Iterable[str], cmd2.argparse_custom.CompleterFuncBase, cmd2.argparse_custom.CompleterFuncWithTokens]], *, all_else: Union[None, Iterable[str], cmd2.argparse_custom.CompleterFuncBase, cmd2.argparse_custom.CompleterFuncWithTokens] = None) → List[str]¶
Tab completes based on a fixed position in the input string.
- 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
index_dict – dictionary whose structure is the following: keys - 0-based token indexes into command line that determine which tokens perform tab completion values - there are two types of values: 1. iterable list of strings to match against (dictionaries, lists, etc.) 2. function that performs tab completion (ex: path_complete)
all_else – an optional parameter for tab completing any token that isn’t at an index in index_dict
- Returns
a list of possible tab completions
- path_complete(text: str, line: str, begidx: int, endidx: int, *, path_filter: Optional[Callable[[str], bool]] = None) → List[str]¶
Performs completion of local file system paths
- 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
path_filter – optional filter function that determines if a path belongs in the results this function takes a path as its argument and returns True if the path should be kept in the results
- Returns
a list of possible tab completions
- shell_cmd_complete(text: str, line: str, begidx: int, endidx: int, *, complete_blank: bool = False) → List[str]¶
Performs completion of executables either in a user’s path or a given path
- 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
complete_blank – If True, then a blank will complete all shell commands in a user’s path. If False, then no completion is performed. Defaults to False to match Bash shell behavior.
- Returns
a list of possible tab completions
- complete(text: str, state: int, custom_settings: Optional[cmd2.utils.CustomCompletionSettings] = None) → Optional[str]¶
Override of cmd2’s complete method which returns the next possible completion for ‘text’
This completer function is called by readline as complete(text, state), for state in 0, 1, 2, …, until it returns a non-string value. It should return the next possible completion starting with text.
Since readline suppresses any exception raised in completer functions, they can be difficult to debug. Therefore this function wraps the actual tab completion logic and prints to stderr any exception that occurs before returning control to readline.
- Parameters
text – the current word that user is typing
state – non-negative integer
custom_settings – used when not tab completing the main command line
- Returns
the next possible completion for text or None
- in_script() → bool¶
Return whether a text script is running
- in_pyscript() → bool¶
Return whether a pyscript is running
- property aliases: Dict[str, str]¶
Read-only property to access the aliases stored in the StatementParser
- get_names() → List[str]¶
Return an alphabetized list of names comprising the attributes of the cmd2 class instance.
- get_all_commands() → List[str]¶
Return a list of all commands
- get_visible_commands() → List[str]¶
Return a list of commands that have not been hidden or disabled
- get_help_topics() → List[str]¶
Return a list of help topics
- sigint_handler(signum: int, _: frame) → None¶
Signal handler for SIGINTs which typically come from Ctrl-C events.
If you need custom SIGINT behavior, then override this function.
- Parameters
signum – signal number
_ – required param for signal handlers
- precmd(statement: Union[cmd2.parsing.Statement, str]) → cmd2.parsing.Statement¶
Hook method executed just before the command is executed by
onecmd()
and after adding it to history.- Parameters
statement – subclass of str which also contains the parsed input
- Returns
a potentially modified version of the input Statement object
See
register_postparsing_hook()
andregister_precmd_hook()
for more robust ways to run hooks before the command is executed. See Postparsing Hooks and Precommand Hooks for more information.
- postcmd(stop: bool, statement: Union[cmd2.parsing.Statement, str]) → bool¶
Hook method executed just after a command is executed by
onecmd()
.- Parameters
stop – return True to request the command loop terminate
statement – subclass of str which also contains the parsed input
See
register_postcmd_hook()
andregister_cmdfinalization_hook()
for more robust ways to run hooks after the command is executed. See Postcommand Hooks and Command Finalization Hooks for more information.
- preloop() → None¶
Hook method executed once when the
cmdloop()
method is called.See
register_preloop_hook()
for a more robust way to run hooks before the command loop begins. See Application Lifecycle Hooks for more information.
- postloop() → None¶
Hook method executed once when the
cmdloop()
method is about to return.See
register_postloop_hook()
for a more robust way to run hooks after the command loop completes. See Application Lifecycle Hooks for more information.
- parseline(line: str) → Tuple[str, str, str]¶
Parse the line into a command name and a string containing the arguments.
NOTE: This is an override of a parent class method. It is only used by other parent class methods.
Different from the parent class method, this ignores self.identchars.
- Parameters
line – line read by readline
- Returns
tuple containing (command, args, line)
- onecmd_plus_hooks(line: str, *, add_to_history: bool = True, raise_keyboard_interrupt: bool = False, py_bridge_call: bool = False) → bool¶
Top-level function called by cmdloop() to handle parsing a line and running the command and all of its hooks.
- Parameters
line – command line to run
add_to_history – If True, then add this command to history. Defaults to True.
raise_keyboard_interrupt – if True, then KeyboardInterrupt exceptions will be raised if stop isn’t already True. This is used when running commands in a loop to be able to stop the whole loop and not just the current command. Defaults to False.
py_bridge_call – This should only ever be set to True by PyBridge to signify the beginning of an app() call from Python. It is used to enable/disable the storage of the command’s stdout.
- Returns
True if running of commands should stop
- runcmds_plus_hooks(cmds: Union[List[cmd2.history.HistoryItem], List[str]], *, add_to_history: bool = True, stop_on_keyboard_interrupt: bool = False) → bool¶
Used when commands are being run in an automated fashion like text scripts or history replays. The prompt and command line for each command will be printed if echo is True.
- Parameters
cmds – commands to run
add_to_history – If True, then add these commands to history. Defaults to True.
stop_on_keyboard_interrupt – if True, then stop running contents of cmds if Ctrl-C is pressed instead of moving to the next command in the list. This is used when the commands are part of a group, like a text script, which should stop upon Ctrl-C. Defaults to False.
- Returns
True if running of commands should stop
- cmd_func(command: str) → Optional[Callable[[...], Optional[bool]]]¶
Get the function for a command
- Parameters
command – the name of the command
- Example
>>> helpfunc = self.cmd_func('help')
helpfunc now contains a reference to the
do_help
method
- onecmd(statement: Union[cmd2.parsing.Statement, str], *, add_to_history: bool = True) → bool¶
This executes the actual do_* method for a command.
If the command provided doesn’t exist, then it executes default() instead.
- Parameters
statement – intended to be a Statement instance parsed command from the input stream, alternative acceptance of a str is present only for backward compatibility with cmd
add_to_history – If True, then add this command to history. Defaults to True.
- Returns
a flag indicating whether the interpretation of commands should stop
- default(statement: cmd2.parsing.Statement) → Optional[bool]¶
Executed when the command given isn’t a recognized command implemented by a do_* method.
- Parameters
statement – Statement object with parsed input
- read_input(prompt: str, *, history: Optional[List[str]] = None, completion_mode: cmd2.utils.CompletionMode = <CompletionMode.NONE: 1>, preserve_quotes: bool = False, choices: Optional[Iterable[Any]] = None, choices_provider: Optional[Union[cmd2.argparse_custom.ChoicesProviderFuncBase, cmd2.argparse_custom.ChoicesProviderFuncWithTokens]] = None, completer: Optional[Union[cmd2.argparse_custom.CompleterFuncBase, cmd2.argparse_custom.CompleterFuncWithTokens]] = None, parser: Optional[argparse.ArgumentParser] = None) → str¶
Read input from appropriate stdin value. Also supports tab completion and up-arrow history while input is being entered.
- Parameters
prompt – prompt to display to user
history – optional list of strings to use for up-arrow history. If completion_mode is CompletionMode.COMMANDS and this is None, then cmd2’s command list history will be used. The passed in history will not be edited. It is the caller’s responsibility to add the returned input to history if desired. Defaults to None.
completion_mode – tells what type of tab completion to support. Tab completion only works when self.use_rawinput is True and sys.stdin is a terminal. Defaults to CompletionMode.NONE.
The following optional settings apply when completion_mode is CompletionMode.CUSTOM:
- Parameters
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.
A maximum of one of these should be provided:
- Parameters
choices – iterable of accepted values for single argument
choices_provider – function that provides choices for single argument
completer – tab completion function that provides choices for single argument
parser – an argument parser which supports the tab completion of multiple arguments
- Returns
the line read from stdin with all trailing new lines removed
- Raises
any exceptions raised by input() and stdin.readline()
- do_alias(args: argparse.Namespace) → None¶
Manage aliases
An alias is a command that enables replacement of a word by another string.
- do_macro(args: argparse.Namespace) → None¶
Manage macros
A macro is similar to an alias, but it can contain argument placeholders.
- complete_help_command(text: str, line: str, begidx: int, endidx: int) → List[str]¶
Completes the command argument of help
- complete_help_subcommands(text: str, line: str, begidx: int, endidx: int, arg_tokens: Dict[str, List[str]]) → List[str]¶
Completes the subcommands argument of help
- do_help(args: argparse.Namespace) → None¶
List available commands or provide detailed help for a specific command
- do_shortcuts(_: argparse.Namespace) → None¶
List available shortcuts
- do_eof(_: argparse.Namespace) → Optional[bool]¶
Called when Ctrl-D is pressed
- do_quit(_: argparse.Namespace) → Optional[bool]¶
Exit this application
- select(opts: Union[str, List[str], List[Tuple[Any, Optional[str]]]], prompt: str = 'Your choice? ') → str¶
Presents a numbered menu to the user. Modeled after the bash shell’s SELECT. Returns the item chosen.
Argument
opts
can be:a single string -> will be split into one-word optionsa list of strings -> will be offered as optionsa list of tuples -> interpreted as (value, text), so that the return value can differ from the text advertised to the user
- complete_set_value(text: str, line: str, begidx: int, endidx: int, arg_tokens: Dict[str, List[str]]) → List[str]¶
Completes the value argument of set
- do_set(args: argparse.Namespace) → None¶
Set a settable parameter or show current settings of parameters
- do_shell(args: argparse.Namespace) → None¶
Execute a command as if at the OS prompt
- do_py(_: argparse.Namespace) → Optional[bool]¶
Run an interactive Python shell
- do_run_pyscript(args: argparse.Namespace) → Optional[bool]¶
Run a Python script file inside the console
- do_ipy(_: argparse.Namespace) → Optional[bool]¶
Run an interactive IPython shell
- do_history(args: argparse.Namespace) → Optional[bool]¶
View, run, edit, save, or clear previously entered commands
- do_edit(args: argparse.Namespace) → None¶
Run a text editor and optionally open a file with it
The editor used is determined by a settable parameter. To set it:
set editor (program-name)
- run_editor(file_path: Optional[str] = None) → None¶
Run a text editor and optionally open a file with it
- Parameters
file_path – optional path of the file to edit. Defaults to None.
- Raises
EnvironmentError if self.editor is not set
- do_run_script(args: argparse.Namespace) → Optional[bool]¶
Run commands in script file that is encoded as either ASCII or UTF-8 text
Script should contain one command per line, just like the command would be typed in the console.
If the -t/–transcript flag is used, this command instead records the output of the script commands to a transcript for testing purposes.
- do__relative_run_script(args: argparse.Namespace) → Optional[bool]¶
Run commands in script file that is encoded as either ASCII or UTF-8 text
Script should contain one command per line, just like the command would be typed in the console.
If the -t/–transcript flag is used, this command instead records the output of the script commands to a transcript for testing purposes.
If this is called from within an already-running script, the filename will be interpreted relative to the already-running script’s directory.
- async_alert(alert_msg: str, new_prompt: Optional[str] = None) → None¶
Display an important message to the user while they are at a command line prompt. To the user it appears as if an alert message is printed above the prompt and their current input text and cursor location is left alone.
Raises a RuntimeError if called while another thread holds terminal_lock.
- IMPORTANT: This function will not print an alert unless it can acquire self.terminal_lock to ensure
a prompt is onscreen. Therefore it is best to acquire the lock before calling this function to guarantee the alert prints and to avoid raising a RuntimeError.
- Parameters
alert_msg – the message to display to the user
new_prompt – if you also want to change the prompt that is displayed, then include it here see async_update_prompt() docstring for guidance on updating a prompt
- async_update_prompt(new_prompt: str) → None¶
Update the command line prompt while the user is still typing at it. This is good for alerting the user to system changes dynamically in between commands. For instance you could alter the color of the prompt to indicate a system status or increase a counter to report an event. If you do alter the actual text of the prompt, it is best to keep the prompt the same width as what’s on screen. Otherwise the user’s input text will be shifted and the update will not be seamless.
Raises a RuntimeError if called while another thread holds terminal_lock.
- IMPORTANT: This function will not update the prompt unless it can acquire self.terminal_lock to ensure
a prompt is onscreen. Therefore it is best to acquire the lock before calling this function to guarantee the prompt changes and to avoid raising a RuntimeError.
If user is at a continuation prompt while entering a multiline command, the onscreen prompt will not change. However self.prompt will still be updated and display immediately after the multiline line command completes.
- Parameters
new_prompt – what to change the prompt to
- set_window_title(title: str) → None¶
Set the terminal window title.
Raises a RuntimeError if called while another thread holds terminal_lock.
- IMPORTANT: This function will not set the title unless it can acquire self.terminal_lock to avoid writing
to stderr while a command is running. Therefore it is best to acquire the lock before calling this function to guarantee the title changes and to avoid raising a RuntimeError.
- Parameters
title – the new window title
- enable_command(command: str) → None¶
Enable a command by restoring its functions
- Parameters
command – the command being enabled
- enable_category(category: str) → None¶
Enable an entire category of commands
- Parameters
category – the category to enable
- disable_command(command: str, message_to_print: str) → None¶
Disable a command and overwrite its functions
- Parameters
command – the command being disabled
message_to_print –
what to print when this command is run or help is called on it while disabled
The variable cmd2.COMMAND_NAME can be used as a placeholder for the name of the command being disabled. ex: message_to_print = f”{cmd2.COMMAND_NAME} is currently disabled”
- disable_category(category: str, message_to_print: str) → None¶
Disable an entire category of commands.
- Parameters
category – the category to disable
message_to_print – what to print when anything in this category is run or help is called on it while disabled. The variable cmd2.COMMAND_NAME can be used as a placeholder for the name of the command being disabled. ex: message_to_print = f”{cmd2.COMMAND_NAME} is currently disabled”
- cmdloop(intro: Optional[str] = None) → int¶
This is an outer wrapper around _cmdloop() which deals with extra features provided by cmd2.
_cmdloop() provides the main loop equivalent to cmd.cmdloop(). This is a wrapper around that which deals with the following extra features provided by cmd2: - transcript testing - intro banner - exit code
- Parameters
intro – if provided this overrides self.intro and serves as the intro banner printed once at start
- register_preloop_hook(func: Callable[], None]) → None¶
Register a function to be called at the beginning of the command loop.
- register_postloop_hook(func: Callable[], None]) → None¶
Register a function to be called at the end of the command loop.
- register_postparsing_hook(func: Callable[[cmd2.plugin.PostparsingData], cmd2.plugin.PostparsingData]) → None¶
Register a function to be called after parsing user input but before running the command
- register_precmd_hook(func: Callable[[cmd2.plugin.PrecommandData], cmd2.plugin.PrecommandData]) → None¶
Register a hook to be called before the command function.
- register_postcmd_hook(func: Callable[[cmd2.plugin.PostcommandData], cmd2.plugin.PostcommandData]) → None¶
Register a hook to be called after the command function.
- register_cmdfinalization_hook(func: Callable[[cmd2.plugin.CommandFinalizationData], cmd2.plugin.CommandFinalizationData]) → None¶
Register a hook to be called after a command is completed, whether it completes successfully or not.