[New-bugs-announce] [issue44157] redirect_* should also redirect C-level streams

Xavier Morel report at bugs.python.org
Mon May 17 08:32:33 EDT 2021

New submission from Xavier Morel <xavier.morel at masklinn.net>:

In 3.4 (resp. 3.5), `redirect_stdout` and `redirect_stderr` were added to provide easy and reentrant stream redirection. Although that is documented, it seems like a waste that they only redirect the high-level `sys.std*`  streams: those are already pretty easy to redirect by simply setting the corresponding attribute, which is essentially what the contextmanager does. However,

* that does not work if the writer has imported the original stream object (`from sys import stderr`)
* that does not work if the writer bypasses or is not aware of the Python layer e.g. a native library

In that case, the user still has to deal with dup/dup2 dances in order to redirect the underlying fds, which is significantly more error-prone (and verbose) than intercepting the high-level `sys.std*` ever was.

On the other hand, it's also less expressive as it requires an actual fd, rather than a Python-level file-like object. So I can understand not doing it by default.

But still, I think I feel like it'd be very useful to either expand  the existing context managers to perform fd redirection, or have a separate context manager able to redirect arbitrary fds.

components: Library (Lib)
messages: 393810
nosy: xmorel
priority: normal
severity: normal
status: open
title: redirect_* should also redirect C-level streams
type: enhancement
versions: Python 3.9

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list