cmd2

Author: Catherine Devlin, http://catherinedevlin.blogspot.com

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:

Instructions for implementing each feature follow.

cmd2 can be installed with easy_install cmd2

Cheese Shop page: http://pypi.python.org/pypi/cmd2

Example cmd2 application (example/example.py)

'''A sample application for cmd2.'''

from cmd2 import Cmd, make_option, options, Cmd2TestCase
import unittest, optparse, sys

class CmdLineApp(Cmd):
    multilineCommands = ['orate']
    Cmd.shortcuts.update({'&': 'speak'})
    maxrepeats = 3
    Cmd.settable.append('maxrepeats')

    @options([make_option('-p', '--piglatin', action="store_true", help="atinLay"),
              make_option('-s', '--shout', action="store_true", help="N00B EMULATION MODE"),
              make_option('-r', '--repeat', type="int", help="output [n] times")
             ])
    def do_speak(self, arg, opts=None):
        """Repeats what you tell me to."""
        arg = ''.join(arg)
        if opts.piglatin:
            arg = '%s%say' % (arg[1:], arg[0])
        if opts.shout:
            arg = arg.upper()
        repetitions = opts.repeat or 1
        for i in range(min(repetitions, self.maxrepeats)):
            self.stdout.write(arg)
            self.stdout.write('\n')
            # self.stdout.write is better than "print", because Cmd can be
            # initialized with a non-standard output destination

    do_say = do_speak     # now "say" is a synonym for "speak"
    do_orate = do_speak   # another synonym, but this one takes multi-line input

class TestMyAppCase(Cmd2TestCase):
    CmdApp = CmdLineApp
    transcriptFileName = 'exampleSession.txt'

parser = optparse.OptionParser()
parser.add_option('-t', '--test', dest='unittests', action='store_true', default=False, help='Run unit test suite')
(callopts, callargs) = parser.parse_args()
if callopts.unittests:
    sys.argv = [sys.argv[0]]  # the --test argument upsets unittest.main()
    unittest.main()
else:
    app = CmdLineApp()
    app.cmdloop()

The following is a sample session running example.py. Thanks to TestMyAppCase(Cmd2TestCase), it also serves as a test suite for example.py when saved as exampleSession.txt. Running python example.py -t will run all the commands in the transcript against example.py, verifying that the output produced matches the transcript.

example/exampleSession.txt:

(Cmd) help

Documented commands (type help <topic>):
========================================
_load  edit  history  li    load   r    save  set    shortcuts  speak
ed     hi    l        list  orate  run  say   shell  show

Undocumented commands:
======================
EOF  cmdenvironment  eof  exit  help  q  quit

(Cmd) help say
Repeats what you tell me to.
Usage: speak [options] arg

Options:
  -h, --help            show this help message and exit
  -p, --piglatin        atinLay
  -s, --shout           N00B EMULATION MODE
  -r REPEAT, --repeat=REPEAT
                        output [n] times

(Cmd) say goodnight, Gracie
goodnight, Gracie
(Cmd) say -ps --repeat=5 goodnight, Gracie
OODNIGHT, GRACIEGAY
OODNIGHT, GRACIEGAY
OODNIGHT, GRACIEGAY
(Cmd) set
prompt: (Cmd)
editor: gedit
echo: False
maxrepeats: 3
(Cmd) set maxrepeats 5
maxrepeats - was: 3
now: 5
(Cmd) say -ps --repeat=5 goodnight, Gracie
OODNIGHT, GRACIEGAY
OODNIGHT, GRACIEGAY
OODNIGHT, GRACIEGAY
OODNIGHT, GRACIEGAY
OODNIGHT, GRACIEGAY
(Cmd) hi
-------------------------[1]
help
-------------------------[2]
help say
-------------------------[3]
say goodnight, Gracie
-------------------------[4]
say -ps --repeat=5 goodnight, Gracie
-------------------------[5]
set
-------------------------[6]
set maxrepeats 5
-------------------------[7]
say -ps --repeat=5 goodnight, Gracie
(Cmd) run 4
say -ps --repeat=5 goodnight, Gracie
OODNIGHT, GRACIEGAY
OODNIGHT, GRACIEGAY
OODNIGHT, GRACIEGAY
OODNIGHT, GRACIEGAY
OODNIGHT, GRACIEGAY
(Cmd) orate Four score and
> seven releases ago
> our BDFL
> blah blah blah
>
>
Four score and seven releases ago our BDFL blah blah blah
(Cmd) & look, a shortcut!
look, a shortcut!
(Cmd) say put this in a file > myfile.txt
(Cmd) say < myfile.txt
put this in a file
(Cmd) set prompt "---> "
prompt - was: (Cmd)
now: --->
---> say goodbye
goodbye