我有一个命令,我script
使用subprocess.Popen
. 如果用户发出SIGINT
.
我可以确定该过程是否以至少两种方式被中断:
A. 如果被包装的命令具有非零退出状态,则死亡(不起作用,因为script
似乎总是返回 0)
B.SIGINT
在父 Python 脚本中做一些特别的事情,而不是简单地中断子进程。我尝试了以下方法:
import sys
import signal
import subprocess
def interrupt_handler(signum, frame):
print "While there is a 'script' subprocess alive, this handler won't executes"
sys.exit(1)
signal.signal(signal.SIGINT, interrupt_handler)
for n in range( 10 ):
print "Going to sleep for 2 second...Ctrl-C to exit the sleep cycles"
# exit 1 if we make it to the end of our sleep
cmd = [ 'script', '-q', '-c', "sleep 2 && (exit 1)", '/dev/null']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
if p.poll() != None :
break
else :
pass
# Exiting on non-zero exit status would suffice
print "Exit status (script always exits zero, despite what happened to the wrapped command):", p.returncode
我想按 Ctrl-C 退出 python 脚本。相反,发生的是子进程死亡并且脚本继续。