0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The events in IPython were exactly what I was looking for ! I was not aware of there existence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.