Skip to content
Open Trading edited this page Feb 26, 2016 · 3 revisions

Cmd2

cmd2 is a tool for writing command-line interactive applications. It is based on the Python Standard Library's cmd module, and can be used anyplace cmd is used simply by importing cmd2 instead.

cmd2}} provides the following features, in addition to those already existing in {{{cmd:

  • Searchable command history
  • Load commands from file, save to file, edit commands in file
  • Multi-line commands
  • Case-insensitive commands
  • Special-character shortcut commands (beyond cmd's @ and !)
  • Settable environment parameters
  • Parsing commands with flags
  • Redirection to file with >, >>; input from file with <
  • Bare '>', '>>' with no filename send output to paste buffer
  • Pipe output to shell commands with |
  • Simple transcript-based application testing

Searchable command history

All commands will automatically be tracked in the session's history, unless the command is listed in Cmd's excludeFromHistory attribute. The history is accessed through the history, list, and run commands (and their abbreviations: hi, li, l, r). If you wish to exclude some of your custom commands from the history, append their names to the list at Cmd.ExcludeFromHistory.

Load commands from file, save to file, edit commands in file

Type help load, help save, help edit for details.

Multi-line commands

Any command accepts multi-line input when its name is listed in Cmd.multilineCommands. The program will keep expecting input until a line ends with any of the characters in Cmd.terminators . The default terminators are ; and /n (empty newline).

Case-insensitive commands

All commands are case-insensitive, unless Cmd.caseInsensitive is set to False.

Special-character shortcut commands (beyond cmd's "@" and "!")

To create a single-character shortcut for a command, update Cmd.shortcuts.

Settable environment parameters

To allow a user to change an environment parameter during program execution, append the parameter's name to Cmd.settable.

Parsing commands with optparse options (flags)

See Python standard library's optparse

Useful Subcommands

Useful cmd2 subcommands are:

  • history - show the command history; rereun commands with: run.
  • load FILE - load a script of commands from FILE.
  • save * FILE - save a script of commands to FILE; use * for all commands, a number for that command, or nothing for the last command.
  • edit - edit the previous command in an editor, or edit *, or edit FILE; commands are run after editor is closed; used EDITOR environment var.
  • py [CMD] - execute a Python command CMD, or with no arguments, enter a Python loop: In the loop: self = CMD2 object, self.oOm = Omellete, self.oOm.oBt = Oven
  • help [SUB] - help, or help on subcommand SUB.

See also:


Parent: Components

Clone this wiki locally