Created
October 20, 2021 02:37
-
-
Save wonderbeyond/11c08e638414f7fe23cc3d60bcfd58c0 to your computer and use it in GitHub Desktop.
[Python] suppress stdout and stderr messages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""See also https://www.codeforests.com/2020/11/05/python-suppress-stdout-and-stderr/""" | |
import os | |
import sys | |
from contextlib import contextmanager | |
@contextmanager | |
def suppress_output(suppress_stdout=True, suppress_stderr=True): | |
orig_streams = (sys.stdout, sys.stderr) | |
null_stream = open(os.devnull, "w") | |
if suppress_stdout: | |
sys.stdout = null_stream | |
if suppress_stderr: | |
sys.stderr = null_stream | |
try: | |
yield | |
finally: | |
sys.stdout, sys.stderr = orig_streams | |
if __name__ == '__main__': | |
with suppress_output(): | |
print("stdout INSIDE context") | |
print("stderr INSIDE context", file=sys.stderr) | |
print("stdout OUTSIDE context") | |
print("stderr OUTSIDE context", file=sys.stderr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment