I have a Python script that is using some closed-box Python functions (i.e. I can't edit these functions) provided by my employer. When I call these functions, they are printing output to my linux terminal that I would like to suppress. I've tried redirecting stdout / stderr via;
orig_out = sys.stdout
sys.stdout = StringIO()
sys.stdout = orig_out
# Define a context manager to suppress stdout and stderr.
A context manager for doing a "deep suppression" of stdout and stderr in
Python, i.e. will suppress all print, even if the print originates in a
compiled C/Fortran sub-function.
This will not suppress raised exceptions, since exceptions are printed
to stderr just before a script exits, and after the context manager has
exited (at least, I think that is why it lets exceptions through).
# Open a pair of null files
self.null_fds = [os.open(os.devnull,os.O_RDWR) for x in range(2)]
# Save the actual stdout (1) and stderr (2) file descriptors.
self.save_fds = (os.dup(1), os.dup(2))
# Assign the null pointers to stdout and stderr.
def __exit__(self, *_):
# Re-assign the real stdout/stderr back to (1) and (2)
# Close the null files
This approach (found through the related sidebar) might work. It reassigns the file descriptors rather than just the wrappers to them in sys.stdout, etc.