<p>不知道具体细节,但最好的方法仍然是用信号捕捉错误(甚至可能是所有错误),并终止任何剩余的进程。</p>
<pre><code>import signal
import sys
import subprocess
import os
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
a = subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT)
while 1:
pass # Press Ctrl-C (breaks the application and is catched by signal_handler()
</code></pre>
<p>这只是一个模型,你需要捕捉的不仅仅是SIGINT,但这个想法可能会让你开始,你还需要检查生成的进程。</p>
<p><a href="http://docs.python.org/2/library/os.html#os.kill" rel="nofollow">http://docs.python.org/2/library/os.html#os.kill</a>
<a href="http://docs.python.org/2/library/subprocess.html#subprocess.Popen.pid" rel="nofollow">http://docs.python.org/2/library/subprocess.html#subprocess.Popen.pid</a>
<a href="http://docs.python.org/2/library/subprocess.html#subprocess.Popen.kill" rel="nofollow">http://docs.python.org/2/library/subprocess.html#subprocess.Popen.kill</a></p>
<p>我建议重写<code>check_output</code>的个性化版本,因为我刚刚意识到check_输出实际上只是为了简单的调试等,因为在执行过程中不能与它进行太多交互。。</p>
<h2>重写检查输出:</h2>
<pre><code>from subprocess import Popen, PIPE, STDOUT
from time import sleep, time
def checkOutput(cmd):
a = Popen('ls -l', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print(a.pid)
start = time()
while a.poll() == None or time()-start <= 30: #30 sec grace period
sleep(0.25)
if a.poll() == None:
print('Still running, killing')
a.kill()
else:
print('exit code:',a.poll())
output = a.stdout.read()
a.stdout.close()
a.stdin.close()
return output
</code></pre>
<p>使用它做任何你想做的事情,也许将活动的执行存储在一个临时变量中,并在退出时用信号或其他方法隐藏主循环的错误/关闭来杀死它们。</p>
<p>最后,您仍然需要在主应用程序中捕获终止符,以便安全地杀死任何child,最好的方法是使用<code>try & except</code>或<code>signal</code>。</p>