Advertisement
Guest User

Untitled

a guest
Mar 31st, 2015
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1. """Wrap stdout, so that print calls can go to a buffer."""
  2. import sys
  3. import io
  4.  
  5. _stdout = sys.stdout
  6. class Wrapper(io.StringIO):
  7. def __init__(self, *args, **kwargs):
  8. super().__init__(*args, **kwargs)
  9. sys.stdout = self
  10. def write(self, *args, **kwargs):
  11. _stdout.write(*args, **kwargs)
  12. io.StringIO.write(self, *args, **kwargs)
  13. def __del__(self):
  14. """Put sys.stdout back in the right place."""
  15. sys.stdout = _stdout
  16.  
  17. w = Wrapper()
  18.  
  19. print('You should see this')
  20. assert w.getvalue() == 'You should see this\n'
  21. del w
  22. print("If you see this it totally worked.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement