Anyone has any idea how to get my destructor called on object destruction?
def __del__(self):
os.unlink(self.pidfile)
Scenario: There is a Daemon that runs Process. Daemon gets a SIGTERM, and immediately sends a SIGTERM to Process. Process stops execution without __del__
called.
As referenced in the comments, defining an __exit__
method for your object and using the with statement is the preferred way of "destructing" objects. It's more explicit and predictable.
However, even using the with
statement won't guarantee clean destruction of your object if a SIGTERM is received. In order to do something when a signal is received, you'll have to add a signal handler.
import signal
import sys
def handle_signal(signum, frame):
print('Got signal')
# Do some cleanup
sys.exit(signum) # Maybe ???
signal.signal(signal.SIGTERM, handle_signal)
At this point, you might consider calling del your_object
in the signal handler, but even that is not guaranteed to call the __del__
method if there are still references to that object in the program (see the docs for __del__)
So bottom line I think is not to expect things to go absolutely smoothly and predictably if you're depending on SIGTERM to close your Python programs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With