Fix Windows AttributeError: 'NoneType' object has no attribute 'encoding' (#9496)
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com> Co-authored-by: UltralyticsAssistant <web@ultralytics.com>
This commit is contained in:
parent
de2641fad7
commit
e5f4f5c8b9
1 changed files with 18 additions and 13 deletions
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue