Skip to content
Myr

Add file-like pager: `click.get_pager_file()` (#1572)

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

authored by Craig de Stigter · committed by GitHub · parent c5cced7 · Browse files · 7 files+136 added−72 removed
This commit

State

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

Trailers

  • Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>

Diff stats

7 files+136 added−72 removed

  • other:+136 added−72 removed

7 files+136 added−72 removed

modified:docs/api.md+4 added
71 unmodified lines
72.. autofunction:: echo_via_pager73```7475```{eval-rst}76.. autofunction:: get_pager_file77```7879```{eval-rst}80.. autofunction:: prompt81```8283```{eval-rst}
274 unmodified lines
modified:docs/utils.md+13 added
108 unmodified lines
109 def less():110 click.echo_via_pager(_generate_output())111```112113For more complex programs, which can't easily use a simple generator, you114can get access to a writable file-like object for the pager, and write to115that instead:116117```{eval-rst}118.. click:example::119 @click.command()120 def less():121 with click.get_pager_file() as pager:122 for idx in range(50000):123 print(idx, file=pager)124```125126## Screen Clearing127128```{versionadded} 2.0129```
276 unmodified lines
modified:src/click/__init__.py+1 added
40 unmodified lines
41from .termui import clear as clear42from .termui import confirm as confirm43from .termui import echo_via_pager as echo_via_pager44from .termui import edit as edit45from .termui import get_pager_file as get_pager_file46from .termui import getchar as getchar47from .termui import launch as launch48from .termui import pause as pause49from .termui import progressbar as progressbar
76 unmodified lines
modified:src/click/_compat.py+4 added
500 unmodified lines
501) -> bool:502 if color is None:503 if stream is None:504 stream = sys.stdin505 elif hasattr(stream, "color"):506 # ._termui_impl.MaybeStripAnsi handles stripping ansi itself,507 # so we don't need to strip it here508 return False509 return not isatty(stream) and not _is_jupyter_kernel_output(stream)510 return not color511512
114 unmodified lines
modified:src/click/_termui_impl.py+90 added-68 removed
6 unmodified lines
7from __future__ import annotations89import collections.abc as cabc10import contextlib11import io12import math13import os14import shlex15import sys
7 unmodified lines
23from ._compat import _default_text_stdout24from ._compat import CYGWIN25from ._compat import get_best_encoding26from ._compat import isatty26from ._compat import open_stream27from ._compat import strip_ansi28from ._compat import term_len29from ._compat import WIN30from .exceptions import ClickException
334 unmodified lines
365 self.finish()366 self.render_progress()367368369def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:369class MaybeStripAnsi(io.TextIOWrapper):370 def __init__(self, stream: t.IO[bytes], *, color: bool, **kwargs: t.Any):371 super().__init__(stream, **kwargs)372 self.color = color373374 def write(self, text: str) -> int:375 if not self.color:376 text = strip_ansi(text)377 return super().write(text)378379380def _pager_contextmanager(381 color: bool | None = None,382) -> t.ContextManager[tuple[t.BinaryIO | t.TextIO, str, bool]]:383 """Decide what method to use for paging through text."""384 stdout = _default_text_stdout()385386 # There are no standard streams attached to write to. For example,
1 unmodified line
388 if stdout is None:389 stdout = StringIO()390391 if not isatty(sys.stdin) or not isatty(stdout):379 return _nullpager(stdout, generator, color)392 return _nullpager(stdout, color)393394 # Split using POSIX mode (the default) so that quote characters are395 # stripped from tokens and quoted Windows paths are preserved.396 # Non-POSIX mode retains quotes in tokens, and wrapping tokens397 # with shlex.quote re-introduces quoting issues on Windows.398 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))399 if pager_cmd_parts:400 if WIN:388 if _tempfilepager(generator, pager_cmd_parts, color):389 return390 elif _pipepager(generator, pager_cmd_parts, color):391 return401 return _tempfilepager(pager_cmd_parts, color)402 return _pipepager(pager_cmd_parts, color)403404 if os.environ.get("TERM") in ("dumb", "emacs"):394 return _nullpager(stdout, generator, color)395 if (WIN or sys.platform.startswith("os2")) and _tempfilepager(396 generator, ["more"], color397 ):398 return399 if _pipepager(generator, ["less"], color):400 return405 return _nullpager(stdout, color)406 if WIN or sys.platform.startswith("os2"):407 return _tempfilepager(["more"], color)408 return _pipepager(["less"], color)409402 import tempfile410404 fd, filename = tempfile.mkstemp()405 os.close(fd)406 try:407 if _pipepager(generator, ["more"], color):408 return409 return _nullpager(stdout, generator, color)410 finally:411 os.unlink(filename)411@contextlib.contextmanager412def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:413 """Context manager.414 Yields a writable file-like object which can be used as an output pager.415 .. versionadded:: 8.2416 :param color: controls if the pager supports ANSI colors or not. The417 default is autodetection.418 """419 with _pager_contextmanager(color=color) as (stream, encoding, color):420 if not isinstance(stream, MaybeStripAnsi):421 if hasattr(stream, "buffer"):422 # Real TextIO with buffer - unwrap and wrap in MaybeStripAnsi423 stream = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)424 elif not getattr(stream, "encoding", None):425 # BinaryIO - wrap directly in MaybeStripAnsi426 stream = MaybeStripAnsi(stream, color=color, encoding=encoding)427 else:428 # StringIO - add .color attribute only, no ANSI stripping429 stream.color = color # type: ignore[attr-defined]430 try:431 yield t.cast(t.TextIO, stream)432 finally:433 stream.flush()434435436@contextlib.contextmanager437def _pipepager(415 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None416) -> bool:438 cmd_parts: list[str], color: bool | None = None439) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:440 """Page through text by feeding it to another program.441442 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list443 produced by :func:`shlex.split`. The command is resolved to an absolute
2 unmodified lines
446447 Invoking a pager through this might support colors: if piping to448 ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set449 automatically.427428 Returns ``True`` if the command was found and executed, ``False``429 otherwise so another pager can be attempted.450 """451 # Split the command into the invoked CLI and its parameters.452 if not cmd_parts:453 stdout = _default_text_stdout() or StringIO()454 yield stdout, "utf-8", False433 return False455 return456457 import shutil458459 cmd = cmd_parts[0]460 cmd_params = cmd_parts[1:]461462 cmd_filepath = shutil.which(cmd)463 if not cmd_filepath:464 stdout = _default_text_stdout() or StringIO()465 yield stdout, "utf-8", False442 return False466 return467468 # Produces a normalized absolute path string.469 # multi-call binaries such as busybox derive their identity from the symlink470 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)
14 unmodified lines
485 color = True486 elif "r" in less_flags or "R" in less_flags:487 color = True488489 if color is None:490 color = False491492 c = subprocess.Popen(493 [str(cmd_path)] + cmd_params,494 shell=False,495 stdin=subprocess.PIPE,496 env=env,497 errors="replace",498 text=True,499 )473 assert c.stdin is not None500 stdin = t.cast(t.BinaryIO, c.stdin)501 encoding = get_best_encoding(stdin)502 try:475 for text in generator:476 if not color:477 text = strip_ansi(text)478479 c.stdin.write(text)503 yield stdin, encoding, color504 except BrokenPipeError:505 # In case the pager exited unexpectedly, ignore the broken pipe error.506 pass507 except Exception as e:
5 unmodified lines
513 raise e514 finally:515 # We must close stdin and wait for the pager to exit before we continue516 try:493 c.stdin.close()517 stdin.close()518 # Close implies flush, so it might throw a BrokenPipeError if the pager519 # process exited already.520 except BrokenPipeError:521 pass
13 unmodified lines
535 pass536 else:537 break538515 return True539517540@contextlib.contextmanager541def _tempfilepager(519 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None520) -> bool:542 cmd_parts: list[str], color: bool | None = None543) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:544 """Page through text by invoking a program on a temporary file.545546 Used as the primary pager strategy on Windows (where piping to547 ``more`` adds spurious ``\\r\\n``), and as a fallback on other548 platforms. The command is resolved to an absolute path with549 :func:`shutil.which`.527528 Returns ``True`` if the command was found and executed, ``False``529 otherwise so another pager can be attempted.550 """551 # Split the command into the invoked CLI and its parameters.552 if not cmd_parts:553 stdout = _default_text_stdout() or StringIO()554 yield stdout, "utf-8", False533 return False555 return556557 import shutil558 import subprocess559560 cmd = cmd_parts[0]561562 cmd_filepath = shutil.which(cmd)563 if not cmd_filepath:564 stdout = _default_text_stdout() or StringIO()565 yield stdout, "utf-8", False541 return False566 return567568 # Produces a normalized absolute path string.569 # multi-call binaries such as busybox derive their identity from the symlink570 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)571 cmd_path = Path(cmd_filepath).absolute()572547 import subprocess573 import tempfile574550 fd, filename = tempfile.mkstemp()551 # TODO: This never terminates if the passed generator never terminates.552 text = "".join(generator)553 if not color:554 text = strip_ansi(text)575 encoding = get_best_encoding(sys.stdout)556 with open_stream(filename, "wb")[0] as f:557 f.write(text.encode(encoding))576 if color is None:577 color = False578 # On Windows, NamedTemporaryFile cannot be opened by another process579 # while Python still has it open, so we use delete=False and clean up manually580 # rather than using a contextmanager here.581 f = tempfile.NamedTemporaryFile(mode="wb", delete=False)582 try:559 subprocess.call([str(cmd_path), filename])560 except OSError:561 # Command not found562 pass583 yield t.cast(t.BinaryIO, f), encoding, color584 f.flush()585 f.close()586 subprocess.call([str(cmd_path), f.name])587 finally:564 os.close(fd)565 os.unlink(filename)588 os.unlink(f.name)589567 return True590569591@contextlib.contextmanager592def _nullpager(571 stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None572) -> None:593 stream: t.TextIO, color: bool | None = None594) -> t.Iterator[tuple[t.TextIO, str, bool]]:595 """Simply print unformatted text. This is the ultimate fallback."""574 for text in generator:575 if not color:576 text = strip_ansi(text)577 stream.write(text)596 encoding = get_best_encoding(stream)597 if color is None:598 color = False599 yield stream, encoding, color600601602class Editor:603 def __init__(
288 unmodified lines
modified:src/click/termui.py+22 added-4 removed
276 unmodified lines
277 raise Abort()278 return rv279280281def get_pager_file(282 color: bool | None = None,283) -> t.ContextManager[t.TextIO]:284 """Context manager.285286 Yields a writable file-like object which can be used as an output pager.287288 .. versionadded:: 8.2289290 :param color: controls if the pager supports ANSI colors or not. The291 default is autodetection.292 """293 from ._termui_impl import get_pager_file294295 color = resolve_color_default(color)296297 return get_pager_file(color=color)298299300def echo_via_pager(301 text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,302 color: bool | None = None,303) -> None:
7 unmodified lines
311 generator emitting the text to page.312 :param color: controls if the pager supports ANSI colors or not. The313 default is autodetection.314 """296 color = resolve_color_default(color)315316 if inspect.isgeneratorfunction(text_or_generator):317 i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()318 elif isinstance(text_or_generator, str):
3 unmodified lines
322323 # convert every element of i to a text type if necessary324 text_generator = (el if isinstance(el, str) else str(el) for el in i)325308 from ._termui_impl import pager326 with get_pager_file(color=color) as pager:327 for text in itertools.chain(text_generator, "\n"):328 pager.write(text)329310 return pager(itertools.chain(text_generator, "\n"), color)330312331@t.overload332def progressbar(333 *,334 length: int,
587 unmodified lines
modified:CHANGES.rst+2 added
256 unmodified lines
257 - ``echo_via_pager`` will not ignore ``KeyboardInterrupt`` anymore. This258 allows the user to search for future output of the generator when259 using less and then aborting the program using ctrl-c.260261- Add ``click.get_pager_file`` for file-like access to an output262 pager. :pr:`1572`263- ``deprecated: bool | str`` can now be used on options and arguments. This264 previously was only available for ``Command``. The message can now also be265 customised by using a ``str`` instead of a ``bool``. :issue:`2263` :pr:`2271`266
1151 unmodified lines