I am working on a custom Nagios script in which I would like to implement parsing of command line arguments in the same way that is used on existing Nagios Plugin check_disk
.
In that plugin you have an option parameter -C
to Clear
current config and start over with new parameters.
Extracted from check_disk
help:
check_disk -w 100 -c 50 -C -w 1000 -c 500 -p /foo -C -w 5% -c 3% -p /bar
----(3)----- ---------(1)---------- --------(2)--------
Checks warning/critical thresholds:
- for volume
/foo
use 1000M and 500M as thresholds - for volume
/bar
use 5% and 3% - All remaining volumes use 100M and 50M
I have tried with argparse
and some parameter as action='append'
but repeated arguments are stored in a list and missing ones are not includes as a "None" entry.
I have also tried with parse_known_args
hoping to stop parsing on first unknown argument, but I get a namespace with all known arguments and a list of unknown arguments.
I guess that my only option is using regular expressions before parsing the command line arguments.
import re
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('-w', help='warning')
parser.add_argument('-c', help='critical')
parser.add_argument('-p', help='path')
separator=r'-S'
groups = re.split(separator, '|'.join(sys.argv[1:])))
args = []
for idx, group_args in enumerate(groups):
args.append('')
args[idx]=parser.parse_args(group_args.split('|'))
I do not know if argparse
can handle this kind of scenario without need to split using regular expressions.
Or if this is the best approach I can find.
This is not related with Using the same option multiple times in Python's argparse because it is not the same case, I have different optional argument not just one option with multiple values.
In example above (3) have not got option -p
, (1) and (2) have it. That is one of the difference and one of the problems. If all options were mandatory, it was easy.