使参数解析器接受绝对数字和百分比的最佳方法? [英] Best way to make argument parser accept absolute number and percentage?
问题描述
我正在尝试编写 Nagios 样式检查以与 Nagios 一起使用.我有工作脚本,它接受类似 -w 15 -c 10
的内容,并将其解释为15% 时警告,10% 时严重".但我刚刚意识到,在内置的 Nagios 插件中,相同的参数意味着警告为 15MB,严重为 10MB";我需要输入 -w 15% -c 10%
以获得上述行为.
I am trying to write a Nagios style check to use with Nagios. I have working script that takes in something like -w 15 -c 10
and interprets that as "Warning at 15%, Critical at 10%". But I just realized that in the built-in Nagios plugins, the same arguments would mean "Warning at 15MB, Critical at 10MB"; I would instead need to enter -w 15% -c 10%
to get the above behavior.
所以我的问题是,让我的脚本表现得像内置 Nagios 脚本的最佳方法是什么?我能想到的唯一方法是将参数作为字符串接受并解析它,但有没有更简洁的方法?
So my question is, what is the best way to make my script behave like the built-in Nagios scripts? The only way I can think of is accepting the argument as a string and parsing it, but is there a neater way?
推荐答案
您可以使用自己的类作为参数的类型:
You can use your own class as type for the arguments:
import argparse
class Percent(object):
def __new__(self, percent_string):
if not percent_string.endswith('%'):
raise ValueError('Need percent got {}'.format(percent_string))
value = float(percent_string[:-1]) * 0.01
return value
parser = argparse.ArgumentParser(description="with percent")
parser.add_argument('-w', '--warning', type=Percent)
parser.add_argument('-c', '--critcal', type=Percent)
args = parser.parse_args()
print(args.warning)
输出:
python parse_percent.py -w 15%
0.15
python parse_percent.py -w 15
usage: parse-percent.py [-h] [-w WARNING] [-c CRITCAL]
parse-percent.py: error: argument -w/--warning: invalid Percent value: '15'
使用百分比或 MB 的版本
class Percent(object):
def __new__(self, percent_string):
if percent_string.endswith('%'):
return float(percent_string[:-1]), 'percent'
else:
return float(percent_string), 'MB'
parser = argparse.ArgumentParser(description="with percent")
parser.add_argument('-w', '--warning', type=Percent)
parser.add_argument('-c', '--critcal', type=Percent)
args = parser.parse_args()
value, unit = args.warning
print('{} {}'.format(value, unit))
输出:
python parse_percent.py -w 15
15.0 MB
python parse_percent.py -w 15%
15.0 percent
这篇关于使参数解析器接受绝对数字和百分比的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!