I have an optional argument that supports a list of arguments itself.
I mean, it should support:
but not:
Is there a way to force this within argparse ? Now I'm using nargs="*", and then checking the list length.
Edit: As requested, what I needed is being able to define a range of acceptable number of arguments. I mean, saying (in the example) 2 or 3 args is right, but not 1 or 4 or anything that's not inside the range 2..3
Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.
You could do this with a custom action:
import argparse def required_length(nmin,nmax): class RequiredLength(argparse.Action): def __call__(self, parser, args, values, option_string=None): if not nmin<=len(values)<=nmax: msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format( f=self.dest,nmin=nmin,nmax=nmax) raise argparse.ArgumentTypeError(msg) setattr(args, self.dest, values) return RequiredLength parser=argparse.ArgumentParser(prog='PROG') parser.add_argument('-f', nargs='+', action=required_length(2,3)) args=parser.parse_args('-f 1 2 3'.split()) print(args.f) # ['1', '2', '3'] try: args=parser.parse_args('-f 1 2 3 4'.split()) print(args) except argparse.ArgumentTypeError as err: print(err) # argument "f" requires between 2 and 3 arguments
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