I am using the argparse library (https://docs.python.org/3/library/argparse.html) to parse arguments for a Python3 script. I would like to be able to specify a particular argument multiple times. For example:
$ myscript -i host1 -i host2
Using parser.add_argument('-i', nargs='*') allows multiple argument with -i. For example:
$ myscript -i host1 host2
However, I want multiple occurrences of -i. Is this possible? Right now a second use of the argument overwrites the first (in my initial example only 'host2' would be passed)
From the documentation, if you use action="append"
, it seems to do what you want.
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])