Make registered atexit function according to exit status
import atexit
import sys
@atexit.register
def goodbye():
print "Good Bye"
print "Hello World"
#sys.exit(0) or sys.exit(1)
The above code Good Bye
is executed every time it exits. Can I print a different message depending on the exit status? Something like, if the exit status is 1, printFATAL: Good Bye
I checked too sys.exitfunc
, but this doesn't support this either? Isn't this something basic to maintain, or is there something better to use in such cases. Is using a wrapper function to exit my program the only way?
source to share
You can easily decapitate sys.exit
:
>>> import sys
>>> sys.my_exit = sys.exit
>>> def func(status):
... if status:
... print "Fatal!"
... sys.my_exit(status)
...
>>> sys.exit = func
>>> sys.exit(1)
Fatal!
Of course, this only works if it is sys.exit
actually called somewhere inside the code ...
You can alternatively wrap your main function in try / except:
import sys
def main():
pass
sys.exit(2) #comment this out, or change the exit status to 0 to test.
try:
main()
except SystemExit as e:
if e.args[0]: #non-zero exit status
print "Failed"
else:
print "Success"
raise
else:
print "Success"
source to share