首页 > 解决方案 > 有没有办法在 python 的 argparse 中设置分隔符?

问题描述

我在 python 3.6 中设置了 argparser,我需要我的参数之一,它定义了 2D 平面中的范围,格式为“-2.0:2.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 个双数。

标签: pythonargparse

解决方案


您可以将类型设置为 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

但这可能会让一个意想不到的用户感到困惑,因为这种带有选项的灵活性被使用得太多了,不允许它是很奇怪的;特别是因为错误消息根本没有表明这一点。


推荐阅读