Python argparse: How to change `--add` into `add`

2019-05-10 10:41发布

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 like this:

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."

Such that:

$ 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 still let it be optional yet not have those -- signs? (preferably also using the argparse library)

2条回答
SAY GOODBYE
2楼-- · 2019-05-10 10:54

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.
查看更多
贼婆χ
3楼-- · 2019-05-10 11:04

You could use sub-commands to achieve this behaviour. Try something like 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 the use of nargs='*' means that args.names is now a list, unlike your args.add, so you can add an arbitrary number of names following add (you'll have to modify 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.
查看更多
登录 后发表回答