user1476056
user1476056

Reputation: 257

Python: Object destruction upon terminal close

I need to create a code that would be flexible enough to perform some required cleanups even if the terminal where it was running is closed or SSH connection is lost. I have all the necessary code wrapped into one class' __del__ method. However, Python doesn't seem to be calling it (unlike C++) on exit. I tried [atexit][1] but it wasn't called either.

Any suggestions will be appreciated.

Upvotes: 0

Views: 287

Answers (1)

John Lyon
John Lyon

Reputation: 11430

You need to use the signal module. SIGHUP should be sent to your program on either closing the terminal window or losing the SSH connection. You could catch SIGINT instead of SIGHUP but this is a catch-all solution.

import signal
import sys
def signal_handler(signal, frame):
    print 'Handling SIGHUP signal!'
    sys.exit(0)
signal.signal(signal.SIGHUHP, signal_handler)
print 'Waiting for SIGHUP'
signal.pause()

You can test this by issuing sudo kill -1 <pid of your python process> in another terminal window.

Upvotes: 2

Related Questions