Search code examples
pythonargparse

How to support List/Range of arguments in argparse?


In python I have:

parser = argparse.ArgumentParser(description='RANGES')
parser.add_argument('IP_Address', action='store', type=str)

How can I let the user provide a single IP adresses or range or separate data?

for example I want to support:

python3 main.py 1.1.1.1
python3 main.py 1.1.1.1, 2.2.2.2
python3 main.py 1.1.1.1-2.2.2.2

Where the first iterates over 1.1.1.1 only, the second iterates over 1.1.1.1 and 2.2.2.2. While the latter iterates over all ips in the specified range.


Solution

  • You could try something like this:

    parser.add_argument('IP_Address', nargs='+', action='store', type=str)
    

    This would only solve your first question.

    nargs='*' might also be possible although does not seem like it from your use case

    For the second, you need to specify the rules of the range creation.