Last active
May 14, 2019 12:21
-
-
Save zimmerrol/0c7e77b829798a5c8f03025937cd1454 to your computer and use it in GitHub Desktop.
Disable print function temporarily
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment