Python - 捕获所有信号
在Linux下的python 2.6中,我可以使用以下命令来处理TERM信号:
import signal
def handleSigTERM():
shutdown()
signal.signal(signal.SIGTERM, handleSigTERM)
除了一次设置一个信号之外,还有什么方法可以为进程接收到的所有信号设置处理程序?
In python 2.6 under Linux, I can use the following to handle a TERM signal:
import signal
def handleSigTERM():
shutdown()
signal.signal(signal.SIGTERM, handleSigTERM)
Is there any way to setup a handler for all signals received by the process, other than just setting them up one-at-a-time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
适用于 Windows 10 和 Python 3.7:
结果:
Works on Windows 10 and Python 3.7:
Results:
这是一种 2/3 兼容的方法,它不像其他方法那样有那么多陷阱:
由于
signalnum
只是一个数字,因此迭代 1 到超出范围,将信号设置为特定句柄。Here's a 2/3 compatible way which doesn't have as many pitfalls as the others:
Since
signalnum
is just a number, iterate over 1 to out of range setting the signal to a particular handle.在Python3.8中,我们有了一个新函数
signal.valid_signals()
https://docs.python.org/3/library/signal.html#signal.valid_signalsIn Python3.8 we've got a new function
signal.valid_signals()
https://docs.python.org/3/library/signal.html#signal.valid_signals对于Python 3:
For Python 3:
该代码在当前版本的 python 中不起作用。有许多以 SIG 开头且具有相同值的变量。例如,SIGHUP 和 SIG_UNBLOCK 都是 1。我能想到的获取实际信号列表的唯一方法就是自己制作。
That code won't work in the current version of python. There are many variables starting with SIG with the same value. For instance, SIGHUP and SIG_UNBLOCK are both 1. The only way I could think of to get a list of actual signals was to just make it myself.
从 Python 3.5 开始,信号常量定义为枚举 ,实现更好的方法:
As of Python 3.5, the signal constants are defined as an enum, enabling a nicer approach:
您只需循环信号模块中的信号并进行设置即可。
You could just loop through the signals in the signal module and set them up.
如果你想摆脱try,只需忽略无法捕获的信号即可。
If you want to get rid of the try, just ignore signals that cannot be caught.