cmd2.Cmd

class cmd2.Cmd(completekey: str = 'tab', stdin: TextIO | None = None, stdout: TextIO | None = 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: List[str] | None = None, allow_redirection: bool = True, multiline_commands: List[str] | None = None, terminators: List[str] | None = None, shortcuts: Dict[str, str] | None = None, command_sets: Iterable[CommandSet] | None = None, auto_load_commands: bool = True, allow_clipboard: bool = True, suggest_similar_command: bool = False)

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: TextIO | None = None, stdout: TextIO | None = 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: List[str] | None = None, allow_redirection: bool = True, multiline_commands: List[str] | None = None, terminators: List[str] | None = None, shortcuts: Dict[str, str] | None = None, command_sets: Iterable[CommandSet] | None = None, auto_load_commands: bool = True, allow_clipboard: bool = True, suggest_similar_command: bool = False) 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, then cmd2.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 to False 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 is False. If allow_cli_args is True 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.

  • allow_clipboard – If False, cmd2 will disable clipboard interactions

  • suggest_similar_command – If True, cmd2 will attempt to suggest the most similar command when the user types a command that does not exist. Default: False.

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 of cmd2.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.

allow_clipboard

If True, cmd2 will allow output to be written to or appended to the operating system pasteboard. If False, this capability will not be allowed. See Clipboard Integration for more information.

suggest_similar_command

If True, cmd2 will attempt to suggest the most similar command when the user types a command that does not exist. Default: False.

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[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[CommandSet], *, subclass_match: bool = False) List[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) CommandSet | None

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: CommandSet) None

Installs a CommandSet, loading all commands defined in the CommandSet

Parameters:

cmdset – CommandSet to load

unregister_command_set(cmdset: 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, 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: 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: AllowStyle

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', apply_style: bool = True, paged: bool = False, chop: bool = False) 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 – object to print

  • end – string appended after the end of the message, default a newline

  • apply_style – If True, then ansi.style_output will be applied to the message text. Set to False in cases where the message text already has the desired style. Defaults to True.

  • paged – If True, pass the output through the configured pager.

  • chop – If paged is True, True to truncate long lines or False to wrap long lines.

perror(msg: Any = '', *, end: str = '\n', apply_style: bool = True, paged: bool = False, chop: bool = False) None

Print message to sys.stderr

Parameters:
  • msg – object 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.

  • paged – If True, pass the output through the configured pager.

  • chop – If paged is True, True to truncate long lines or False to wrap long lines.

psuccess(msg: Any = '', *, end: str = '\n', paged: bool = False, chop: bool = False) None

Writes to stdout applying ansi.style_success by default

Parameters:
  • msg – object to print

  • end – string appended after the end of the message, default a newline

  • paged – If True, pass the output through the configured pager.

  • chop – If paged is True, True to truncate long lines or False to wrap long lines.

pwarning(msg: Any = '', *, end: str = '\n', paged: bool = False, chop: bool = False) None

Wraps perror, but applies ansi.style_warning by default

Parameters:
  • msg – object to print

  • end – string appended after the end of the message, default a newline

  • paged – If True, pass the output through the configured pager.

  • chop – If paged is True, True to truncate long lines or False to wrap long lines.

pfailure(msg: Any = '', *, end: str = '\n', paged: bool = False, chop: bool = False) None

Writes to stderr applying ansi.style_error by default

Parameters:
  • msg – object to print

  • end – string appended after the end of the message, default a newline

  • paged – If True, pass the output through the configured pager.

  • chop – If paged is True, True to truncate long lines or False to wrap long lines.

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', apply_style: bool = True, paged: bool = False, chop: bool = False) None

For printing nonessential feedback. Can be silenced with quiet. Inclusion in redirected output is controlled by feedback_to_output.

Parameters:
  • msg – object to print

  • end – string appended after the end of the message, default a newline

  • apply_style – If True, then ansi.style_output will be applied to the message text. Set to False in cases where the message text already has the desired style. Defaults to True.

  • paged – If True, pass the output through the configured pager.

  • chop – If paged is True, True to truncate long lines or False to wrap long lines.

ppaged(msg: Any, *, end: str = '\n', chop: bool = False, dest: TextIO | IO[str] | None = None) None

Print output using a pager if it would go off screen and stdout isn’t currently being redirected.

Never uses a pager inside 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 – object to print

  • 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

  • dest – Optionally specify the destination stream to write to. If unspecified, defaults to self.stdout

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, Iterable[str] | CompleterFuncBase | CompleterFuncWithTokens], *, all_else: None | Iterable[str] | CompleterFuncBase | 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, Iterable[str] | CompleterFuncBase | CompleterFuncWithTokens], *, all_else: Iterable[str] | CompleterFuncBase | CompleterFuncWithTokens | None = 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: Callable[[str], bool] | None = 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: CustomCompletionSettings | None = None) str | None

Override of cmd’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 running inside a Python shell or pyscript

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, _: FrameType | None) None

Signal handler for SIGINTs which typically come from Ctrl-C events.

If you need custom SIGINT behavior, then override this method.

Parameters:
  • signum – signal number

  • _ – the current stack frame or None

termination_signal_handler(signum: int, _: FrameType | None) None

