Python argparse: how to change `--add` to` add`, but still an optional argument?

I want this functionality:

$ python program.py add Peter 'Peter' was added to the list of names. 

I can achieve this with --add instead of add as follows:

 import argparse parser = argparse.ArgumentParser() parser.add_argument("--add", help="Add a new name to the list of names", action="store") args = parser.parse_args() if args.add: print "'%s' was added to the list of names." % args.add else: print "Just executing the program baby." 

Thus:

 $ python program.py --add Peter 'Peter' was added to the list of names. 

But when I change --add to add , it is no longer optional, how can I let it be optional but not have these signs -- ? (preferably also using the argparse library)

+3
python command-line-arguments argparse
source share
2 answers

What you want is actually called "positional arguments." You can parse them like this:

 import argparse parser = argparse.ArgumentParser() parser.add_argument("cmd", help="Execute a command", action="store", nargs='*') args = parser.parse_args() if args.cmd: cmd, name = args.cmd print "'%s' was '%s'-ed to the list of names." % (name, cmd) else: print "Just executing the program baby." 

Which gives you the ability to specify different actions:

 $ python g.py add peter 'peter' was 'add'-ed to the list of names. $ python g.py del peter 'peter' was 'del'-ed to the list of names. $ python g.py Just executing the program baby. 
+2
source share

You can use sub-commands to achieve this behavior. Try the following:

 import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(title='Subcommands', description='valid subcommands', help='additional help') addparser = subparsers.add_parser('add') addparser.add_argument('names', nargs='*') args = parser.parse_args() if args.names: print "'%s' was added to the list of names." % args.names else: print "Just executing the program baby." 

Note that using nargs='*' means that args.names now a list, unlike your args.add , so you can add any number of names following add (you will have to change how you handle this argument) . The above can then be called as follows:

 $ python test.py add test '['test']' was added to the list of names. $ python test.py add test1 test2 '['test1', 'test2']' was added to the list of names. 
+1
source share

All Articles