Python argparse: combine multiple-value argument with default and const -
i've been looking solution add argument behave action='store_const'
, take multiple values.
so if don't pass @ all, should has no value(or value), if pass without value should has default value, , if pass value(s) should list of these values.
e.g.
parser.parse_args(''.split()) parser.parse_args('-a'.split()) parser.parse_args('-a 1 2 3'.split())
should result in
[none] [0] [1, 2, 3]
not hard:
parser = argparse.argumentparser() parser.add_argument('-a',default=[none],action='store',type=int,nargs='*') print parser.parse_args(''.split()) print parser.parse_args('-a'.split()) print parser.parse_args('-a 1 2 3'.split())
if want special case -a
no additional arguments, there no way without using custom action:
import argparse class myaction(argparse.action): def __call__(self,parser,namespace,values,option_string=none): if not values: setattr(namespace,self.dest,[0]) else: setattr(namespace,self.dest,values) parser = argparse.argumentparser() parser.add_argument('-a',default=[none],action=myaction,type=int,nargs='*') print parser.parse_args(''.split()) print parser.parse_args('-a'.split()) print parser.parse_args('-a 1 2 3'.split())
Comments
Post a Comment