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.
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 argparseclass 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.01return valueparser = 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)
Output:
python parse_percent.py -w 15%
0.15python 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'
Version that works with percent or 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))
Output:
python parse_percent.py -w 15
15.0 MB
python parse_percent.py -w 15%
15.0 percent