我试图SIGINT在Python 2.7程序中捕获(或键盘中断).这就是我的Python测试脚本的test外观:
#!/usr/bin/python
import time
try:
time.sleep(100)
except KeyboardInterrupt:
pass
except:
print "error"
Run Code Online (Sandbox Code Playgroud)
接下来我有一个shell脚本test.sh:
./test & pid=$!
sleep 1
kill -s 2 $pid
Run Code Online (Sandbox Code Playgroud)
当我使用bash或sh或其他东西运行脚本时,bash test.shPython进程test保持运行并且无法使用SIGINT.而当我复制test.sh命令并将其粘贴到(bash)终端时,Python进程test将关闭.
我不知道发生了什么,我想了解.那么,差异在哪里,为什么?
这不是关于如何捕获SIGINTPython!根据文档 - 这是应该工作的方式:
Python默认安装少量信号处理程序:SIGPIPE ...和SIGINT转换为KeyboardInterrupt异常
这的确是追赶KeyboardInterrupt时SIGINT被发送kill,如果该程序是由外壳直接启动,但是当程序从后台运行bash脚本开始,似乎KeyboardInterrupt永远不会提高.