0

I'm setting up argparser in python 3.6 and I need one of my arguments which defines range in the 2D plane to be in the format '-2.0:2.0:-1.0:1.0'.

Which I tried to define as follows:

parser = argparse.ArgumentParser()  
parser.add_argument('-r', '--rect', type=str, default='-2.0:2.0:-2.0:2.0', help='Rectangle in the complex plane.')
args = parser.parse_args()

xStart, xEnd, yStart, yEnd = args.rect.split(':')

unfortunately this results in error: argument -r/--rect: expected one argument after

python3 script.py --rect "-2.0:2.0:-2.0:2.0"

I'm looking for a way to get the 4 double numbers.

Zarrie
  • 325
  • 2
  • 16
  • Possible duplicate of [Python Argparse: Issue with optional arguments which are negative numbers](https://stackoverflow.com/questions/9025204/python-argparse-issue-with-optional-arguments-which-are-negative-numbers) – 9769953 May 06 '19 at 10:24
  • Neither the shell or `argparse` uses the `:` delimiter. `-2.0:...` is just a string that starts with a dash. But dash is used by `argparse` to indicate a flag, so it's not recognized as argument for `--rect`. Not being able to use a string that starts with a dash as argument is a long standing issue. – hpaulj May 06 '19 at 15:59

1 Answers1

2

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.

9769953
  • 10,344
  • 3
  • 26
  • 37