Python检测杀死请求 [英] Python detect kill request
问题描述
我有一个python 3脚本,它在启动时运行.而且它可以处理一些我希望在退出时免费的资源.
I have a python 3 script and it runs on boot. And it work with some resources I want it free on exit.
如果我用kill -6 $PID
杀死该脚本,如何管理该脚本将退出.
How can I manage that script is going to exit if I'm killing it with kill -6 $PID
.
有关如何发送出口命令并在脚本中检测出口命令的其他想法.
Or any other ideas about how to send exit command and detect it in script.
推荐答案
信号模块就是您要寻找的. p>
The signal module is what you are looking for.
import signal
def handler(signum, frame):
print('Signal handler called with signal', signum)
signal.signal(signal.SIGABRT, handler)
在处理函数中,您可以以sys.exit()
结尾.
Within the handler function you could terminate with sys.exit()
.
但是,更常见的是使用SIGINT(在终端中按CTRL + C时会发生这种情况)或SIGTERM终止程序.如果您没有清理代码,则无需编写任何代码来处理SIGINT-默认情况下,它会引发 KeyboardInterrupt 异常,如果未捕获,则为异常(这就是您应该这样做的原因永远不要使用空白的except:
语句),导致您的程序终止.
However, it is more common to use SIGINT (that's what happens when you press CTRL+C in the terminal) or SIGTERM to terminate a program. If you don't have cleanup code you don't need to write a single line of code to handle SIGINT - by default it raises a KeyboardInterrupt exception which, if not caught (that's a reason why you should never use blank except:
statements), causes your program to terminate.
这篇关于Python检测杀死请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!