Repository: Textualize/rich
Pull request #2678 (2022-11-30 09:54:14)

robust handling of fileno
More robust handling of `fileno()` which is often implemented badly in proxies and wrappers.

Should fix https://github.com/Textualize/rich/issues/2645


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 89fd9787..1dcab064 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,9 +12,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 - Bumped minimum Python version to 3.7 https://github.com/Textualize/rich/pull/2567
 - Pretty-printing of "tagged" `__repr__` results is now greedy when matching tags https://github.com/Textualize/rich/pull/2565
 
+### Fixed
+
+- Handling of broken `fileno` made more robust. Fixes https://github.com/Textualize/rich/issues/2645
+
 ### Added
+
 - Add type annotation for key_separator of pretty.Node https://github.com/Textualize/rich/issues/2625
 
+
 ## [12.6.0] - 2022-10-02
 
 ### Added
diff --git a/rich/_fileno.py b/rich/_fileno.py
new file mode 100644
index 00000000..b17ee651
--- /dev/null
+++ b/rich/_fileno.py
@@ -0,0 +1,24 @@
+from __future__ import annotations
+
+from typing import IO, Callable
+
+
+def get_fileno(file_like: IO[str]) -> int | None:
+    """Get fileno() from a file, accounting for poorly implemented file-like objects.
+
+    Args:
+        file_like (IO): A file-like object.
+
+    Returns:
+        int | None: The result of fileno if available, or None if operation failed.
+    """
+    fileno: Callable[[], int] | None = getattr(file_like, "fileno", None)
+    if fileno is not None:
+        try:
+            return fileno()
+        except Exception:
+            # `fileno` is documented as potentially raising a OSError
+            # Alas, from the issues, there are so many poorly implemented file-like objects,
+            # that `fileno()` can raise just about anything.
+            return None
+    return None
diff --git a/rich/console.py b/rich/console.py
index 36537216..c59f0d77 100644
--- a/rich/console.py
+++ b/rich/console.py
@@ -1,5 +1,4 @@
 import inspect
-import io
 import os
 import platform
 import sys
@@ -48,6 +47,7 @@ else:
 from . import errors, themes
 from ._emoji_replace import _emoji_replace
 from ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT
+from ._fileno import get_fileno
 from ._log_render import FormatTimeCallable, LogRender
 from .align import Align, AlignMethod
 from .color import ColorSystem, blend_rgb
@@ -2006,12 +2006,11 @@ class Console:
                     if WINDOWS:
                         use_legacy_windows_render = False
                         if self.legacy_windows:
-                            try:
+                            fileno = get_fileno(self.file)
+                            if fileno is not None:
                                 use_legacy_windows_render = (
-                                    self.file.fileno() in _STD_STREAMS_OUTPUT
+                                    fileno in _STD_STREAMS_OUTPUT
                                 )
-                            except (ValueError, io.UnsupportedOperation):
-                                pass
 
                         if use_legacy_windows_render:
                             from rich._win32_console import LegacyWindowsTerm


Test patch:
diff --git a/tests/test_getfileno.py b/tests/test_getfileno.py
new file mode 100644
index 00000000..7f664ddb
--- /dev/null
+++ b/tests/test_getfileno.py
@@ -0,0 +1,25 @@
+from rich._fileno import get_fileno
+
+
+def test_get_fileno():
+    class FileLike:
+        def fileno(self) -> int:
+            return 123
+
+    assert get_fileno(FileLike()) == 123
+
+
+def test_get_fileno_missing():
+    class FileLike:
+        pass
+
+    assert get_fileno(FileLike()) is None
+
+
+def test_get_fileno_broken():
+    class FileLike:
+        def fileno(self) -> int:
+            1 / 0
+            return 123
+
+    assert get_fileno(FileLike()) is None