Search code examples
pythoneclipsepydevdel

Eclipse+Pydev: "cleanup" functions aren't called when pressing "stop""?


Trying to run this file in eclipse

class Try:
   def __init__(self):
       pass
   def __del__(self):
       print 1
a=Try()
raw_input('waiting to finish')

and pressing the stop button without letting the program finish doesn't print "1", i.e the del method is never called. If i try to run the script from the shell and do ctrl-c\sys.exit "1" does get printed i.e del is called. Same thing if I try to use wait():

class A:

    def __enter__(self):
        return None
    def __exit__(self, type, value, traceback):
        print 3


with A():
    print 1
    raw_input('Waiting')
    print 2

If i press "stop" when prompted, "3" isn't printed

Why is that? Is there a way around it?

Thanks, Noam


Solution

  • Pressing stop in Eclipse outright kills the interpreter (though it actually fails fairly often). Like using kill/taskkill, the process is unaware of it's demise.

    Ctrl+C snippet from Wikipedia...

    Control-C as an abort command was popularized by UNIX and adopted in other systems. In POSIX systems, the sequence causes the active program to receive a SIGINT signal. If the program does not specify how to handle this condition, it is terminated. Typically a program which does handle a SIGINT will still terminate itself, or at least terminate the task running inside it.

    Ctrl+C is a control signal to interrupt the program, but as you may have noticed in the middle of that paragraph, programs can specify how to handle the signal. In Python, Ctrl+C throws a KeyboardInterrupt exception which is normally caught and then Python exits cleanly. Even if you're killing the interpreter with Ctrl+C it may handle it so that it cleans the environment before exiting.

    I included the following because you asked "Is there a way around it?"

    If you are wanting to stop on raw_input(...) calls, you could use Ctrl+Z to send EOF. I looked around, and there seems to be no way to send Ctrl+C/0x03 in Eclipse, unfortunately.