Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do something when terminate a python program

I want make a python script do something such as publishing a message before terminating it. I have tried signal and it works when I input Ctrl+c in cmd window. However, it seems inoperative when I just directly close cmd window or kill the process from Windows task manager. So how can I reach my goal in the condition of above situation? Thanks for all suggestions!

like image 389
Da Vinci Avatar asked Mar 09 '17 13:03

Da Vinci


People also ask

What does exit () do in Python?

exit() method is used to terminate the process with the specified status. We can use this method without flushing buffers or calling any cleanup handlers. After writing the above code (python os. exit() function), the output will appear as a “ 0 1 2 “.


1 Answers

Take a look at the atexit module:

http://docs.python.org/library/atexit.html

Example:

import atexit

def exit_handler():
    print('My program just quit')

atexit.register(exit_handler)
like image 125
Eric Avatar answered Sep 29 '22 07:09

Eric