Python3系统出口vs SystemExi公司

2024-05-15 09:37:52 发布

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

Python3新手,在调试时遇到了一个问题。当状态使用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)

编辑

以下操作无效:

^{pr2}$

这将打印完整的输出:

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

所需输出为SystemExit(0):

OK - 1.8% used on /
OK - 35.7% used on /boot

我得到的输出系统出口(0):

OK - 1.8% used on /

Tags: andthekeyformatvalueonsysexit
1条回答
网友
1楼 · 发布于 2024-05-15 09:37:52
SystemExit(0)

这实际上并不存在。它只是构建一个异常对象并将其丢弃。您需要raise SystemExit(0)才能实际退出。在

When the status prints using sys.exit, the output from my print statement gets cut off to one line

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

相关问题 更多 >