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.
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.
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!
Update for year 2020!
Click library has easier usage
Fire is a cool library for making your app command line featured!
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With