python3 sys.exit 与 SystemExit

1 python nagios python-3.x

Python 3 的新手,遇到了调试时遇到的问题。当使用 打印状态时sys.exit,我的语句的输出print被截断为一行,但是当我使用它时SystemExit,它会打印所有输出。有人可以向我解释一下吗?

import psutil
import sys

def mountpoint():
    output = psutil.disk_partitions(all=False)
    marray = []
    #create a list from the disk partitions function
    for fs in output:
        marray.append(fs.mountpoint)
    return marray

def usage():
    uarray = {}
    for i in mountpoint():
        #create a dictionary with mountpoint as the key and the usage percentage as the value
        uarray[i] = psutil.disk_usage(i).percent
    return uarray

diskUsage = usage()

#Icinga errors
s = "SEVERE -"
c = "CRITICAL -"
w = "WARNING -"
o = "OK -"
u = "UNKNOWN -"

for key, value in diskUsage.items():
    if value == 100:
        print("{0} {1}% used on {2}".format(s,value,key))
        sys.exit(2)
    elif value >= 95 and value < 100:
        print("{0} {1}% used on {2}".format(c,value,key))
        sys.exit(2)
    elif value >= 92 and value < 95:
        print("{0} {1}% used on {2}".format(w,value,key))
        sys.exit(1)
    elif value < 92 and value > 0:
        print("{0} {1}% used on {2}".format(o,value,key))
        sys.exit(0)
    else:
        print("UNKNOWN - Unable to pull file-system usage or a non int value was stored")
        sys.exit(3)
Run Code Online (Sandbox Code Playgroud)

编辑

以下内容无效:

elif value < 92 and value > 0:
        print("{0} {1}% used on {2}".format(o,value,key))
        sys.stdout.flush()
        sys.exit(0)

elif value < 92 and value > 0:
        print("{0} {1}% used on {2}".format(o,value,key), file=sys.stderr)
        sys.exit(0)

elif value < 92 and value > 0:
            print("{0} {1}% used on {2}".format(o,value,key), flush=True)
            sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

这将打印完整的输出:

elif value < 92 and value > 0:
            print("{0} {1}% used on {2}".format(o,value,key))
            SystemExit(0)
Run Code Online (Sandbox Code Playgroud)

所需的输出是 SystemExit(0):

OK - 1.8% used on /
OK - 35.7% used on /boot
Run Code Online (Sandbox Code Playgroud)

我通过 sys.exit(0) 得到的输出:

OK - 1.8% used on /
Run Code Online (Sandbox Code Playgroud)

use*_*ica 5

SystemExit(0)
Run Code Online (Sandbox Code Playgroud)

那实际上并没有退出。它只是构建一个异常对象并将其丢弃。您需要raise SystemExit(0)实际退出。

当使用 sys.exit 打印状态时,我的打印语句的输出被截断为一行

嗯,是的。那是因为你打印了一行然后退出了。你为什么打电话sys.exit来?如果您想设置进程的退出代码,请sys.exit在实际完成后调用。