Created
July 20, 2012 14:37
-
-
Save swsnr/3151059 to your computer and use it in GitHub Desktop.
Suppress output to file descriptors in Python
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 os | |
from contextlib import contextmanager | |
@contextmanager | |
def suppress_output(fd): | |
""" | |
Suppress output to the given ``fd``:: | |
with suppress_fd(sys.stderr): | |
# in this block any output to standard error is suppressed | |
``fd`` is an integral file descriptor, or any object with a ``fileno()`` | |
method. | |
""" | |
if hasattr(fd, 'fileno'): | |
# we were given a file-like object with an underlying fd | |
if hasattr(fd, 'flush'): | |
# flush Python-side buffers before redirecting | |
fd.flush() | |
# get the fd to redirect | |
fd = fd.fileno() | |
# duplicate the file descriptor to restore it eventually | |
oldfd = os.dup(fd) | |
try: | |
# open the trash can | |
devnull = os.open(os.devnull, os.O_WRONLY) | |
try: | |
# point the file descriptor to the trash can | |
os.dup2(devnull, fd) | |
finally: | |
# close the old trash can descriptor, we don't need it anymore | |
# since the fd now points to the trash can | |
os.close(devnull) | |
# enter the callers block | |
yield | |
# restore the file descriptor | |
os.dup2(oldfd, fd) | |
finally: | |
# close the duplicated copy of the original fd, we don't need it | |
# anymore now that fd is restored | |
os.close(oldfd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment