2

So I know from

Redirecting stdout to "nothing" in python

that you can suppress print statements. But is it possible to undo that command later on, so that after a certain points, print statements will indeed be printed again?

For example, let's say I want to print "b" but not "a".

I would do:

import os
f = open(os.devnull, 'w')
sys.stdout = f

print("a")

# SOME COMMAND

print("b")

Could someone enlighten me as to what "SOME COMMAND" would be?

Community
  • 1
  • 1
jj172
  • 751
  • 2
  • 9
  • 35
  • use [`contextlib.redirect_stdout`](https://docs.python.org/3.4/library/contextlib.html#contextlib.redirect_stdout) and don't worry about it. – roippi Aug 16 '14 at 01:16
  • You could use a context manager as shown in [Redirect stdout to a file in Python?](http://stackoverflow.com/a/22434262/4279). – jfs Aug 16 '14 at 01:18

3 Answers3

5

The original sys.stdout is always preserved in sys.__stdout__:

sys.stdout = sys.__stdout__

However, the documentation does note that explictly saving the original sys.stdout is preferred:

It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object.

dano
  • 91,354
  • 19
  • 222
  • 219
3
import os
import sys

f = open(os.devnull, 'w')
x = sys.stdout # save sys.stdout
sys.stdout = f

print("a")


sys.stdout = x # re-assign sys.stdout
print("b") # print 'b'
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
2

starting from python 3.4 you can do this (see contextlib.redirect_stdout)

from contextlib import redirect_stdout

with redirect_stdout(None):
    # stdout suppressed
# stdout restored

stdout is suppressed within the with statement. outside the with context your stdout is restored.

and by the way: there is no need to f = open(os.devnull, 'w') in your original version - sys.stdout = None is enough as i recently learned: why does sys.stdout = None work? .

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111