How should I implement "nested" subcommands in Python?

tima picture tima · Dec 14, 2011 · Viewed 11.9k times · Source

Implementing "nested" subcommands in Python with cmdln.

I'm not sure I'm using the right terminology here. I'm trying to implement a commandline tool using cmdln that allows for "nested" subcommands. Here is a real world example:

git svn rebase

What is the best way of implementing this? I've been searching for more information on this in the doc, here and the web at large, but have come up empty. (Perhaps I was searching with the wrong terms.)

Short of an undocumented feature that does this automatically, my initial thought was to have the previous subcommand handler determine that there is another subcommand and dispatch the command dispatcher again. I've looked at the internals of cmdln though and the dispatcher is a private method, _dispatch_cmd. My next thought is to create my own sub-sub-command dispatcher, but that seems less than ideal and messy.

Any help would be appreciated.

Answer

Derek Ruths picture Derek Ruths · Jul 28, 2015

Late to the party here, but I've had to do this quite a bit and have found argparse pretty clunky to do this with. This motivated me to write an extension to argparse called arghandler, which has explicit support for this - making is possible implement subcommands with basically zero lines of code.

Here's an example:

from arghandler import *

@subcmd
def push(context,args):
    print 'command: push'

@subcmd
def pull(context,args):
    print 'command: pull'

# run the command - which will gather up all the subcommands
handler = ArgumentHandler()
handler.run()