0

How do I set a Jupyter notebook's output back to the output cells after sending its output to a file?

Sending its output to a file:

sys.stdout = open(filename, 'w')
print "stuff"

Sending its output back to the output cells:

sys.stdout = ?
print "hopefully this is in an output cell now"
Matt Kleinsmith
  • 1,017
  • 3
  • 13
  • 24
  • 1
    Possible duplicate of [Redirect stdout to a file in Python?](https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python) The second answer is much better than the accepted one, as it ensures proper cleanup and avoids having to write a bunch of manual code. – jpmc26 Sep 25 '19 at 13:42

1 Answers1

4

Use a temporary variable:

stdout_backup = sys.stdout

Sending its output to a file:

sys.stdout = open(filename, 'w')
print "stuff"

Sending its output back to the output cells:

sys.stdout = stdout_backup
print "this is in an output cell now"
Matt Kleinsmith
  • 1,017
  • 3
  • 13
  • 24