3

我想要这个功能:

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

我可以用--add而不是add这样来实现这一点:

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

这样:

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

但是当我改成--addadd不再是可选的时候,我怎么还能让它是可选的却没有那些--标志呢?(最好也使用argparse图书馆)

4

2 回答 2

2

您想要的实际上称为“位置参数”。你可以像这样解析它们:

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

这使您能够指定不同的操作:

$ 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.
于 2012-08-08T09:53:27.577 回答
1

您可以使用子命令来实现此行为。尝试以下内容

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.
于 2012-08-08T09:53:53.627 回答