def run_pipeline(cmds):
# The Python executable (and its children) ignore SIGPIPE. (See
# http://bugs.python.org/issue1652) Our subprocesses need to see
# it.
sigpipe_handler = signal.signal(signal.SIGPIPE, signal.SIG_DFL)
stdin = None
last_proc = None
procs = []
try:
for cmd in cmds:
proc = subprocess.Popen(shlex.split(cmd), stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if last_proc:
# Ensure last_proc receives SIGPIPE if proc exits first
last_proc.stdout.close()
procs.append(proc)
stdin = proc.stdout
last_proc = proc
finally:
signal.signal(signal.SIGPIPE, sigpipe_handler)
last_stderr = last_proc.communicate()[1]
results = []
for (cmd, proc) in zip(cmds[:-1], procs[:-1]):
# wait() is OK here, despite use of PIPE above; these procs
# are finished.
proc.wait()
results.append((proc.returncode, proc.stderr.read()))
results.append((last_proc.returncode, last_stderr))
return results
评论列表
文章目录