From e5f4f5c8b9fc2d17c26e3bc0211b714b1da26c4f Mon Sep 17 00:00:00 2001 From: gs80140 Date: Tue, 2 Apr 2024 17:46:54 +0800 Subject: [PATCH] Fix Windows AttributeError: 'NoneType' object has no attribute 'encoding' (#9496) Co-authored-by: Glenn Jocher Co-authored-by: UltralyticsAssistant --- ultralytics/utils/__init__.py | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/ultralytics/utils/__init__.py b/ultralytics/utils/__init__.py index c005e3c8f..2dba6cde9 100644 --- a/ultralytics/utils/__init__.py +++ b/ultralytics/utils/__init__.py @@ -230,37 +230,42 @@ def plt_settings(rcparams=None, backend="Agg"): return decorator -def set_logging(name=LOGGING_NAME, verbose=True): - """Sets up logging for the given name with UTF-8 encoding support.""" +def set_logging(name="LOGGING_NAME", verbose=True): + """Sets up logging for the given name with UTF-8 encoding support, ensuring compatibility across different + environments. + """ level = logging.INFO if verbose and RANK in {-1, 0} else logging.ERROR # rank in world for Multi-GPU trainings - # Configure the console (stdout) encoding to UTF-8 + # Configure the console (stdout) encoding to UTF-8, with checks for compatibility formatter = logging.Formatter("%(message)s") # Default formatter - if WINDOWS and sys.stdout.encoding != "utf-8": + if WINDOWS and hasattr(sys.stdout, "encoding") and sys.stdout.encoding != "utf-8": + + class CustomFormatter(logging.Formatter): + def format(self, record): + """Sets up logging with UTF-8 encoding and configurable verbosity.""" + return emojis(super().format(record)) + try: + # Attempt to reconfigure stdout to use UTF-8 encoding if possible if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8") + # For environments where reconfigure is not available, wrap stdout in a TextIOWrapper elif hasattr(sys.stdout, "buffer"): import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") else: - sys.stdout.encoding = "utf-8" + formatter = CustomFormatter("%(message)s") except Exception as e: print(f"Creating custom formatter for non UTF-8 environments due to {e}") + formatter = CustomFormatter("%(message)s") - class CustomFormatter(logging.Formatter): - def format(self, record): - """Sets up logging with UTF-8 encoding and configurable verbosity.""" - return emojis(super().format(record)) - - formatter = CustomFormatter("%(message)s") # Use CustomFormatter to eliminate UTF-8 output as last recourse - - # Create and configure the StreamHandler + # Create and configure the StreamHandler with the appropriate formatter and level stream_handler = logging.StreamHandler(sys.stdout) stream_handler.setFormatter(formatter) stream_handler.setLevel(level) + # Set up the logger logger = logging.getLogger(name) logger.setLevel(level) logger.addHandler(stream_handler)