18

I would like to print into the terminal window that runs IPython Notebook and not into the cell output. Printing into cell output consumes more memory and slows down my system when I issue a substantial number of print calls. In essence, I would like this behaviour by design.

I have tried the following:

  1. I tried a different permutations of print and sys.stdout.write calls
  2. I looked at the IPython Notebook documentation here, here and here without help
  3. I have tried using this as a workaround but it seems to be only working on Python 2.7

3 Answers 3

19

You have to redirect your output to the systems standard output device. This depends on your OS. On Mac that would be:

import sys
sys.stdout = open('/dev/stdout', 'w')

Type the above code in an IPython cell and evaluate it. Afterwards all output will show up in terminal.

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

7 Comments

Is there a way to reverse that ? and recover ipython stdout
You could e.g. safe a reference to notebook's stdout before redirecting: nb_stdout = sys.stdout. Now, you would redirect the output. To get back to in notebook output simply write: sys.stdout = nb_stdout. A cleaner solution would be to use contextlib.redirect_stdout(new_target) context manager.
@MaxPowers Do you know what you should write in Windows?
@MaxPowers: Note that contextlib.redirect_stdout only works in python 3.4 and above.
Thanks to you, I can sys.stderr = open('/dev/stderr', 'w'); but how do I make this available for Windows?
|
4

On Windows, this can work:

import sys
sys.stdout = open(1, 'w')

2 Comments

Hey you are copied answer of @MaxPowers and posting
What about sys.stderr?
2

In order to be able to switch form one to the other easily:

terminal_output = open('/dev/stdout', 'w')

print('this will show up in the IPython cell output')
print('this will show up in the terminal', file=terminal_output)

Similarly, terminal_error = open('/dev/stderr', 'w') can be used to send to the terminal stderr, without any conflict with the default behavior of sys.stderr (which is to print an error message in the IPython cell output).

Comments

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.