1

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?
4
  • 1
    Could you be a little more specific? Which OS, which program, which function?
    – Schorsch
    Commented May 16, 2013 at 14:49
  • and how does the user close the program?? Is it GUI?? Please be more specific....
    – IcyFlame
    Commented May 16, 2013 at 15:42
  • @Schorsch Sorry for my poor expression.
    – Hunger
    Commented May 16, 2013 at 15:42
  • 1
    No need to be sorry. Just keep improving your question, by being as precise as possible (look at the questions that are posted in comments here).
    – Schorsch
    Commented May 16, 2013 at 15:45

3 Answers 3

3

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)

0
1

You can use the atexit module to register functions to be executed when the program exits.

0

The simplest way would be to wrap your behavior in a try/finally, with your exit behavior in the finally block.

try:
  normal_behavior()
finally:
  on_exit_behavior()

Not the answer you're looking for? Browse other questions tagged or ask your own question.