I'm trying to use a with
statement to suppress sys.stdout
or sys.stderr
individually. I found a tutorial that didn't work. I'm using Python 3.6.4
and I think the tutorial is some version of Python 2
.
I looked it up on SO and found a few but with applications that didn't work or did not apply to this situation.
This doesn't apply:Python subprocess supress stdout and stderr
Couldn't get any of the with
statements to work:
Suppress stdout / stderr print from Python functions
This is for fortran: Redirecting FORTRAN (called via F2PY) output in Python
from contextlib import contextmanager
@contextmanager
def suppress_console(file=sys.stdout):
with open(os.devnull, "w") as devnull:
old_file = file
file = devnull
try:
yield
finally:
file = old_file
with suppress_console():
print(1, file=sys.stdout)
# 1
I use something like this:
class Suppress:
def __init__(self, *, suppress_stdout=False, suppress_stderr=False):
self.suppress_stdout = suppress_stdout
self.suppress_stderr = suppress_stderr
self.original_stdout = None
self.original_stderr = None
def __enter__(self):
import sys, os
devnull = open(os.devnull, "w")
# Suppress streams
if self.suppress_stdout:
self.original_stdout = sys.stdout
sys.stdout = devnull
if self.suppress_stderr:
self.original_stderr = sys.stderr
sys.stderr = devnull
def __exit__(self, *args, **kwargs):
import sys
# Restore streams
if self.suppress_stdout:
sys.stdout = self.original_stdout
if self.suppress_stderr:
sys.stderr = self.original_stderr
Example:
import sys
print("Before")
with Suppress(suppress_stdout=True):
print("Inside")
print("After")
print("Before", file=sys.stderr)
with Suppress(suppress_stderr=True):
print("Inside", file=sys.stderr)
print("After", file=sys.stderr)
Output:
Before After Before After
Notes:
__exit__
method. You might look into crafting a more robust exit method.