Skip to content

Instantly share code, notes, and snippets.

@multimeric
Created May 24, 2017 07:56
Show Gist options
  • Save multimeric/545a5e1639c7d88720eab8054a6cae92 to your computer and use it in GitHub Desktop.
Save multimeric/545a5e1639c7d88720eab8054a6cae92 to your computer and use it in GitHub Desktop.
@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