2 回答

TA贡献1856条经验 获得超5个赞
#!/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()
从如何在 Python 中捕获 SIGINT?
我建议您使用并注册适当的信号处理程序,至少如果您的主要目标是简单地捕获任何用户/系统中断。
这是清理任何退出/中断的好方法。
如果您将应用程序作为服务运行以处理关闭事件等,也可以使用。

TA贡献2039条经验 获得超7个赞
我觉得这可能不是正确的方法,但您可以尝试使用contextmanager:
import time
from contextlib import contextmanager
# build your keyboard interrupt listener
@contextmanager
def kb_listener(func):
print('Hey want to listen to KeyboardInterrupt?')
try:
yield func
except KeyboardInterrupt:
print("Who's there?")
interrupt() # <--- what you actually want to do when KeyboardInterrupt
# This might not be necessary for your code
finally:
print('Keyboa^C')
# sample KeyboardInterrupt event
def interrupt():
print("KeyboardInterrupt.")
# sample layered function
def do_thing():
while True:
print('Knock Knock')
time.sleep(1)
with kb_listener(do_thing) as f:
f()
测试输出:
Hey want to listen to KeyboardInterrupt?
Knock Knock
Knock Knock
Knock Knock
Who's there?
KeyboardInterrupt.
Keyboa^C
至少这样您就不需要将整个函数包装在一个try... except块中。
添加回答
举报