您可以创建自己的类似文件的类来写入多个文件句柄。这是一个简单的示例,其中包含重定向 sys.stdout 和 sys.stderr 的测试。
import sys
class MultiOut(object):
def __init__(self, *args):
self.handles = args
def write(self, s):
for f in self.handles:
f.write(s)
with open('q1', 'w') as f1, open('q2', 'w') as f2, open('q3', 'w') as f3:
sys.stdout = MultiOut(f1, f2)
sys.stderr = MultiOut(f3, f2)
for i, c in enumerate('abcde'):
print(c, 'out')
print(i, 'err', file=sys.stderr)
运行该代码后,这些文件包含以下内容:
q1
a out
b out
c out
d out
e out
第三季度
0 err
1 err
2 err
3 err
4 err
q2
a out
0 err
b out
1 err
c out
2 err
d out
3 err
e out
4 err
FWIW,如果你愿意,你甚至可以这样做:
sys.stdout = MultiOut(f1, f2, sys.stdout)
sys.stderr = MultiOut(f3, f2, sys.stderr)
不幸的是,像MultiOut 这样的类文件对象不能与Popen 一起使用,因为Popen 通过底层操作系统文件描述符访问文件,即它想要操作系统认为是文件的东西,所以只有提供有效fileno 方法的Python 对象才能用于Popen 的文件参数。
相反,我们可以使用 Python 3 的 asyncio 功能来执行 shell 命令并同时复制其 stdout 和 stderr 输出。
首先,这是我用来测试以下 Python 代码的简单 Bash 脚本。它只是循环一个数组,将数组内容回显到 stdout,将数组索引回显到 stderr,就像前面的 Python 示例一样。
multitest.bsh
#!/usr/bin/env bash
a=(a b c d e)
for((i=0; i<${#a[@]}; i++))
do
echo "OUT: ${a[i]}"
echo "ERR: $i" >&2
sleep 0.01
done
输出
OUT: a
ERR: 0
OUT: b
ERR: 1
OUT: c
ERR: 2
OUT: d
ERR: 3
OUT: e
ERR: 4
这是运行 multitest.bsh 的 Python 3 代码,将其 stdout 输出通过管道传输到文件 q1 和 q2,并将其 stderr 输出通过管道传输到 q3 和 q2。
import asyncio
from asyncio.subprocess import PIPE
class MultiOut(object):
def __init__(self, *args):
self.handles = args
def write(self, s):
for f in self.handles:
f.write(s)
def close(self):
pass
@asyncio.coroutine
def copy_stream(stream, outfile):
""" Read from stream line by line until EOF, copying it to outfile. """
while True:
line = yield from stream.readline()
if not line:
break
outfile.write(line) # assume it doesn't block
@asyncio.coroutine
def run_and_pipe(cmd, fout, ferr):
# start process
process = yield from asyncio.create_subprocess_shell(cmd,
stdout=PIPE, stderr=PIPE, executable="/bin/bash")
# read child's stdout/stderr concurrently
try:
yield from asyncio.gather(
copy_stream(process.stdout, fout),
copy_stream(process.stderr, ferr))
except Exception:
process.kill()
raise
finally:
# wait for the process to exit
rc = yield from process.wait()
return rc
# run the event loop
loop = asyncio.get_event_loop()
with open('q1', 'wb') as f1, open('q2', 'wb') as f2, open('q3', 'wb') as f3:
fout = MultiOut(f1, f2)
ferr = MultiOut(f3, f2)
rc = loop.run_until_complete(run_and_pipe("./multitest.bsh", fout, ferr))
loop.close()
print('Return code:', rc)
运行代码后,这些文件包含以下内容:
q1
OUT: a
OUT: b
OUT: c
OUT: d
OUT: e
第三季度
ERR: 0
ERR: 1
ERR: 2
ERR: 3
ERR: 4
q2
OUT: a
ERR: 0
OUT: b
ERR: 1
OUT: c
ERR: 2
OUT: d
ERR: 3
OUT: e
ERR: 4
asyncio 代码从J.F. Sebastian's answer 提升到问题Subprocess.Popen: cloning stdout and stderr both to terminal and variables。谢谢,J.F!
请注意,当调度的协程可以使用数据时,会将数据写入文件;确切的何时发生取决于当前的系统负载。所以我将sleep 0.01 命令放在multitest.bsh 中,以保持stdout 和stderr 行的处理同步。如果没有这种延迟, q2 中的 stdout 和 stderr 行通常不会很好地交错。可能有更好的方法来实现这种同步,但我仍然是异步编程的新手。