Search code examples
python

Executing a function when the console window closes?


I want to execute a function when the program is closed by user.

For example, if the main program is time.sleep(1000),how can I write a txt to record unexpected termination of the program.

The program is packaged into exe by cxfreeze. Click the "X" to close the console window.

I know atexit can deal with sys.exit(),but is there a more powerful way can deal with close window event?

Questions

  1. Is this possible in Python?
  2. If so, how can I do this?

Solution

  • The closest you will get is using an exit handler:

    def bye():
        print('goodbye world!!')
    
    import atexit
    atexit.register(bye)
    

    This may not work depending on technical details of how python is terminated (it relies on normal interpreter termination)