Advertisement
Guest User

Untitled

a guest
Jan 28th, 2015
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. #
  2. # Sometime, specifically in your tests, you want to silence the
  3. # standard output or be able to read the standard output of a function
  4. # to test what's printed. Here is some recipe to do that.
  5. #
  6. #
  7.  
  8. import cStringIO as StringIO
  9. import sys
  10.  
  11. from contextlib import contextmanager
  12.  
  13. @contextmanager
  14. def SilenceStdout(new_stream=None):
  15. if new_stream is None:
  16. new_stream = StringIO.StringIO()
  17.  
  18. old_stream, sys.stdout = sys.stdout, new_stream
  19. try:
  20. yield sys.stdout
  21. finally:
  22. sys.stdout = old_stream
  23. new_stream.seek(0)
  24.  
  25.  
  26. # test
  27. if __name__ == '__main__':
  28. def verbose_function():
  29. print 'This function print stuff'
  30.  
  31. with SilenceStdout():
  32. verbose_function()
  33.  
  34. with SilenceStdout() as fdout:
  35. verbose_function()
  36.  
  37. if 'stuff' in fdout.read():
  38. print 'the word "stuff" was found!'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement