[Twisted-Python] Cisco-style hierarchial CLI

Tommi Virtanen tv at tv.debian.net
Mon Mar 22 06:25:58 EST 2004


Phil Mayers wrote:
> I'm putting together some glue-ware for a system, and would like to hide
> the underlying nature of it. It's a bit of software that fits in and
> around routers / switches etc. and there's a pretty common CLI for those
> these days, which consists of a hierarchial context-based set of
> commands, plus completion, e.g. on Cisco, although I suspect everyone is
> familiar with the concept:
...
> Any such beast exist?

Have a look at twisted.python.usage's idea of subCommands, that should
help. You need to build tab completion etc. on top of that; but ideally,
t.p.usage will allow you to have the same thing available straight from
shell:

$ mycommand sub1 --option=42 sub2 -f sub3
Doing stuff...

or

$ mycommand
your-app-here> sub1 --option=42
sub1> sub2 -f
sub1 sub2> sub3
Doing stuff...

sub1 sub2>


Additionally, this snippet allows you to implement the subcommand
modularly, with twisted's plugin architecture.

--8<--
from twisted.python import usage, plugin

class SubCommandOptions(usage.Options):
     def __init__(self):
         usage.Options.__init__(self)
         self.subCommands = []
         plugins = plugin.getPlugIns('YourApplicationNameHere-command')
         plugins.sort()
         for p in plugins:
             module = p.load()
             description = getattr(p, 'description', None)
             self.subCommands.append((p.name,
                                      None,
                                      getattr(module, 'Command'),
                                      description))
         self.subCommands.sort()

     def postOptions(self):
         if not hasattr(self, 'subOptions'):
             self.opt_help()
--8<--

--8<--
# plugins.tml
register(
     type="YourApplicationNameHere-command",
     module="YourApp.commands.sub1",
     name="sub1",
     description="Frobble the kibits",
)
--8<--

--8<--
# YourApp/commands/sub1.py
from twisted.python import usage

class Command(usage.Options):
     def postOptions(self):
	do_stuff_here()
--8<--




More information about the Twisted-Python mailing list