python3 sys.exit vs SystemExit

2.6k views Asked by At

New to Python 3, and running into an issue I'm having trouble debugging. When the status prints using sys.exit, the output from my print statement gets cut off to one line, but when I use SystemExit it prints all of the output. Can anyone explain this to me please?

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)

EDIT

The following did not work:

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)

This prints the full output:

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

The desired output is with SystemExit(0):

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

The output i'm getting with sys.exit(0):

OK - 1.8% used on /
1

There are 1 answers

0
user2357112 On
SystemExit(0)

That doesn't actually exit. It just builds an exception object and throws it away. You would need to raise SystemExit(0) to actually exit.

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

Well, yeah. That's because you printed one line and then exited. Why are you calling sys.exit at all? If you want to set the process's exit code, call sys.exit once you're actually done.