jj172
jj172

Reputation: 809

Python-Undoing stdout redirect

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?

Upvotes: 2

Views: 814

Answers (3)

hiro protagonist
hiro protagonist

Reputation: 46839

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? .

Upvotes: 2

Nir Alfasi
Nir Alfasi

Reputation: 53525

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'

Upvotes: 3

dano
dano

Reputation: 94871

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.

Upvotes: 6

Related Questions