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)
修改
以下不起作用:
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)
这将打印完整输出:
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
输出我在sys.exit(0)中获得:
OK - 1.8% used on /
答案 0 :(得分:3)
SystemExit(0)
实际上并没有退出。它只是构建一个异常对象并抛弃它。您需要raise SystemExit(0)
才能真正退出。
嗯,是的。这是因为您打印了一行然后退出。你为什么要打电话给当使用sys.exit打印状态时,我的print语句的输出被切断为一行
sys.exit
?如果您要设置流程的退出代码,请在实际完成后致电sys.exit
。