Original title: Import prints, even when stdout and stderr are suppressed
I have a module that I need to use. However, when it is imported, it helpfully prints out some status information.
import problematic_module Connected to local cache! Detected version 1.0.0!
I want to suppress this, so a CLI tool does not have unnecessary cruft surrounding the output. There are many questions about how to suppress console output, and a popular solution is something like this.: import contextlib import os import sys
@contextlib.contextmanager def silent_legacy_startup(): try: old_stdout = sys.stdout old_stderr = sys.stderr with open(os.devnull, “w”) as devnull: with contextlib.redirect_stdout(devnull): with contextlib.redirect_stderr(devnull):
sys.__stdout__ = devnull
sys.__stderr__ = devnull
# PLEASE BE QUIET.
yield
finally:
sys.__stdout__ = old_stdout