Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions src/click/_termui_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,12 @@ def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, Non
yield stream
finally:
stream.flush()
# MaybeStripAnsi wraps an existing buffer (e.g. sys.stdout.buffer).
# io.TextIOWrapper takes ownership of the buffer and closes it on
# GC, which would silently close sys.stdout. Detach first so the
# buffer is not closed when this wrapper is collected.
if isinstance(stream, MaybeStripAnsi):
stream.detach()


@contextlib.contextmanager
Expand Down
13 changes: 13 additions & 0 deletions tests/test_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -747,3 +747,16 @@ def cli() -> None:
# Click output is not leaking into Pytest.
assert "inside-stdout" not in captured.out
assert "inside-stderr" not in captured.err


def test_echo_via_pager_in_cli_runner() -> None:
"""CliRunner should not get 'I/O operation on closed file' after echo_via_pager."""

@click.command()
def cli() -> None:
click.echo_via_pager("Hello, pager!")

runner = CliRunner()
result = runner.invoke(cli)
assert result.exit_code == 0
assert "Hello, pager!" in result.output
Loading