<p>我用的大概是:</p>
<pre><code>from datetime import datetime
from time import time
import subprocess
import sys
import threading
import os
class Execution(threading.Thread):
comm = None
proc = None
returncode = None
stdoutdata = None
stderrdate = None
def __init__(self, comm):
threading.Thread.__init__(self)
self.comm = comm
def run(self):
self.proc = subprocess.Popen(self.comm, bufsize=-1, stdin=None,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.proc.wait()
(self.stdoutdata, self.stderrdata) = self.proc.communicate()
self.returncode = self.proc.poll()
for curcommand in somecommandlist:
ex = Execution(curcommand)
starttime = time()
ex.start()
ex.join(some_timeout_in_seconds)
wastimeout = False
if (ex.isAlive()):
wastimeout = True
print("TIMEOUT OCCURRED @ %s" % (datetime.today(),))
ex.proc.kill()
ex.join()
endtime = time()
duration = endtime - starttime
print("DURATION %s" % (duration,))
exitcode = ex.returncode
print("EXIT CODE: %s" % (exitcode,))
print somepostprocessing(ex.stdoutdata,ex.stderrdata)
sys.stdout.flush()
</code></pre>
<p>基本上:在一个单独的线程中启动进程。这是必需的,因为<code>threading</code>模块给您超时等待,而<code>subprocess</code>模块没有。等待超时;检查线程是否仍处于活动状态。如果线程是活动的,我们通过终止进程来终止它(这里,<code>subprocess</code>提供了一个<code>kill()</code>构造,<code>threading</code>没有),并等待线程自行结束。在</p>
<p>请记住,<code>communicate()</code>阻塞并存储来自子级stderr和stdout的<em>完整</em>输出,因此如果输出非常大,这可能不起作用。在</p>