0

I'd like to do a clean shutdown of a class that does one task when exiting normally, and not under something like exit(1). How can I determine the current exit code. Example:

import sys
import atexit

def myexit():
    print("atexit")
atexit.register(myexit)

class Test(object):
    def __init(self):
        pass
    def __del__(self):
        print("here")
        # print(sys.exit_code) # How do I get this???

x = Test()
exit(1)

which produces:

atexit
here

But in neither of those places do I know how to get the exit code passed to sys.exit().

There was other answer but it doesn't seem wise to implement a forced wrapper from another reusable module.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Wes Hardaker
  • 21,735
  • 2
  • 38
  • 69
  • 4
    Don't use `__del__`. There's no guarantee that it'll be called. – Aran-Fey Sep 13 '18 at 16:35
  • 1
    Also there's no guarantee that Python is shutting down at all when `__del__` is called. – user2357112 Sep 13 '18 at 16:36
  • 1
    Instead of trying to detect an exit on failure, why not use a context manager that detects uncaught exceptions (which includes `SystemExit`)? – jwodder Sep 13 '18 at 16:36
  • Well, my solution may indeed not be the best. But the goal is that any time a module with an open file handle gets released/destroyed/whatever it writes a final line to the file. *except* when something like exit(1) is called, which is clearly an error case. So the reality is that __del__ likely is the right place under most condititions but I functionally *don't* want it to get called during exit(1) scenarios. – Wes Hardaker Sep 13 '18 at 17:39

0 Answers0