Just for completeness, here's a nice solution from Dave Smith's blog:
from contextlib import contextmanager
import sys, os
@contextmanager
def suppress_stdout():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
With this, you can use context management wherever you want to suppress output:
print("Now you see it")
with suppress_stdout():
print("Now you don't")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…