Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-128595: Default to stdout isatty for colour detection instead of stderr #128498

Merged
merged 18 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions Lib/_colorize.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,20 @@ class ANSIColors:
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 file is None:
file = sys.stdout

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
Expand All @@ -49,7 +55,7 @@ def can_colorize() -> bool:
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":
Expand All @@ -62,6 +68,6 @@ def can_colorize() -> bool:
return False

try:
return os.isatty(sys.stderr.fileno())
return os.isatty(file.fileno())
except io.UnsupportedOperation:
return sys.stderr.isatty()
return sys.stdout.isatty()
2 changes: 1 addition & 1 deletion Lib/doctest.py
Original file line number Diff line number Diff line change
Expand Up @@ -1558,7 +1558,7 @@ def out(s):
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)
Expand Down
4 changes: 2 additions & 2 deletions Lib/test/libregrtest/single.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def test_func():
def _runtest_env_changed_exc(result: TestResult, runtests: RunTests,
display_failure: bool = True) -> None:
# Handle exceptions, detect environment changes.
ansi = get_colors()
ansi = get_colors(file=sys.stderr)
red, reset, yellow = ansi.RED, ansi.RESET, ansi.YELLOW

# Reset the environment_altered flag to detect if a test altered
Expand Down Expand Up @@ -303,7 +303,7 @@ def run_single_test(test_name: TestName, runtests: RunTests) -> TestResult:
If runtests.use_junit, xml_data is a list containing each generated
testsuite element.
"""
ansi = get_colors()
ansi = get_colors(file=sys.stderr)
red, reset, yellow = ansi.BOLD_RED, ansi.RESET, ansi.YELLOW

start_time = time.perf_counter()
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/support/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2839,7 +2839,7 @@ def no_color():
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"}:
Expand Down
2 changes: 1 addition & 1 deletion Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def print_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \

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)


Expand Down
3 changes: 2 additions & 1 deletion Lib/unittest/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,8 @@ def _exc_info_to_string(self, err, test):
capture_locals=self.tb_locals, compact=True)
from _colorize import can_colorize

msgLines = list(tb_e.format(colorize=can_colorize()))
file = self.stream if hasattr(self, "stream") else None
msgLines = list(tb_e.format(colorize=can_colorize(file=file)))

if self.buffer:
output = sys.stdout.getvalue()
Expand Down
6 changes: 4 additions & 2 deletions Lib/unittest/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ def __init__(self, stream, descriptions, verbosity, *, durations=None):
self.showAll = verbosity > 1
self.dots = verbosity == 1
self.descriptions = descriptions
self._ansi = get_colors()
file = sys.stderr if stream == "<stderr>" else None
self._ansi = get_colors(file=file)
self._newline = True
self.durations = durations

Expand Down Expand Up @@ -286,7 +287,8 @@ def run(self, test):
expected_fails, unexpected_successes, skipped = results

infos = []
ansi = get_colors()
file = sys.stderr if self.stream == "<stderr>" else None
ansi = get_colors(file=file)
bold_red = ansi.BOLD_RED
green = ansi.GREEN
red = ansi.RED
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Default to stdout isatty for colour detection instead of stderr. Patch by
Hugo van Kemenade.
Loading