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.

4
  • 4
    Don't use __del__. There's no guarantee that it'll be called. Commented Sep 13, 2018 at 16:35
  • 1
    Also there's no guarantee that Python is shutting down at all when __del__ is called. Commented Sep 13, 2018 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)? Commented Sep 13, 2018 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. Commented Sep 13, 2018 at 17:39

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.