Signal handler for SIGHUP and SIGTERM. Only runs on Linux and Mac.

SIGHUP - received when terminal window is closed SIGTERM - received when this app has been requested to terminate

The basic purpose of this method is to call sys.exit() so our exit handler will run and save the persistent history file. If you need more complex behavior like killing threads and performing cleanup, then override this method.

Parameters:
  • signum – signal number

  • _ – the current stack frame or None

precmd(statement: Statement | str) 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() and register_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: 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() and register_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, orig_rl_history_length: int | None = None) 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.

  • orig_rl_history_length – Optional length of the readline history before the current command was typed. This is used to assist in combining multiline readline history entries and is only populated by cmd2. Defaults to None.

Returns:

True if running of commands should stop

runcmds_plus_hooks(cmds: List[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) Callable[[...], bool | None] | None

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: 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: Statement) bool | None

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: List[str] | None = None, completion_mode: CompletionMode = CompletionMode.NONE, preserve_quotes: bool = False, choices: Iterable[Any] | None = None, choices_provider: ChoicesProviderFuncBase | ChoicesProviderFuncWithTokens | None = None, completer: CompleterFuncBase | CompleterFuncWithTokens | None = None, parser: ArgumentParser | None = 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: Namespace) None

Manage aliases

do_macro(args: Namespace) None

Manage macros

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: Namespace) None

List available commands or provide detailed help for a specific command

print_topics(header: str, cmds: List[str] | None, cmdlen: int, maxcol: int) None

Print groups of commands and topics in columns and an optional header Override of cmd’s print_topics() to handle headers with newlines, ANSI style sequences, and wide characters

Parameters:
  • header – string to print above commands being printed

  • cmds – list of topics to print

  • cmdlen – unused, even by cmd’s version

  • maxcol – max number of display columns to fit into

columnize(str_list: List[str] | None, display_width: int = 80) None

Display a list of single-line strings as a compact set of columns. Override of cmd’s print_topics() to handle strings with ANSI style sequences and wide characters

Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough).

do_shortcuts(_: Namespace) None

List available shortcuts

do_eof(_: Namespace) bool | None

Called when Ctrl-D is pressed and calls quit with no arguments. This can be overridden if quit should be called differently.

do_quit(_: Namespace) bool | None

Exit this application

select(opts: str | List[str] | List[Tuple[Any, str | None]], prompt: str = 'Your choice? ') Any

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 options
a list of strings -> will be offered as options
a 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: Namespace) None

Set a settable parameter or show current settings of parameters

do_shell(args: Namespace) None

Execute a command as if at the OS prompt

do_py(_: Namespace) bool | None

Run an interactive Python shell :return: True if running of commands should stop

do_run_pyscript(args: Namespace) bool | None

Run a Python script file inside the console

Returns:

True if running of commands should stop

do_ipy(_: Namespace) bool | None

Enter an interactive IPython shell

Returns:

True if running of commands should stop

do_history(args: Namespace) bool | None

View, run, edit, save, or clear previously entered commands

Returns:

True if running of commands should stop

do_edit(args: Namespace) None

Run a text editor and optionally open a file with it

run_editor(file_path: str | None = 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: Namespace) bool | None

Run commands in script file that is encoded as either ASCII or UTF-8 text.

Returns:

True if running of commands should stop

do__relative_run_script(args: Namespace) bool | None

Run commands in script file that is encoded as either ASCII or UTF-8 text

Returns:

True if running of commands should stop

async_alert(alert_msg: str, new_prompt: str | None = 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.

This function needs to acquire self.terminal_lock to ensure a prompt is on screen. Therefore, it is best to acquire the lock before calling this function to avoid raising a RuntimeError.

This function is only needed when you need to print an alert or update the prompt while the main thread is blocking at the prompt. Therefore, this should never be called from the main thread. Doing so will raise 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.

Raises:
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.

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

Raises:
async_refresh_prompt() None

Refresh the oncreen prompt to match self.prompt.

One case where the onscreen prompt and self.prompt can get out of sync is when async_alert() is called while a user is in search mode (e.g. Ctrl-r). To prevent overwriting readline’s onscreen search prompt, self.prompt is updated but readline’s saved prompt isn’t.

Therefore when a user aborts a search, the old prompt is still on screen until they press Enter or this method is called. Call need_prompt_refresh() in an async print thread to know when a refresh is needed.

Raises:
need_prompt_refresh() bool

Check whether the onscreen prompt needs to be asynchronously refreshed to match self.prompt.

static set_window_title(title: str) None

Set the terminal window title.

NOTE: This function writes to stderr. Therefore, if you call this during a command run by a pyscript,

the string which updates the title will appear in that command’s CommandResult.stderr data.

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: str | None = 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[[PostparsingData], PostparsingData]) None

Register a function to be called after parsing user input but before running the command

register_precmd_hook(func: Callable[[PrecommandData], PrecommandData]) None

Register a hook to be called before the command function.

register_postcmd_hook(func: Callable[[PostcommandData], PostcommandData]) None

Register a hook to be called after the command function.

register_cmdfinalization_hook(func: Callable[[CommandFinalizationData], CommandFinalizationData]) None

Register a hook to be called after a command is completed, whether it completes successfully or not.