使参数解析器接受绝对数字和百分比的最佳方法? [英] 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屋!