在Python中将python函数的输出从STDOUT重定向到变量

gib*_*tar 2 python io-redirection

这就是我想要实现的目标


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)

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

Eri*_*ric 6

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
Run Code Online (Sandbox Code Playgroud)

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

with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
    ...
Run Code Online (Sandbox Code Playgroud)