A slightly more complex solution is to define a function for the type
attribute and a class extending argparse._AppendAction
. The idea of this class is to 'flatten' internally the argument list. This is a job that can also be done after parsing (in this case, no need to extend the class).
import argparse
import re
class newAppendAction(argparse._AppendAction):
def __call__(self, parser, namespace, values, option_string=None):
items = getattr(namespace, self.dest, None)
items = argparse._copy_items(items)
for value in values:
if type(value) is list:
for item in value:
items.append(item)
else:
items.append(value)
setattr(namespace, self.dest, items)
def type_lambda(value):
return [v for v in re.split("\-|\,", value) if len(v) > 0]
We can then simply declare the argument of the parser:
parser = argparse.ArgumentParser(description='RANGES')
parser.add_argument('IP_Address', nargs='+', action=newAppendAction, type=type_lambda)
And test the result:
>>> s3 = "python3 main.py 1.1.1.1-2.2.2.2"
>>> print(parser.parse_args(s1.split(" ")[2:]))
Namespace(IP_Address=['1.1.1.1'])
>>> s2 = "python3 main.py 1.1.1.1, 2.2.2.2"
>>> print(parser.parse_args(s2.split(" ")[2:]))
Namespace(IP_Address=['1.1.1.1', '2.2.2.2'])
>>> s1 = "python3 main.py 1.1.1.1"
>>> print(parser.parse_args(s3.split(" ")[2:]))
Namespace(IP_Address=['1.1.1.1', '2.2.2.2'])