Skip to content

Instantly share code, notes, and snippets.

@0x9900
Created January 28, 2015 22:38
Show Gist options
  • Save 0x9900/6167791681a80ba53d7a to your computer and use it in GitHub Desktop.
Save 0x9900/6167791681a80ba53d7a to your computer and use it in GitHub Desktop.
Silence stdout (python)
#
# Sometime, specifically in your tests, you want to silence the
# standard output or be able to read the standard output of a function
# to test what's printed. Here is some recipe to do that.
#
#
import cStringIO as StringIO
import sys
from contextlib import contextmanager
@contextmanager
def SilenceStdout(new_stream=None):
if new_stream is None:
new_stream = StringIO.StringIO()
old_stream, sys.stdout = sys.stdout, new_stream
try:
yield sys.stdout
finally:
sys.stdout = old_stream
new_stream.seek(0)
# test
if __name__ == '__main__':
def verbose_function():
print 'This function print stuff'
with SilenceStdout():
verbose_function()
with SilenceStdout() as fdout:
verbose_function()
if 'stuff' in fdout.read():
print 'the word "stuff" was found!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment