0

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)

1

1 Answer 1

1

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'])
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! I overlooked the 'action' keyword argument. So the solution for me is parser.add_argument('-i', action='append'). Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.