如何使用asyncio从子进程流式传输stdout/stderr,并在之后获取其退出代码?

akn*_*ds1 4 python asynchronous python-3.4 python-asyncio

在Windows上的Python 3.4下,我需要通过子进程流式传输写入stdout/stderr的数据,即使用Python 3.4中引入的asyncio框架接收其输出.之后我还必须确定程序的退出代码.我怎样才能做到这一点?

akn*_*ds1 6

到目前为止我提出的解决方案使用SubprocessProtocol接收子进程的输出,以及关联的传输以获取进程的退出代码.我不知道这是否是最佳的.我的方法是基于JF Sebastian对类似问题回答.

import asyncio
import contextlib
import os
import locale


class SubprocessProtocol(asyncio.SubprocessProtocol):
    def pipe_data_received(self, fd, data):
        if fd == 1:
            name = 'stdout'
        elif fd == 2:
            name = 'stderr'
        text = data.decode(locale.getpreferredencoding(False))
        print('Received from {}: {}'.format(name, text.strip()))

    def process_exited(self):
        loop.stop()


if os.name == 'nt':
    # On Windows, the ProactorEventLoop is necessary to listen on pipes
    loop = asyncio.ProactorEventLoop()
    asyncio.set_event_loop(loop)
else:
    loop = asyncio.get_event_loop()
with contextlib.closing(loop):
    # This will only connect to the process
    transport = loop.run_until_complete(loop.subprocess_exec(
        SubprocessProtocol, 'python', '-c', 'print(\'Hello async world!\')'))[0]
    # Wait until process has finished
    loop.run_forever()
    print('Program exited with: {}'.format(transport.get_returncode()))
Run Code Online (Sandbox Code Playgroud)