【发布时间】:2016-12-15 03:06:54
【问题描述】:
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 /
【问题讨论】:
-
尝试使用
print('message', file=sys.stderr)。这有什么改变吗?这可能与stdout将被缓冲并且不一定立即写入这一事实有关。或者在退出前添加sys.stdout.flush()。但是为什么你首先使用sys.exit(0),而不是使用break并让它退出循环然后正常退出脚本。 -
你应该使用
print(thing, flush=True) -
感谢您的回答,我正在使用 sys.exit(0) 来捕获特定的退出代码,以便 nagios 获取它。我现在将尝试这些建议并报告回来。编辑这不起作用:elif value 0: print("{0} {1}% used on {2}".format(o,value,key)) sys.stdout.flush() sys.退出(0)
-
我已添加:print("{0} {1}% used on {2}".format(o,value,key), file=sys.stderr) print("{0 } {1}% 用于 {2}".format(o,value,key), flush=True) 和 print 和 sys.exit(0) 之间的 sys.stdout.flush() 这些都不起作用
-
将这些添加到您的问题中,以便问题和您尝试过的事情更加清晰。
标签: python python-3.x nagios