Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I implement "nested" subcommands in Python?

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.

like image 318
tima Avatar asked Dec 14 '11 21:12

tima


People also ask

What is subcommand in Python?

Used to define subcommands under a main command. For example, within git commit , commit is a subcommand of git . Subcommands can also be nested within subcommands.

How do you execute a command in python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!


2 Answers

Update for year 2020!
Click library has easier usage
Fire is a cool library for making your app command line featured!

like image 178
Iman Avatar answered Oct 18 '22 01:10

Iman


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()
like image 27
Derek Ruths Avatar answered Oct 18 '22 01:10

Derek Ruths