python - 有没有办法在 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 个双数。
解决方案
您可以将类型设置为 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
但这可能会让一个意想不到的用户感到困惑,因为这种带有选项的灵活性被使用得太多了,不允许它是很奇怪的;特别是因为错误消息根本没有表明这一点。
推荐阅读
- wpf - Android WCF 客户端在 2 次调用后停止响应
- python - 用于预测未来环境状态的路径核算的寻路算法
- c++ - 为什么 C++ 已弃用的警告会打印两次?
- java - 如何捕获图像并通过电子邮件将其 Uri 直接发送到附件
- reactjs - 导入graphql文件时清理创建React App的缓存
- node.js - 加快文件加载速度
- angular - Angular 4:如果页面有多个选项卡,则 Angular 的最佳实践
- c++ - 我不能在 C++ 的头文件中的类中使用 ofstream 对象
- javascript - 在浏览器的 URL 中反射并发出 Axios 请求
- java - 如何在rabbbitmq中配置队列的消费者来监听一种以上数据类型的消息?