【发布时间】:2018-06-17 23:13:24
【问题描述】:
如何同时查看长时间运行的子进程的标准输出和标准错误,并在子进程生成后立即处理每一行?
我不介意使用 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()
输出:
2018-06-18 00:06:35.766948 Out 1
2018-06-18 00:06:37.770187 Out 2
2018-06-18 00:06:37.770882 E: Err 1
虽然我希望它输出如下内容:
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
【问题讨论】:
标签: python subprocess python-asyncio