0

I'm trying to utilize argparse for a scale-able solution for SNMP (Nagios).

The issue i'm running into is trying to have constants and vars be passed along through the add_argument()

example :

./SNMP.py -j 10 20 -l

-j would store the str ".1.5.5.8" the arguments after would set the warn integer level and the critical integer level bypassing the defaults set in parser.add_argument()

-l would store a different OID str but would use the default warn and critical levels stored in parser.add_argument()

Thanks!

In short the code i have to get around this dilemma :

parser = argparse.ArgumentParser(description = "This is used to parse latency, jitter, and packet loss on an HDX")

parser.add_argument("-j", action = 'append', dest = 'jitter',
 default = [".2.51.5.9.4","20 40"])

args = parser.parse_args()

warn, crit = args.jitter[-1].split()
  • I was going to write a long post to try and help, but I think maybe this would be more helpful: http://stackoverflow.com/questions/36166225/using-the-same-option-multiple-times-in-pythons-argparse – Nagios Support Jan 11 '17 at 17:23
  • What argparse code have you tried so far? It's easier to suggest fixes for an existing parser than to write one from scratch based on your written description. – hpaulj Jan 11 '17 at 18:45
  • I have updated the post. thanks – Adam Bruneau Jan 11 '17 at 20:05

1 Answers1

0
In [16]: parser=argparse.ArgumentParser()
In [17]: parser.add_argument("-j", action = 'append', dest = 'jitter',
    ...:  default = [".2.51.5.9.4","20 40"])
Out[17]: _AppendAction(option_strings=['-j'], dest='jitter', nargs=None, const=None, default=['.2.51.5.9.4', '20 40'], type=None, choices=None, help=None, metavar=None)

In [18]: parser.parse_args([])
Out[18]: Namespace(jitter=['.2.51.5.9.4', '20 40'])
In [19]: parser.parse_args(['-j','1'])
Out[19]: Namespace(jitter=['.2.51.5.9.4', '20 40', '1'])

So the append action puts the default in the Namespace, and appends any values supplied with -j to that list. Also -j may be repeated, adding more values.

Some people think this an error and that values should be appended to [], and the default should only appear with -j is not used at all. The current behavior is simple and predicable.

An alternative is to leave the default as None or [], and add the default values yourself after parsing if args.jitter is None:

In [22]: parser.add_argument("-j", action = 'append', dest = 'jitter', nargs=2)
Out[22]: _AppendAction(option_strings=['-j'], dest='jitter', nargs=2, const=None, default=None, type=None, choices=None, help=None, metavar=None)
In [23]: parser.parse_args([])
Out[23]: Namespace(jitter=None)
In [24]: parser.parse_args(['-j','20','40'])
Out[24]: Namespace(jitter=[['20', '40']])

So testing would be something like:

if args.jitter is None:
   args.jitter= [...]

I added nargs to show that what gets appended is a sublist.

See http://bugs.python.org/issue16399 for more discussion of append with defaults.

hpaulj
  • 221,503
  • 14
  • 230
  • 353