Skip to content

Commit 9205298

Browse files
Fix crash when sys.stdout.encoding is None (#21392)
[print_msg](cci:1://file:///d:/Github/keras/keras/src/utils/io_utils.py:91:0-112:29) now defaults to UTF-8 when `sys.stdout.encoding` is unset, preventing a `TypeError` during logging in non-interactive or redirected-output environments.
1 parent e0bf7f8 commit 9205298

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

keras/src/utils/io_utils.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,12 @@ def print_msg(message, line_break=True):
101101
# To address this, replace special unicode characters in the
102102
# message, and then encode and decode using the target encoding.
103103
message = _replace_special_unicode_character(message)
104-
message_bytes = message.encode(sys.stdout.encoding, errors="ignore")
105-
message = message_bytes.decode(sys.stdout.encoding)
104+
# Fallback to UTF-8 when `sys.stdout.encoding` is `None` (e.g. when
105+
# stdout is redirected). This prevents a `TypeError` that would be
106+
# raised by `bytes.encode(None)` / `bytes.decode(None)`.
107+
encoding = sys.stdout.encoding or "utf-8"
108+
message_bytes = message.encode(encoding, errors="ignore")
109+
message = message_bytes.decode(encoding)
106110
sys.stdout.write(message)
107111
sys.stdout.flush()
108112
else:

0 commit comments

Comments
 (0)