You could set the type to float, and nargs=4, and the default to [-2, 2, -2, 2]
, and then run it as python3 testargp.py --rect -2 2 -2 2
. That also prevents a user from missing an argument, since you'll get an error if there are not four numbers.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--rect', type=float, nargs=4,
default=[-2, 2, -2, 2], help='Rectangle in the complex plane.')
args = parser.parse_args()
print(args.rect)
Results:
python3 script.py
[-2, 2, -2, 2]
python3 script.py --rect -12 12 -3 3
[-12.0, 12.0, -3.0, 3.0]
python3 script.py --rect -12 12 -3
usage: script.py [-h] [-r RECT RECT RECT RECT]
script.py: error: argument -r/--rect: expected 4 arguments
An alternative, given in this answer, is to explicitly use the =
sign in case of the long option, and don't use a space in case of the short option:
python3 script.py -r '-2.0:2.0:-2.0:2.0'
usage: script.py [-h] [-r RECT]
script.py: error: argument -r/--rect: expected one argument
python3 script.py -r'-2.0:2.0:-2.0:2.0'
-2.0:2.0:-2.0:2.0
python3 script.py --rect '-2.0:2.0:-2.0:2.0'
usage: script.py [-h] [-r RECT]
script.py: error: argument -r/--rect: expected one argument
python3 script.py --rect='-2.0:2.0:-2.0:2.0'
-2.0:2.0:-2.0:2.0
But this may confuse an unexpected user, since this kind of flexibility with options is used so much, that it's weird to not allow it; especially since the error message doesn't indicate this at all.