Hello!
We've encountered an issue where sys.stdout.encoding can sometimes be None. This leads to a TypeError when calling the console_to_str method, as the console_encoding variable is also None.
10 def console_to_str(s: bytes) -> str:
│ 11 │ """From pypa/pip project, pip.backwardwardcompat. License MIT."""
│ 12 │ try:
│ ❱ 13 │ │ return s.decode(console_encoding, "ignore")
│ 14 │ except UnicodeDecodeError:
│ 15 │ │ return s.decode("utf_8", "ignore")
│ 16
TypeError: decode() argument 'encoding' must be str, not None
Possible Cases Where sys.stdout.encoding is None
There are multiple scenarios where sys.stdout.encoding can be None, including:
-
Running in a non-interactive environment
-
Redirecting stdout to a file or a pipe
- If standard output is redirected, it may not have an associated encoding.
- Example:
python script.py > output.txt
- Similarly, when piping output:
-
Running in certain containerized environments
-
Windows with specific configurations
-
Using custom or overridden sys.stdout streams
- If sys.stdout is reassigned (e.g., wrapped in a custom stream), the encoding may not be set explicitly.
- Example:
import sys
sys.stdout = open('log.txt', 'w')
print(sys.stdout.encoding) # None
Context
This issue arises in [Kathará](https://github.com/KatharaFramework/Kathara), a container-based network emulator. More details can be found in [Kathará Issue #333](KatharaFramework/Kathara#333).
Possible Fix
A potential solution is the approach used [here](https://github.com/tcaiazzi/libtmux/blob/1bf73396ca579488a1f266a16e553f3ca735011e/src/libtmux/_compat.py#L7), which provides a fallback encoding:
console_encoding = sys.stdout.encoding if sys.stdout.encoding else sys.getdefaultencoding()
However, I am unsure if this is the best approach. Would love to hear your thoughts on whether this is the right fix or if there's a better alternative.
Thanks!
Hello!
We've encountered an issue where
sys.stdout.encodingcan sometimes be None. This leads to aTypeErrorwhen calling theconsole_to_str method, as theconsole_encodingvariable is also None.Possible Cases Where
sys.stdout.encodingisNoneThere are multiple scenarios where sys.stdout.encoding can be None, including:
Running in a non-interactive environment
Redirecting stdout to a file or a pipe
Running in certain containerized environments
Windows with specific configurations
Using custom or overridden
sys.stdoutstreamsContext
This issue arises in [Kathará](https://github.com/KatharaFramework/Kathara), a container-based network emulator. More details can be found in [Kathará Issue #333](KatharaFramework/Kathara#333).
Possible Fix
A potential solution is the approach used [here](https://github.com/tcaiazzi/libtmux/blob/1bf73396ca579488a1f266a16e553f3ca735011e/src/libtmux/_compat.py#L7), which provides a fallback encoding:
However, I am unsure if this is the best approach. Would love to hear your thoughts on whether this is the right fix or if there's a better alternative.
Thanks!