Python Cmd module in Cisco IOS-style

Everything except argument processing is complete and tested in this version.  A new version that supports IOS-style arg processing is currently undergoing testing; it will be available in the very near future.

Source Code

import sys
from cmd import Cmd
USING_READLINE = True
try:
    # For platforms without readline support go visit ...
    # http://pypi.python.org/pypi/readline/
    import readline
except:
    try:
        # For Windows readline support go visit ...
        # https://launchpad.net/pyreadline
        import pyreadline
    except:
        USING_READLINE = False

class CmdLine(Cmd):
    """
    Help may be requested at any point in a command by entering
    a question mark '?'.  If nothing matches, the help list will
    be empty and you must backup until entering a '?' shows the
    available options.
    Two styles of help are provided:
    1. Full help is available when you are ready to enter a
       command argument (e.g. 'show ?') and describes each possible
       argument.
    2. Partial help is provided when an abbreviated argument is entered
       and you want to know what arguments match the input
       (e.g. 'show pr?'.)
    """ 
    def __init__(self):
        Cmd.__init__(self)
        if not USING_READLINE:
            self.completekey = None
        self.prompt = "#"
        self.intro  = "Python IOS-style command-line demonstration."
       
    def default(self, line):
        cmd, arg, line = self.parseline(line)
        cmds = self.completenames(cmd)
        num_cmds = len(cmds)
        if num_cmds == 1:
            getattr(self, 'do_'+cmds[0])(arg)
        elif num_cmds > 1:
            sys.stdout.write('%% Ambiguous command:\t"%s"\n' % cmd)
        else:
            sys.stdout.write('% Unrecognized command\n')

    def emptyline(self):
        pass
   
    def do_help(self, arg):
        doc_strings = [ (i[3:], getattr(self, i).__doc__)
            for i in dir(self) if i.startswith('do_') ]
        doc_strings = [ '  %s\t%s\n' % (i, j)
            for i, j in doc_strings if j is not None ]
        sys.stdout.write('Commands:\n%s\n' % ''.join(doc_strings))

    def do_shell(self, args):
        " Shell operations "
        sys.stdout.write('Executing Shell Command\n')
       
    def do_show(self, args):
        " Show running system information "
        sys.stdout.write('Executing Show Command\n')

    def precmd(self, line):
        if line.strip() == 'help':
            sys.stdout.write('%s\n' % self.__doc__)
            return ''
        cmd, arg, line = self.parseline(line)
        if arg == '?':
            cmds = self.completenames(cmd)
            if cmds:
                self.columnize(cmds)
                sys.stdout.write('\n')
            return ''
        return line           
   
# *** MAIN LOOP ***
if __name__ == '__main__':
    cmdLine = CmdLine()
    cmdLine.cmdloop()

Examples

Python IOS-style command-line demonstration.
#s
% Ambiguous command:    "s"
#z
% Unrecognized command
#help

    Help may be requested at any point in a command by entering
    a question mark '?'.  If nothing matches, the help list will
    be empty and you must backup until entering a '?' shows the
    available options.
    Two styles of help are provided:
    1. Full help is available when you are ready to enter a
       command argument (e.g. 'show ?') and describes each possible
       argument.
    2. Partial help is provided when an abbreviated argument is entered
       and you want to know what arguments match the input
       (e.g. 'show pr?'.)

#?
Commands:
  shell  Shell operations
  show   Show running system information

#show?
show

#show
Executing Show Command
#sho
Executing Show Command
#s?
shell  show

#shell
Executing Shell Command
#

Related Posts

Tags: , , ,

One Response to “Python Cmd module in Cisco IOS-style”

  1. Peter Nathan Says:

    Hello,

    Very nice tutorial. Really appreciate sharing your knowledge with others. You mentioned: “A new version that supports IOS-style arg processing is currently undergoing testing; it will be available in the very near future”.

    Is this available anywhere already ?

    thanks.
    Peter

Leave a comment