我认为这是对另一个答案的更清晰的变体(依赖于self.default
自定义操作的属性):
import argparse
import sys
class Extender(argparse.Action):
def __call__(self,parser,namespace,values,option_strings=None):
#Need None here incase `argparse.SUPPRESS` was supplied for `dest`
dest = getattr(namespace,self.dest,None)
#print dest,self.default,values,option_strings
if(not hasattr(dest,'extend') or dest == self.default):
dest = []
setattr(namespace,self.dest,dest)
#if default isn't set to None, this method might be called
# with the default as `values` for other arguements which
# share this destination.
parser.set_defaults(**{self.dest:None})
try:
dest.extend(values)
except ValueError:
dest.append(values)
#another option:
#if not isinstance(values,basestring):
# dest.extend(values)
#else:
# dest.append(values) #It's a string. Oops.
def new_parser(args):
parser = argparse.ArgumentParser()
parser.add_argument('foo', nargs='*',action=Extender)
parser.add_argument('--foo', nargs='*', dest='foo', action=Extender)
parser.set_defaults(foo = [['spam']])
return parser.parse_args(args.split())
tests = {'a b c --foo 1 --foo 2 --foo 3':['a','b','c','1','2','3'],
'':[['spam']],
'a b c --foo 1 2 3':['a','b','c','1','2','3'],
'--foo 1':['1'],
'a':['a']}
for s,r in tests.items():
print ( "parsing: {0}".format(s) )
args = new_parser(s)
if(args.foo != r):
print ("ERROR")
print (args.foo)
print (r)
sys.exit(1)
print ( args )
print ('*'*80)
另请注意,我曾经parser.set_defaults(...)
为foo
属性设置默认值。