GuillaumeA
GuillaumeA

Reputation: 3545

Jupyter notebook output redirection

I'd like to redirect the output of each cell of my notebook. Here is what I tried

class Logger():
    def __init__(self, stdout):
        self.stdout = stdout

    def write(self, msg):
        self.stdout.write('augmented:' + msg)

    def flush(self):
        self.stdout.flush() 

and in a cell, I change the stdout on the fly

sys.stdout = Logger(sys.stdout)

However, the output string of the next executed cells has not the "augmented" string

Upvotes: 0

Views: 2144

Answers (1)

gdlmx
gdlmx

Reputation: 6789

You can use the contextlib.

from contextlib import contextmanager
import sys
@contextmanager
def stdout_redirector():
    class MyStream:
        def write(self, msg):
            prefix = 'augmented:' if msg.strip() else ''
            old_stdout.write( prefix + msg)
        def flush(self):
            old_stdout.flush()
    old_stdout = sys.stdout
    sys.stdout = MyStream()
    try:
        yield
    finally:
        sys.stdout = old_stdout

output

It is better to use with statement to manage the redirection. If that's not possible in your case, calling the __enter__() and __exit__() methods of the redirector object also works. You can also put those redirector codes in the pre_run_cell and post_run_cell hook function in IPython.

Upvotes: 1

Related Questions