Skip to content

Instantly share code, notes, and snippets.

@turing4ever
Created February 22, 2018 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turing4ever/d37047994d4e239f67ed87d75464bb63 to your computer and use it in GitHub Desktop.
Save turing4ever/d37047994d4e239f67ed87d75464bb63 to your computer and use it in GitHub Desktop.
What if you have to call a noisy function that prints a lot but you can't modify it? Mute it with a context manager.
# A context manager to shut down stdout
# Within this context, sys.stdout will be written into devnull.
# so, effectively it's muted.
@contextlib.contextmanager
def shut_stdout():
sys.stdout = open(os.devnull, 'w')
yield
sys.stdout = sys.__stdout__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment