I've been looking for solution to add an argument that would behave as action='store_const'
, but would take multiple values.
So that if I don't pass it at all, it should has no value(or some value), if I pass it without value it should has default value, and if I pass it with value(s) it should be a 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 too 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 you want to special case the -a
with no additional arguments, there is no way to do that without using a 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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With