<p>要实现这一点,您需要一个函数,该函数将获取两个异步序列,并将它们合并到一起,在它们可用时从其中一个或另一个生成结果。{cd1>中的stock可以是这样的函数:</p>
<pre><code>async def run(cmd):
p = await asyncio.create_subprocess_shell(cmd, stdout=PIPE, stderr=PIPE)
async for f in merge(p.stdout, p.stderr):
print(datetime.now(), f.decode().strip())
</code></pre>
<p>像<code>merge</code>这样的函数在标准库中还不存在,但是<code>aiostream</code>外部库<a href="http://aiostream.readthedocs.io/en/latest/operators.html#aiostream.stream.merge" rel="noreferrer">provides one</a>。您也可以使用异步生成器和<code>asyncio.wait()</code>编写自己的程序:</p>
^{pr2}$
<p>上面的<code>run</code>仍然与您期望的输出有一个细节上的不同:它不会区分输出和错误行。但这很容易通过在线条上装饰一个指示器来实现:</p>
<pre><code>async def decorate_with(it, prefix):
async for item in it:
yield prefix, item
async def run(cmd):
p = await asyncio.create_subprocess_shell(cmd, stdout=PIPE, stderr=PIPE)
async for is_out, line in merge(decorate_with(p.stdout, True),
decorate_with(p.stderr, False)):
if is_out:
print(datetime.now(), line.decode().strip())
else:
print(datetime.now(), "E:", line.decode().strip())
</code></pre>