Answers:
用以下方式注册您的处理程序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
参见此处。
./program.py > output.log
。当您按Ctrl-C时,您要让程序记录所有数据文件均已刷新并标记为干净以确认它们处于已知的良好状态,从而使其正常退出。但是Ctrl-C将SIGINT发送到管道中的所有进程,因此shell可以在program.py完成打印最终日志之前关闭STDOUT(现在为“ output.log”)。Python将抱怨:“文件对象析构函数关闭失败:sys.excepthook中的错误:”。
您可以像对待其他异常一样将其视为异常(KeyboardInterrupt)。制作一个新文件,并从您的外壳运行以下内容,以了解我的意思:
import time, sys
x = 1
while True:
try:
print x
time.sleep(.3)
x += 1
except KeyboardInterrupt:
print "Bye"
sys.exit()
并作为上下文管理器:
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
StopIteration
当按下ctrl-C时,它也可能抛出a 中断最内层的循环,对吗?
简称main
为主要功能,并exit_gracefully
为CTRL+ c处理器
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
finally:
exit_gracefully()
我改编了@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>
)
与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
time.sleep()
不要对变量执行繁忙循环。
感谢现有的答案,但补充 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
如果您想确保清理过程完成,则可以使用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()