You need to store the old stdin so that you can restore it:
import sys
import os
# Disable
def blockPrint():
sys.__stdout__ = sys.stdout
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
blockPrint()
print("test")
enablePrint()
print("test")
will print test
once. Furthermore I'd recommend the use of a contextmanager:
from contextlib import contextmanager
@contextmanager
def blockPrint():
import sys
old_stdout = sys.stdout
sys.stdout = None
try:
yield
finally:
sys.stdout = old_stdout
with blockPrint():
print("test")
print("test")
which will again print test
just once.
Edit: For those wondering why this can benecessary: Under some circumstances sys.__stdout__
can be None (see https://docs.python.org/3/library/sys.html) - For me this is for example the case in a Python 3.5 shell within IDLE on Windows.
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import sys
>>> repr(sys.__stdout__)
'None'
>>> repr(sys.stdout)
'<idlelib.PyShell.PseudoOutputFile object at 0x03ACF8B0>'