Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import builtins as __builtin__
- import sys
- import io
- class VoidPrinter:
- def __init__(self):
- pass
- def __enter__(self):
- self._stdout_bkp = sys.stdout
- self._stderr_bkp = sys.stderr
- sys.stdout = io.StringIO()
- sys.stderr = io.StringIO()
- def __exit__(self, exc_type, exc_val, exc_tb):
- self._stdout_trap = sys.stdout
- self._stderr_trap = sys.stderr
- sys.stdout = self._stdout_bkp
- sys.stderr = self._stderr_bkp
- def print(self):
- sys.stdout.write(self._stdout_trap.getvalue())
- sys.stderr.write(self._stderr_trap.getvalue())
- # Examples:
- # 1. Hide all output to stdout/stderr:
- #
- # with VoidPrinter():
- # [your code]
- #
- # 2. Show the output later again (might be interesting to access error-logs)
- #
- # printer = VoidPrinter()
- # with printer:
- # [your code]
- # printer.print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement