擅长:python、mysql、java
<p>在我看来,实际上有一个更简单的解决方案来解决这个问题,至少如果监视代码不需要在一个协程调用中。在</p>
<p>您可以生成两个独立的协同程序,一个用于stdout,一个用于stderr。并行运行它们将为您提供所需的语义,您可以使用<code>gather</code>等待它们的完成:</p>
<pre><code>def watch(stream, prefix=''):
async for line in stream:
print(datetime.now(), prefix, line.decode().strip())
async def run(cmd):
p = await asyncio.create_subprocess_shell(cmd, stdout=PIPE, stderr=PIPE)
await asyncio.gather(watch(p.stdout), watch(p.stderr, 'E:'))
</code></pre>