Python argparse: How to change `--add` into `add` while still being an optional argument?

允我心安 提交于 2019-12-05 20:32:01

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.

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!