diff --git a/Lib/_colorize.py b/Lib/_colorize.py index 5f44a3aa05eb8f6..4427d5ee2fe0e5e 100644 --- a/Lib/_colorize.py +++ b/Lib/_colorize.py @@ -603,6 +603,8 @@ def _safe_getenv(k: str, fallback: str | None = None) -> str | None: return os.isatty(file.fileno()) except OSError: return hasattr(file, "isatty") and file.isatty() + except ValueError: + return False default_theme = Theme() diff --git a/Lib/test/test__colorize.py b/Lib/test/test__colorize.py index c7bc6914ac1bc44..788c68562cabd47 100644 --- a/Lib/test/test__colorize.py +++ b/Lib/test/test__colorize.py @@ -187,6 +187,11 @@ def test_colorized_detection_checks_for_file(self): file.isatty.return_value = False self.assertEqual(_colorize.can_colorize(file=file), False) + # gh-157581: A closed file raises ValueError from fileno(). + file = unittest.mock.Mock() + file.fileno.side_effect = ValueError + self.assertFalse(_colorize.can_colorize(file=file)) + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Library/2026-09-15-21-12-02.gh-issue-157581.qJEepi.rst b/Misc/NEWS.d/next/Library/2026-09-15-21-12-02.gh-issue-157581.qJEepi.rst new file mode 100644 index 000000000000000..3cb829b65e624ee --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-09-15-21-12-02.gh-issue-157581.qJEepi.rst @@ -0,0 +1 @@ +Updated :func:``!_colorize.can_colorize`` to not raise when given a closed file stream. \ No newline at end of file