I would like to get the following functionality while using the add_subparsers
method of the argparse
library and without using the keyword argument nargs
:
$ python my_program.py scream Hello
You just screamed Hello!!
$ python my_program.py count ten
You just counted to ten.
I know I could do this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("cmd", help="Execute a command", action="store",
nargs='*')
args = parser.parse_args()
args_list = args.cmd
if len(args.cmd) == 2:
if args.cmd[0] == "scream":
if args.cmd[1] == "Hello":
print "You just screamed Hello!!"
else:
print "You just screamed some other command!!"
elif args.cmd[0] == "count":
if args.cmd[1]:
print "You just counted to %s." % args.cmd[1]
else:
pass
else:
print "These two commands are undefined"
else:
print "These commands are undefined"
But then when I do $ python my_program.py
I lose that default arparse text that shows a list of arguments etc. .
I know there is an add_subparsers
method of the argparse
library that can handle more than one positional argument but I have not found a way to get it properly working. Could anyone show me how?