有没有办法在 python 的参数解析中设置分隔符?



我在python 3.6中设置了argparser,我需要我的一个参数,该参数定义2D平面的范围为格式'-2.0:2.0:-1.0:-1.0:1.0:1.0:1.0''。

我试图定义如下:

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(':')

不幸的是这导致 error: argument -r/--rect: expected one argument

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

我正在寻找一种获得4个双数的方法。

您可以将类型设置为float,而nargs = 4,默认值为 [-2, 2, -2, 2],然后以 python3 testargp.py --rect -2 2 -2 2运行。这也阻止用户丢失参数,因为如果没有四个数字,您会遇到错误。

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)

结果:

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

在此答案中给出的一种替代方案是在长期选项中明确使用=符号,并且在短选项的情况下不要使用空间:

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

,但这可能会使意外的用户感到困惑,因为使用这种灵活性是如此之多,以至于不允许使用它很奇怪。特别是由于错误消息根本没有表示这一点。

最新更新