0

In JupyterLab, I want to close the sys.stdout to avoid printing data, and then reopen the sys.stdout to allow printing.

Firstly, I use "sys.stdout = open(os.devnull, 'w')" to redirect the output flow. It worked in Jupyter. In Block 3, the output is not working.

redirect stdout

However, in Block 4, I tried recover the sys.stdout, the output displays in Block 2. recover stdout

I want to show the output in Block 4.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
lin sun
  • 3
  • 2
  • If the stdout is still set to /dev/null, why the print command outputs the data in block 2? Furthermore, when using print(5) in block 5, it's working. – lin sun Mar 06 '23 at 07:06
  • As an aside: There's a built in Jupyter magic where you can suppress most output from a cell or with a `with capture()` to just suppress things in the `with` context. See [here](https://stackoverflow.com/a/23692951/8508004) and my comment below that highly-voted answer. – Wayne Mar 06 '23 at 21:47
  • Always put your code in the answer as text, even if also including a screenshot. That way people can run it easily and give you the edited version back easily. See [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask), particularly about screenshots. Here it was good to show the behavior you described. However, code is generally necessary. No one wants to retype code you already had as text and could have included. – Wayne Mar 06 '23 at 21:55

1 Answers1

0

The first time you run the 4th cell, which is the following:

sys.stdout = std_out_bk
print(1)

It won't show the output. (Probably because it is a cell property how std.out is being directed at present when when the cell is initiated and locked in until that cell execution completes. Just a guess based on the behavior. I even tried adding a context)
Put sys.stdout = std_out_bk as a separate cell above that.
Or run the 4th cell twice.

Or use the stderr channel for stdout as cell 4:

from contextlib import redirect_stdout
with redirect_stdout(sys.stderr):
    print(1)
sys.stdout = std_out_bk

See that in context in a notebook here. (Click on the github symbol icon above to go to the gist from the nbviewer rendering.)

Wayne
  • 6,607
  • 8
  • 36
  • 93