@@ -288,21 +288,29 @@ def decolor(text: str) -> str:
288288
289289
290290def can_colorize (* , file : IO [str ] | IO [bytes ] | None = None ) -> bool :
291+
292+ def _safe_getenv (k : str , fallback : str | None = None ) -> str | None :
293+ """Exception-safe environment retrieval. See gh-128636."""
294+ try :
295+ return os .environ .get (k , fallback )
296+ except Exception :
297+ return fallback
298+
291299 if file is None :
292300 file = sys .stdout
293301
294302 if not sys .flags .ignore_environment :
295- if os . environ . get ("PYTHON_COLORS" ) == "0" :
303+ if _safe_getenv ("PYTHON_COLORS" ) == "0" :
296304 return False
297- if os . environ . get ("PYTHON_COLORS" ) == "1" :
305+ if _safe_getenv ("PYTHON_COLORS" ) == "1" :
298306 return True
299- if os . environ . get ("NO_COLOR" ):
307+ if _safe_getenv ("NO_COLOR" ):
300308 return False
301309 if not COLORIZE :
302310 return False
303- if os . environ . get ("FORCE_COLOR" ):
311+ if _safe_getenv ("FORCE_COLOR" ):
304312 return True
305- if os . environ . get ("TERM" ) == "dumb" :
313+ if _safe_getenv ("TERM" ) == "dumb" :
306314 return False
307315
308316 if not hasattr (file , "fileno" ):
@@ -345,7 +353,8 @@ def get_theme(
345353 environment (including environment variable state and console configuration
346354 on Windows) can also change in the course of the application life cycle.
347355 """
348- if force_color or (not force_no_color and can_colorize (file = tty_file )):
356+ if force_color or (not force_no_color and
357+ can_colorize (file = tty_file )):
349358 return _theme
350359 return theme_no_color
351360
0 commit comments