使用系统出口在for循环中

2024-05-29 08:04:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个小python脚本,它遍历大型json输出并获取所需的信息并将其放入小词典中。然后它遍历字典来寻找一个名为restartcount的键。如果计数大于3但小于5,则打印warning。如果大于5,则打印critical。但是,这个脚本被设置为一个nagios插件,它需要在退出代码中加上警告sys.exit(1),而{}表示严重。如果你看一下我的脚本,我用我的函数把我需要的信息放到一个小字典里,然后运行一个for循环。如果我在任何If语句后面放一个sys.exit,我只会遍历第一个字典,其余的都不检查。任何帮助将不胜感激,如何合并退出代码,而不丢失跳过或丢失任何信息。在

代码:

import urllib2
import json
import argparse
from sys import exit

def get_content(pod):
    kube = {}
    kube['name'] = pod["metadata"]["name"]
    kube['phase'] = pod["status"]["phase"]
    kube['restartcount'] = pod["status"]["containerStatuses"][0]["restartCount"]
    return kube

if __name__ == '__main__':
    parser = argparse.ArgumentParser( description='Monitor Kubernetes Pods' )
    parser.add_argument('-w', '--warning', type=int, help='levels we should look into',default=3)
    parser.add_argument('-c', '--critical', type=int, help='its gonna explode',default=5)
    parser.add_argument('-p', '--port', type=int, help='port to access api server',default=8080)
    args = parser.parse_args()

try:
    api_call = "http://localhost:{}/api/v1/namespaces/default/pods/".format(args.port)
    req = urllib2.urlopen(api_call).read()
    content = json.loads(req)
except urllib2.URLError:
    print 'URL Error. Please re-check the API call'
    exit(2)


for pods in content.get("items"):
    try:
        block = get_content(pods)
        print block
    except KeyError:
        print 'Container Failed'
        exit(2)

    if block["restartcount"] >= args.warning and block["restartcount"] < args.critical:
        print "WARNING | {} restart count  is {}".format(block["name"], block["restartcount"])

    if block["restartcount"] >= args.critical:
        print "CRITICAL | {} restart count  is {}".format(block["name"], block["restartcount"])

block变量的外观:

^{pr2}$

Tags: nameimport脚本apidefaultparserexitargs
2条回答

变量法是正确的 问题是,当您进一步检查时,可能会将它设置为1,而它已经是2,所以我建议在这里添加一个条件,如果它已经是2,则不要将其设置为1

创建一个名为exit_status的变量。将其初始化为0,并根据需要在代码中设置它(例如,当前调用exit)的位置。在程序执行结束时,调用sys.exit(exit_status)(其他地方不调用)。在

重写代码的最后一部分:

exit_status = 0
for pods in content.get("items"):
    try:
        block = get_content(pods)
        print block
    except KeyError:
        print 'Container Failed'
        exit(2)

    if block["restartcount"] >= args.warning and block["restartcount"] < args.critical:
        print "WARNING | {} restart count  is {}".format(block["name"], block["restartcount"])
        if exit_status < 1: exit_status = 1

    if block["restartcount"] >= args.critical:
        print "CRITICAL | {} restart count  is {}".format(block["name"], block["restartcount"])
        exit_status = 2

sys.exit(exit_status)

相关问题 更多 >

    热门问题