我有一个字典如下(dict命名为channel_info):
{'flume02': u'98.94420000000001', 'flume03': u'32.562999999999995', 'flume01': u'2.15'}
我试图遍历字典并报告值警告或严重。我必须参与该计划
parser.add_argument('-w', '--warning', type=int, help='Warning threshold', default=85)
parser.add_argument('-c', '--critical', type=int, help='Critical threshold', default=95)
所以基本上当我运行像myprog.py -w 80 -c 90
这样的程序时,我想要
flume02是关键的(在这种情况下,这将是唯一的输出)。如果任何其他密钥的值大于80或90,则它们将分别报告为警告或关键。
然而情况并非如此,我将所有值都置于关键状态。
相关代码:
if args.warning and not args.critical:
for each in channel_info.items():
if float(each[1]) > float(args.warning):
print 'WARNING | {} is {} percent full'.format(*each)
exit(1)
if args.critical and not args.warning:
for each in channel_info.items():
if float(each[1]) > float(args.critical):
print 'CRITICAL | {} is {} percent full'.format(*each)
exit(2)
if args.warning and args.critical:
for each in channel_info.items():
if float(args.warning) < each[1] < float(args.critical):
print 'WARNING | {} is {} percent full'.format(*each)
elif each[1] > float(args.critical):
print 'CRITICAL | {} is {} percent full'.format(*each)
输出:
CRITICAL | flume02 is 99.9892 percent full
CRITICAL | flume03 is 51.4497 percent full
CRITICAL | flume01 is 7.95 percent full
如果最后一个if条件(if args.warning and args.critical
)放置,那么为了确保程序能够使用1(-w
或-c
)或两个参数运行。任何有关我做错的帮助将不胜感激
答案 0 :(得分:1)
我想你忘了分支#3上的 float (每个[1])。即将字符串与浮点数进行比较。
更有理由将比较值格式化一次,而不是每次都进行浮点运算(xyz)。
threshold_crit = 90.0
threshold_warn = 80.0
for each in channel_info.items():
# value = float(each[1])
value = each[1]
if threshold_crit < value < threshold_warn:
print 'WARNING | {} is {} percent full'.format(*each)
elif value > threshold_crit:
print 'CRITICAL | {} is {} percent full'.format(*each)
输出:
CRITICAL | flume02 is 98.94420000000001 percent full
CRITICAL | flume03 is 32.562999999999995 percent full
CRITICAL | flume01 is 2.15 percent full
将代码更改为:
value = float(each[1])
#value = each[1]
输出:
CRITICAL | flume02 is 98.94420000000001 percent full
答案 1 :(得分:0)
解决了它。原来有两个问题
-c
不能单独工作的主要问题是这两个参数都有默认值,当我只使用-c
时,第一个if语句正在执行(因为有一个值)并且它相当于真)并且所有值都被标记为警告