setattr(NoColors, attr, "")
-def get_colors(colorize: bool = False) -> ANSIColors:
- if colorize or can_colorize():
+def get_colors(colorize: bool = False, *, file=None) -> ANSIColors:
+ if colorize or can_colorize(file=file):
return ANSIColors()
else:
return NoColors
-def can_colorize() -> bool:
+def can_colorize(*, file=None) -> bool:
+ if file is None:
+ file = sys.stdout
+
if not sys.flags.ignore_environment:
if os.environ.get("PYTHON_COLORS") == "0":
return False
if os.environ.get("TERM") == "dumb":
return False
- if not hasattr(sys.stderr, "fileno"):
+ if not hasattr(file, "fileno"):
return False
if sys.platform == "win32":
return False
try:
- return os.isatty(sys.stderr.fileno())
+ return os.isatty(file.fileno())
except io.UnsupportedOperation:
- return sys.stderr.isatty()
+ return file.isatty()
save_displayhook = sys.displayhook
sys.displayhook = sys.__displayhook__
saved_can_colorize = _colorize.can_colorize
- _colorize.can_colorize = lambda: False
+ _colorize.can_colorize = lambda *args, **kwargs: False
color_variables = {"PYTHON_COLORS": None, "FORCE_COLOR": None}
for key in color_variables:
color_variables[key] = os.environ.pop(key, None)
from .os_helper import EnvironmentVarGuard
with (
- swap_attr(_colorize, "can_colorize", lambda: False),
+ swap_attr(_colorize, "can_colorize", lambda file=None: False),
EnvironmentVarGuard() as env,
):
for var in {"FORCE_COLOR", "NO_COLOR", "PYTHON_COLORS"}:
def setUpModule():
- _colorize.can_colorize = lambda: False
+ _colorize.can_colorize = lambda *args, **kwargs: False
def tearDownModule():
def test_colorized_detection_checks_for_environment_variables(self):
flags = unittest.mock.MagicMock(ignore_environment=False)
with (unittest.mock.patch("os.isatty") as isatty_mock,
+ unittest.mock.patch("sys.stdout") as stdout_mock,
unittest.mock.patch("sys.stderr") as stderr_mock,
unittest.mock.patch("sys.flags", flags),
unittest.mock.patch("_colorize.can_colorize", ORIGINAL_CAN_COLORIZE),
contextlib.nullcontext()) as vt_mock):
isatty_mock.return_value = True
+ stdout_mock.fileno.return_value = 1
+ stdout_mock.isatty.return_value = True
stderr_mock.fileno.return_value = 2
stderr_mock.isatty.return_value = True
with unittest.mock.patch("os.environ", {'TERM': 'dumb'}):
self.assertEqual(_colorize.can_colorize(), True)
isatty_mock.return_value = False
+ stdout_mock.isatty.return_value = False
stderr_mock.isatty.return_value = False
self.assertEqual(_colorize.can_colorize(), False)
def _print_exception_bltin(exc, /):
file = sys.stderr if sys.stderr is not None else sys.__stderr__
- colorize = _colorize.can_colorize()
+ colorize = _colorize.can_colorize(file=file)
return print_exception(exc, limit=BUILTIN_EXCEPTION_LIMIT, file=file, colorize=colorize)
--- /dev/null
+Default to stdout isatty for color detection instead of stderr. Patch by
+Hugo van Kemenade.