在 for 循环中使用 sys.exit

Using sys.exit in for loops

我正在编写一个小的 python 脚本,它遍历一个大的 json 输出并获取我需要的信息并将其放入小词典中。然后它遍历字典以查找名为 restartcount 的键。如果计数大于 3 但小于 5,则打印 warning。如果大于 5,则打印 critical。然而,这个脚本被设置为一个 nagios 插件,它需要将退出代码与警告一起放置 sys.exit(1),并且 sys.exit(2) 用于严重。如果您查看我的脚本,我会使用我的函数将我需要的信息抓取到一个小字典中,然后 运行 一个 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 变量的样子:

{'phase': u'Running', 'restartcount': 0, 'name': u'pixels-1.0.9-k1v5u'}

创建一个名为 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)

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