Yes, I did miss Victor's dup2() comment. (It looks like I did not subscribe to this issue from the start and missed early discussion - sorry.)
The simple feature is not very useful for me. I have to deal with too many cases of misguided code like this:
def write_xyz(output=sys.stdout):
...
for which
with RedirectStdout(...):
write_xyz()
will not work.
I will create a separate issue once I have a concrete proposal, but with respect to this specific issue, I think it is better to provide a recipe in contextlib documentation for something like this:
@contextlib.contextmanager
def redirect_stdout(stream):
old_stdout = sys.stdout
sys.stdout = stream
yield
sys.stdout = old_stdout
With the proposed RedirectStdout, I think many users will want some tweaks and will copy the "from scratch" implementation instead of discovering contextmanager. |