问题:如何在Python中捕获SIGINT?
我正在研究启动多个进程和数据库连接的python脚本。我不时地想用Ctrl+ C信号杀死脚本,我想进行一些清理。
在Perl中,我可以这样做:
$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
如何在Python中做类似的事情?
回答 0
用以下方式注册您的处理程序signal.signal
:
#!/usr/bin/env python
import signal
import sys
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
代码改编自此处。
有关更多文档,请signal
参见此处。
回答 1
您可以像对待其他异常一样将其视为异常(KeyboardInterrupt)。制作一个新文件,并从您的外壳运行以下内容,以了解我的意思:
import time, sys
x = 1
while True:
try:
print x
time.sleep(.3)
x += 1
except KeyboardInterrupt:
print "Bye"
sys.exit()
回答 2
并作为上下文管理器:
import signal
class GracefulInterruptHandler(object):
def __init__(self, sig=signal.SIGINT):
self.sig = sig
def __enter__(self):
self.interrupted = False
self.released = False
self.original_handler = signal.getsignal(self.sig)
def handler(signum, frame):
self.release()
self.interrupted = True
signal.signal(self.sig, handler)
return self
def __exit__(self, type, value, tb):
self.release()
def release(self):
if self.released:
return False
signal.signal(self.sig, self.original_handler)
self.released = True
return True
使用方法:
with GracefulInterruptHandler() as h:
for i in xrange(1000):
print "..."
time.sleep(1)
if h.interrupted:
print "interrupted!"
time.sleep(2)
break
嵌套处理程序:
with GracefulInterruptHandler() as h1:
while True:
print "(1)..."
time.sleep(1)
with GracefulInterruptHandler() as h2:
while True:
print "\t(2)..."
time.sleep(1)
if h2.interrupted:
print "\t(2) interrupted!"
time.sleep(2)
break
if h1.interrupted:
print "(1) interrupted!"
time.sleep(2)
break
回答 3
您可以通过捕获异常来处理CTRL+ 。您可以在异常处理程序中实现任何清理代码。CKeyboardInterrupt
回答 4
从Python的文档中:
import signal
import time
def handler(signum, frame):
print 'Here you go'
signal.signal(signal.SIGINT, handler)
time.sleep(10) # Press Ctrl+c here
回答 5
另一个片段
简称main
为主要功能,并exit_gracefully
为CTRL+ c处理器
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
finally:
exit_gracefully()
回答 6
我改编了@udi的代码以支持多种信号(没什么花哨的):
class GracefulInterruptHandler(object):
def __init__(self, signals=(signal.SIGINT, signal.SIGTERM)):
self.signals = signals
self.original_handlers = {}
def __enter__(self):
self.interrupted = False
self.released = False
for sig in self.signals:
self.original_handlers[sig] = signal.getsignal(sig)
signal.signal(sig, self.handler)
return self
def handler(self, signum, frame):
self.release()
self.interrupted = True
def __exit__(self, type, value, tb):
self.release()
def release(self):
if self.released:
return False
for sig in self.signals:
signal.signal(sig, self.original_handlers[sig])
self.released = True
return True
此代码支持键盘中断调用(SIGINT
)和SIGTERM
(kill <process>
)
回答 7
与Matt J的回答相反,我使用一个简单的对象。这使我有可能将处理程序解析为所有需要停止securlery的线程。
class SIGINT_handler():
def __init__(self):
self.SIGINT = False
def signal_handler(self, signal, frame):
print('You pressed Ctrl+C!')
self.SIGINT = True
handler = SIGINT_handler()
signal.signal(signal.SIGINT, handler.signal_handler)
别处
while True:
# task
if handler.SIGINT:
break
回答 8
您可以使用Python的内置信号模块中的函数在python中设置信号处理程序。具体来说,该signal.signal(signalnum, handler)
功能用于注册handler
信号功能signalnum
。
回答 9
感谢现有的答案,但补充 signal.getsignal()
import signal
# store default handler of signal.SIGINT
default_handler = signal.getsignal(signal.SIGINT)
catch_count = 0
def handler(signum, frame):
global default_handler, catch_count
catch_count += 1
print ('wait:', catch_count)
if catch_count > 3:
# recover handler for signal.SIGINT
signal.signal(signal.SIGINT, default_handler)
print('expecting KeyboardInterrupt')
signal.signal(signal.SIGINT, handler)
print('Press Ctrl+c here')
while True:
pass
回答 10
如果您想确保清理过程完成,则可以使用SIG_IGN来添加Matt J的答案,以便进一步忽略它们,以防止清理中断。SIGINT
import signal
import sys
def signal_handler(signum, frame):
signal.signal(signum, signal.SIG_IGN) # ignore additional signals
cleanup() # give your process a chance to clean up
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler) # register the signal with the signal handler first
do_stuff()
回答 11
就个人而言,我无法使用try / except KeyboardInterrupt,因为我使用的是阻塞的标准套接字(IPC)模式。因此,对SIGINT进行了提示,但仅在套接字上接收到数据之后才出现。
设置信号处理程序的行为相同。
另一方面,这仅适用于实际终端。其他启动环境可能不接受Ctrl+ C或预先处理信号。
此外,Python中还有“异常”和“ BaseExceptions”,它们在解释器需要干净退出本身的意义上有所不同,因此某些异常的优先级高于其他异常(异常是从BaseException派生的)