如何同时监视长时间运行的子进程的标准输出和标准错误,并在子进程生成每一行时立即对其进行处理?在
我不介意使用Python3.6的异步工具在两个流中的每一个上实现我所期望的无阻塞异步循环,但这似乎并不能解决问题。以下代码:import asyncio
from asyncio.subprocess import PIPE
from datetime import datetime
async def run(cmd):
p = await asyncio.create_subprocess_shell(cmd, stdout=PIPE, stderr=PIPE)
async for f in p.stdout:
print(datetime.now(), f.decode().strip())
async for f in p.stderr:
print(datetime.now(), "E:", f.decode().strip())
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(run('''
echo "Out 1";
sleep 1;
echo "Err 1" >&2;
sleep 1;
echo "Out 2"
'''))
loop.close()
输出:
^{pr2}$
我希望它能输出类似于:2018-06-18 00:06:35.766948 Out 1
2018-06-18 00:06:36.770882 E: Err 1
2018-06-18 00:06:37.770187 Out 2