当python进程被杀死时运行atexit() [英] Run atexit() when python process is killed
问题描述
我有一个在后台运行的python进程,我希望它仅在脚本终止时才生成一些输出.
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)
调用引发KeyboardInterupt
异常,然后sys.exit()
正确调用handle_exit()
,但是如果我要从终端执行kill {PID}
,它将终止脚本而无需调用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().
有没有办法终止在后台运行的进程,并且仍然在终止前运行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?
推荐答案
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)
现在您可以执行kill {pid}
,并且handle_exit
将被执行.
Now you can kill {pid}
and handle_exit
will be executed.
这篇关于当python进程被杀死时运行atexit()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!