Skip to content
Myr

Do not let the GC close a borrowed `stdout`

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Complete the "I/O operation on closed file" fix from #3482, and definitely addresses #3449.

authored by Kevin Deldycke · committed by Kevin Deldycke · parent cd9bdd9 · Browse files · 4 files+112 added−27 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+112 added−27 removed

  • tests:+56 added−0 removed
  • other:+56 added−27 removed

4 files+112 added−27 removed

modified:src/click/_termui_impl.py+40 added-27 removed
27 unmodified lines
28from ._compat import term_len29from ._compat import WIN30from .exceptions import ClickException31from .utils import echo32from .utils import KeepOpenFile3334V = t.TypeVar("V")3536
404 unmodified lines
441 """442 with _pager_contextmanager(color=color) as (stream, encoding, color):443 # Split streams by capabilities rather than the abstract TextIO /444 # BinaryIO annotations: buffered text streams can be unwrapped to bytes,444 # while text-only streams are yielded as-is.445 # while other streams are yielded as-is.446 wrapper: MaybeStripAnsi | None = None447 if _has_binary_buffer(stream):448 # Text stream backed by a binary buffer.447 stream = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)448 elif isinstance(stream, t.BinaryIO):449 # Binary stream450 stream = MaybeStripAnsi(stream, color=color, encoding=encoding)449 wrapper = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)450 stream = wrapper451 try:452 yield stream452 # Narrow the BinaryIO | TextIO union that _pager_contextmanager453 # yields; the caller writes text to the pager.454 yield t.cast(t.TextIO, stream)455 finally:456 try:454 stream.flush()457 stream.flush()458 finally:459 # Hand the binary buffer back to the pager that produced it460 # rather than letting this TextIOWrapper close it on garbage461 # collection. The pager owns the buffer's lifecycle: subprocess462 # pipes and temp files are closed by their own helpers, while a463 # borrowed stdout must stay open for the caller. detach() runs464 # even if flush() raised, so the buffer is never closed here.465 if wrapper is not None:466 wrapper.detach()467468469@contextlib.contextmanager470def _pipepager(
11 unmodified lines
482 automatically.483 """484 # Split the command into the invoked CLI and its parameters.485 if not cmd_parts:486 # No usable pager: fall back to stdout through _nullpager so it gets the487 # same borrowed-stream handling and the caller's stream is not closed.488 stdout = _default_text_stdout() or StringIO()475 yield stdout, "utf-8", False489 with _nullpager(stdout, color) as rv:490 yield rv491 return492493 import shutil494
1 unmodified line
496 cmd_params = cmd_parts[1:]497498 cmd_filepath = shutil.which(cmd)499 if not cmd_filepath:500 # No usable pager: fall back to stdout through _nullpager so it gets the501 # same borrowed-stream handling and the caller's stream is not closed.502 stdout = _default_text_stdout() or StringIO()486 yield stdout, "utf-8", False503 with _nullpager(stdout, color) as rv:504 yield rv505 return506507 # Produces a normalized absolute path string.508 # multi-call binaries such as busybox derive their identity from the symlink
79 unmodified lines
588 :func:`shutil.which`.589 """590 # Split the command into the invoked CLI and its parameters.591 if not cmd_parts:592 # No usable pager: fall back to stdout through _nullpager so it gets the593 # same borrowed-stream handling and the caller's stream is not closed.594 stdout = _default_text_stdout() or StringIO()575 yield stdout, "utf-8", False595 with _nullpager(stdout, color) as rv:596 yield rv597 return598599 import shutil600 import subprocess
1 unmodified line
602 cmd = cmd_parts[0]603604 cmd_filepath = shutil.which(cmd)605 if not cmd_filepath:606 # No usable pager: fall back to stdout through _nullpager so it gets the607 # same borrowed-stream handling and the caller's stream is not closed.608 stdout = _default_text_stdout() or StringIO()586 yield stdout, "utf-8", False609 with _nullpager(stdout, color) as rv:610 yield rv611 return612613 # Produces a normalized absolute path string.614 # multi-call binaries such as busybox derive their identity from the symlink
17 unmodified lines
632 finally:633 os.unlink(f.name)634635612class _SkipClose:613 def __init__(self, stream: t.IO[t.Any]) -> None:614 self.stream = stream615616 def __getattr__(self, name: str) -> t.Any:617 return getattr(self.stream, name)618619 @property620 def buffer(self) -> t.BinaryIO:621 return _SkipClose(self.stream.buffer) # type: ignore[attr-defined, return-value]622623 def close(self) -> None:624 pass625626636@contextlib.contextmanager637def _nullpager(638 stream: t.TextIO, color: bool | None = None639) -> t.Iterator[tuple[t.TextIO, str, bool]]:640 """Simply print unformatted text. This is the ultimate fallback. Don't close the641 output stream in this case, since it's coming from elsewhere rather than our642 internal helpers.643644 The stream is wrapped in :class:`~click.utils.KeepOpenFile` so that, as a645 borrowed stream, it is not closed by a ``with`` block. The wrapper that646 :func:`get_pager_file` builds around it is detached rather than closed.647 """648 encoding = get_best_encoding(stream)649650 if color is None:651 color = False652640 yield _SkipClose(stream), encoding, color # type: ignore[misc]653 yield KeepOpenFile(stream), encoding, color # type: ignore[misc]654655656class Editor:657 def __init__(
288 unmodified lines
modified:src/click/utils.py+12 added
203 unmodified lines
204 return iter(self._f) # type: ignore205206207class KeepOpenFile:208 """Proxy a file object but keep it open across a ``with`` block.209210 Wraps a borrowed file (such as ``sys.stdin`` or ``sys.stdout``) so that211 leaving a ``with`` block does not close it, as used by :func:`open_file`212 for the ``-`` filename. The caller stays responsible for the file: an213 explicit :meth:`close` still passes through to the wrapped object.214215 Dunder methods are proxied explicitly: implicit special-method lookups216 bypass :meth:`__getattr__`, because Python resolves them on the type rather217 than the instance.218 """219220 _file: t.IO[t.Any]221222 def __init__(self, file: t.IO[t.Any]) -> None:223 self._file = file
430 unmodified lines
modified:tests/test_termui.py+56 added
1import contextlib2import gc3import io4import platform5import shlex6import shutil
799 unmodified lines
806807 assert pager_out.read_text(encoding="utf-8") == "hello\n"808809810def test_get_pager_file_missing_pager_keeps_borrowed_stream_open(monkeypatch):811 """A missing ``PAGER`` must not close the borrowed stdout (issue #3449).812813 The ``8.4.0`` regression was only fixed for the no-tty ``_nullpager`` path;814 the ``_pipepager``/``_tempfilepager`` fallbacks (reached in a tty when815 ``PAGER`` resolves to nothing) used to close the borrowed stream too.816 """817 buffer = io.BytesIO()818 stream = io.TextIOWrapper(buffer, encoding="utf-8")819820 monkeypatch.setitem(821 click._termui_impl.os.environ,822 "PAGER",823 "click-tests-nonexistent-pager-9b3f2",824 )825 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)826 monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)827828 with click.get_pager_file() as pager:829 pager.write("hello\n")830831 # Drop the wrapper reference and force finalization: the old bug closed the832 # borrowed buffer when the TextIOWrapper built by get_pager_file was833 # garbage-collected.834 del pager835 gc.collect()836837 assert not buffer.closed838 assert not stream.closed839 assert buffer.getvalue().replace(b"\r\n", b"\n") == b"hello\n"840841842def test_echo_via_pager_tty_pager_missing(runner, monkeypatch):843 """``echo_via_pager`` through the tty fallback keeps ``CliRunner`` working.844845 Regression for issue #3449 via the pager fallback: a tty with ``PAGER``846 pointing at a missing binary used to close the runner's stdout, breaking847 ``CliRunner.invoke``.848 """849 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)850 monkeypatch.setitem(851 click._termui_impl.os.environ,852 "PAGER",853 "click-tests-nonexistent-pager-9b3f2",854 )855856 @click.command()857 def cli():858 click.echo_via_pager("Hello, Click!")859860 result = runner.invoke(cli)861 assert not result.exception862 assert result.output == "Hello, Click!\n"863864865@pytest.mark.parametrize(866 ("color", "expected"),867 [868 pytest.param(False, "hello\n", id="strip ansi"),
694 unmodified lines
modified:CHANGES.rst+4 added
15 unmodified lines
16 :issue:`3059` :pr:`3507`17- ``echo_via_pager`` flushes after each write, so passing a generator streams18 output to the pager incrementally instead of staying hidden until the pipe19 buffer fills. :issue:`3242` :issue:`2542` :pr:`3534`20- ``echo_via_pager`` and ``get_pager_file`` no longer close a borrowed stdout21 stream when no external pager runs, completing the partial22 ``I/O operation on closed file`` fix from :pr:`3482`. :issue:`3449`23 :pr:`3533`242526Version 8.4.127-------------
1478 unmodified lines