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?
import argparse
def scream(args):
print "you screamed "+' '.join(args.words)
def count(args):
print "you counted to {0}".format(args.count)
parser = argparse.ArgumentParser()
#tell the parser that there will be subparsers
subparsers = parser.add_subparsers(help="subparsers")
#Add parsers to the object that was returned by `add_subparsers`
parser_scream = subparsers.add_parser('scream')
#use that as you would any other argument parser
parser_scream.add_argument('words',nargs='*')
#set_defaults is nice to call a function which is specific to each subparser
parser_scream.set_defaults(func=scream)
#repeat for our next sub-command
parser_count = subparsers.add_parser('count')
parser_count.add_argument('count')
parser_count.set_defaults(func=count)
#parse the args
args = parser.parse_args()
args.func(args) #args.func is the function that was set for the particular subparser
now run it:
>python test.py scream Hello World! #you screamed Hello World!
>python test.py count 10 #you counted to 10
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