Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # 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!'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement