cmd2 Application Lifecycle and Hooks

The typical way of starting a cmd2 application is as follows:

from cmd2 import Cmd
class App(Cmd):
    # customized attributes and methods here
app = App()
app.cmdloop()

There are several pre-existing methods and attributes which you can tweak to control the overall behavior of your application before, during, and after the main loop.

Application Lifecycle Hook Methods

The preloop and postloop methods run before and after the main loop, respectively.

Cmd.preloop()

Hook method executed once when the cmdloop() method is called.

Cmd.postloop()

Hook method executed once when the cmdloop() method is about to return.

Application Lifecycle Attributes

There are numerous attributes (member variables of the cmd2.Cmd) which have a significant effect on the application behavior upon entering or during the main loop. A partial list of some of the more important ones is presented here:

  • intro: str - if provided this serves as the intro banner printed once at start of application, after preloop runs
  • allow_cli_args: bool - if True (default), then searches for -t or –test at command line to invoke transcript testing mode instead of a normal main loop
    and also processes any commands provided as arguments on the command line just prior to entering the main loop
  • echo: bool - if True, then the command line entered is echoed to the screen (most useful when running scripts)
  • prompt: str - sets the prompt which is displayed, can be dynamically changed based on application state and/or
    command results

Command Processing Hooks

Inside the main loop, every time the user hits <Enter> the line is processed by the onecmd_plus_hooks method.

Cmd.onecmd_plus_hooks(line)

Top-level function called by cmdloop() to handle parsing a line and running the command and all of its hooks.

Parameters:line – str - line of text read from input
Returns:bool - True if cmdloop() should exit, False otherwise

As the onecmd_plus_hooks name implies, there are a number of hook methods that can be defined in order to inject application-specific behavior at various points during the processing of a line of text entered by the user. cmd2 increases the 2 hooks provided by cmd (precmd and postcmd) to 6 for greater flexibility. Here are the various hook methods, presented in chronological order starting with the ones called earliest in the process.

Cmd.preparse(raw)

Hook method executed just before the command line is interpreted, but after the input prompt is generated.

Parameters:raw – str - raw command line input
Returns:str - potentially modified raw command line input
Cmd.postparse(parse_result)

Hook that runs immediately after parsing the command-line but before parsed() returns a ParsedString.

Parameters:parse_result – pyparsing.ParseResults - parsing results output by the pyparsing parser
Returns:pyparsing.ParseResults - potentially modified ParseResults object
Cmd.postparsing_precmd(statement)

This runs after parsing the command-line, but before anything else; even before adding cmd to history.

NOTE: This runs before precmd() and prior to any potential output redirection or piping.

If you wish to fatally fail this command and exit the application entirely, set stop = True.

If you wish to just fail this command you can do so by raising an exception:

  • raise EmptyStatement - will silently fail and do nothing
  • raise <AnyOtherException> - will fail and print an error message
Parameters:statement
  • the parsed command-line statement
Returns:(bool, statement) - (stop, statement) containing a potentially modified version of the statement
Cmd.precmd(statement)

Hook method executed just before the command is processed by onecmd() and after adding it to the history.

Parameters:statement – ParsedString - subclass of str which also contains pyparsing ParseResults instance
Returns:ParsedString - a potentially modified version of the input ParsedString statement
Cmd.postcmd(stop, line)

Hook method executed just after a command dispatch is finished.

Cmd.postparsing_postcmd(stop)

This runs after everything else, including after postcmd().

It even runs when an empty line is entered. Thus, if you need to do something like update the prompt due to notifications from a background thread, then this is the method you want to override to do it.

Parameters:stop – bool - True implies the entire application should exit.
Returns:bool - True implies the entire application should exit.