如何使用ASYNCIO流标准输出/标准错误,从一个子进程,并取得后,其退出code? [英] How to stream stdout/stderr from a child process using asyncio, and obtain its exit code after?

查看:412
本文介绍了如何使用ASYNCIO流标准输出/标准错误,从一个子进程,并取得后,其退出code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows上的Python 3.4,我需要/标准错误,子进程流写入stdout数据,也就是说,它出现接收它的输出,使用的 ASYNCIO在Python 3.4引入了框架。我也有事后确定程序的退出code。我怎样才能做到这一点?

Under Python 3.4 on Windows, I need to stream data written to stdout/stderr by a child process, i.e. receive its output as it occurs, using the asyncio framework introduced in Python 3.4. I also have to determine the program's exit code afterwards. How can I do this?

推荐答案

该解决方案,我想出迄今使用的 SubprocessProtocol 接收来自子进程的输出,以及相关的运输得到进程的退出code。我不知道这是否是最优的。我根据我的上回答由J.F.塞巴斯蒂安了类似的问题。

The solution I've come up with so far uses SubprocessProtocol to receive output from the child process, and the associated transport to get the process' exit code. I don't know if this is optimal though. I've based my approach on an answer to a similar question by J.F. 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()))

这篇关于如何使用ASYNCIO流标准输出/标准错误,从一个子进程,并取得后,其退出code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