Redirecting the output of a python function from STDOUT to variable in Python

io-redirection, python

Solution

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

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

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

Problem

This is what I am trying to achieve ``` 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?

Original source

Related problems