简体   繁体   中英

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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM