我有一个在后台运行的Python进程,我希望它只在脚本终止时生成一些输出。
def handle_exit():
print('\nAll files saved in ' + directory)
generate_output()
atexit.register(handle_exit)
调用引发KeyboardInterupt
异常和sys.exit()
正确地调用handle_exit()
,但如果我从终端执行kill {PID}
则会在不调用handle_exit()的情况下终止脚本。
有没有一种方法可以终止在后台运行的进程,并在终止之前运行handle_exit()
?