Run atexit() when python process is killed

和自甴很熟 提交于 2019-12-09 17:33:10

问题


I have a python process which runs in background, and I would like it to generate some output only when the script is terminated.

def handle_exit():
    print('\nAll files saved in ' + directory)
    generate_output()

atexit.register(handle_exit)

Calling raising a KeyboardInterupt exception and sys.exit() calls handle_exit() properly, but if I were to do kill {PID} from the terminal it terminates the script without calling handle_exit().

Is there a way to terminate the process that is running in the background, and still have it run handle_exit() before terminating?


回答1:


Try signal.signal. It allows to catch any system signal:

import signal

def handle_exit():
    print('\nAll files saved in ' + directory)
    generate_output()

atexit.register(handle_exit)
signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)

Now you can kill {pid} and handle_exit will be executed.



来源:https://stackoverflow.com/questions/40866576/run-atexit-when-python-process-is-killed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!