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!
Asked
Active
Viewed 308 times
5

Da Vinci
- 51
- 2
-
I also have tried `atexit`, but it doesn't meet my need. – Da Vinci Mar 10 '17 at 01:25
1 Answers
5
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)

Jean-François Fabre
- 137,073
- 23
- 153
- 219

Eric
- 159
- 2
- 11
-
Thanks for your help. I have a try according to your method, however, it's a pity that it doesn't work when I simply close the cmd window or click 'stop' in Pycharm where the python script is running. It works when I input `Ctrl+C` in cmd just like using `signal` method. – Da Vinci Mar 10 '17 at 01:23