Created
May 24, 2017 07:56
-
-
Save multimeric/545a5e1639c7d88720eab8054a6cae92 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
@contextlib.contextmanager | |
def suppress_outputs(suppress_stdout=True, suppress_stderr=True): | |
""" | |
Context manager that can be used to suppress any printing to sdtout or stderr from any python | |
code within its context | |
""" | |
#Open /dev/null | |
null = open(os.devnull, 'w') | |
# Save the old output streams | |
save_stdout = sys.stdout | |
save_stderr = sys.stderr | |
# Pipe the streams to /dev/null if needed | |
if suppress_stdout: | |
sys.stdout = null | |
if suppress_stderr: | |
sys.stderr = null | |
# Pass control back to the user | |
yield | |
# Restore the output streams | |
sys.stdout = save_stdout | |
sys.stderr = save_stderr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment