capture.py 570 B

123456789101112131415161718192021222324252627282930
  1. # vim: set fileencoding=utf-8 :
  2. import sys
  3. from contextlib import contextmanager
  4. from six import StringIO
  5. class StderrCapture(StringIO):
  6. def save(self):
  7. self.safed = sys.stderr
  8. sys.stderr = self
  9. def restore(self):
  10. if self.safed is not None:
  11. sys.stderr = self.safed
  12. self.safed = None
  13. def output(self):
  14. self.seek(0)
  15. return self.read()
  16. @contextmanager
  17. def capture_stderr():
  18. """Capture an output and return its content"""
  19. c = StderrCapture()
  20. c.save()
  21. yield c
  22. c.restore()