Last active
August 10, 2018 09:35
-
-
Save msabramo/6040400 to your computer and use it in GitHub Desktop.
A context manager to temporarily redirect stdout or stderr e.g.: ```python
with stdchannel_redirected(sys.stderr, os.devnull): ...
```
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 contextlib | |
@contextlib.contextmanager | |
def stdchannel_redirected(stdchannel, dest_filename): | |
""" | |
A context manager to temporarily redirect stdout or stderr | |
e.g.: | |
with stdchannel_redirected(sys.stderr, os.devnull): | |
if compiler.has_function('clock_gettime', libraries=['rt']): | |
libraries.append('rt') | |
""" | |
try: | |
oldstdchannel = os.dup(stdchannel.fileno()) | |
dest_file = open(dest_filename, 'w') | |
os.dup2(dest_file.fileno(), stdchannel.fileno()) | |
yield | |
finally: | |
if oldstdchannel is not None: | |
os.dup2(oldstdchannel, stdchannel.fileno()) | |
if dest_file is not None: | |
dest_file.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Blogged about this at http://marc-abramowitz.com/archives/2013/07/19/python-context-manager-for-redirected-stdout-and-stderr/ and tweeted about this at https://twitter.com/MSAbramo/status/358262914920087552