JupyterLab no longer allows ouput to be redirected to stdout?

In the past when working in a Jupyter notebook, I could redirect output like a print command to my computer’s terminal window rather than the notebook in which the code was running. This looked like this:

import sys
from contextlib import redirect_stdout
terminal = sys.__stdout__
with redirect_stdout(terminal):
    print("test", file=terminal, flush=True)

However, in a recent update of JupyterLab, this no longer works. Now the code above directs the output to both the terminal and the notebook. How do I direct this print command to the terminal only (the usual sys.stdout) rather than having it also print in the notebook itself (seemingly via the ipykernel.iostream.OutStream object)?

You could maybe try to suppress the in-notebook stream with the %%capture cell magic?

%%capture
import sys
from contextlib import redirect_stdout
terminal = sys.__stdout__
with redirect_stdout(terminal):
    print("test", file=terminal, flush=True)

Unfortunately that still prints to the notebook too.

The bigger picture is that I am developing a package and I want the package’s printed output to go to the terminal, not to the notebook. The code I posted above used to do that, both when run in the notebook directly, or when used in a module that the notebook imported.

I don’t think this is a JupyterLab vs Jupyter Notebook difference. In the current Jupyter Notebook package, I also get output in the notebook and in terminal. Perhaps some other package changed to make the current behavior?

Does your example snippet work for you right now in the current version of the classic Jupyter Notebook?

1 Like

Interesting. In classic Jupyter Notebook it also directs the output to both the terminal and the notebook.

I just downgraded ipykernel to 5.5.5 (from 6.4.1), and the old behavior is back: it directs the output to only the terminal. Perhaps something in ipykernel v6.x is hijacking stdout and forcing it to always render in the notebook itself?

Redirecting output would be the ipykernel’s job, so likely that is where the issue would be.

1 Like