ython函数的输出从STDOUT重定向到Python中的变量的

ython函数的输出从STDOUT重定向到Python中的变量的

本文介绍了将Python函数的输出从STDOUT重定向到Python中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我要实现的目标



def fun():
    runner = InteractiveConsole()
    while(True):
        code = raw_input()
        code.rstrip('\n')
        # I want to achieve the following
        # By default the output and error of the 'code' is sent to STDOUT and STDERR
        # I want to obtain the output in two variables out and err
        out,err = runner.push(code)

到目前为止,我所研究的所有解决方案都使用任一管道发出单独的脚本执行命令(在我的情况下这是不可能的).还有其他方法可以实现这一目标吗?

All the solution that I have looked at till now, use either pipes to issue separate script execution command (which is not possible in my case). Any other way I can achieve this?

推荐答案

import StringIO, sys
from contextlib import contextmanager

@contextmanager
def redirected(out=sys.stdout, err=sys.stderr):
    saved = sys.stdout, sys.stderr
    sys.stdout, sys.stderr = out, err
    try:
        yield
    finally:
        sys.stdout, sys.stderr = saved


def fun():
    runner = InteractiveConsole()
    while True:
        out = StringIO.StringIO()
        err = StringIO.StringIO()
        with redirected(out=out, err=err):
            out.flush()
            err.flush()
            code = raw_input()
            code.rstrip('\n')
            # I want to achieve the following
            # By default the output and error of the 'code' is sent to STDOUT and STDERR
            # I want to obtain the output in two variables out and err
            runner.push(code)
            output = out.getvalue()
        print output

在较新版本的python中,此contezt管理器内置于:

In newer versions of python, this contezt manager is built in:

with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
    ...

这篇关于将Python函数的输出从STDOUT重定向到Python中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:20