Skip to content
Myr

Implement streaming pager. Fixes #409

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

The streaming pager works using generators. You can pass a generator function or object into echo_via_pager: generator expression: ``` click.echo_via_pager(("{}\n".format(i) for i in range(999999))) ``` generator function / expression: ``` def gen(): counter = 0 while True: counter++ yield counter click.echo_via_pager(gen) click.echo_via_pager(gen()) # you can pass both ```

authored by Steffen Neubauer · committed by Steffen Neubauer · parent 7eb990f · Browse files · 4 files+80 added−28 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+80 added−28 removed

  • tests:+25 added−3 removed
  • other:+55 added−25 removed

4 files+80 added−28 removed

modified:click/_termui_impl.py+26 added-20 removed
11 unmodified lines
12import os13import sys14import time15import math1617from ._compat import _default_text_stdout, range_type, PY2, isatty, \18 open_stream, strip_ansi, term_len, get_best_encoding, WIN, int_types, \19 CYGWIN20from .utils import echo
251 unmodified lines
272 __next__ = next273 del next274275275def pager(text, color=None):276def pager(generator, color=None):277 """Decide what method to use for paging through text."""278 stdout = _default_text_stdout()279 if not isatty(sys.stdin) or not isatty(stdout):279 return _nullpager(stdout, text, color)280 return _nullpager(stdout, generator, color)281 pager_cmd = (os.environ.get('PAGER', None) or '').strip()282 if pager_cmd:283 if WIN:283 return _tempfilepager(text, pager_cmd, color)284 return _pipepager(text, pager_cmd, color)284 return _tempfilepager(generator, pager_cmd, color)285 return _pipepager(generator, pager_cmd, color)286 if os.environ.get('TERM') in ('dumb', 'emacs'):286 return _nullpager(stdout, text, color)287 return _nullpager(stdout, generator, color)288 if WIN or sys.platform.startswith('os2'):288 return _tempfilepager(text, 'more <', color)289 return _tempfilepager(generator, 'more <', color)290 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:290 return _pipepager(text, 'less', color)291 return _pipepager(generator, 'less', color)292293 import tempfile294 fd, filename = tempfile.mkstemp()295 os.close(fd)296 try:297 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:297 return _pipepager(text, 'more', color)298 return _nullpager(stdout, text, color)298 return _pipepager(generator, 'more', color)299 return _nullpager(stdout, generator, color)300 finally:301 os.unlink(filename)302303303def _pipepager(text, cmd, color):304def _pipepager(generator, cmd, color):305 """Page through text by feeding it to another program. Invoking a306 pager through this might support colors.307 """308 import subprocess
9 unmodified lines
318 color = True319 elif 'r' in less_flags or 'R' in less_flags:320 color = True321321 if not color:322 text = strip_ansi(text)323322 c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,323 env=env)324 encoding = get_best_encoding(c.stdin)325 try:328 c.stdin.write(text.encode(encoding, 'replace'))329 c.stdin.close()326 for text in generator:327 if not color:328 text = strip_ansi(text)329330 c.stdin.write(text.encode(encoding, 'replace'))331 except (IOError, KeyboardInterrupt):332 pass333 else:334 c.stdin.close()335336 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting337 # search or other commands inside less).338 #
10 unmodified lines
349 else:350 break351352350def _tempfilepager(text, cmd, color):353def _tempfilepager(generator, cmd, color):354 """Page through text by invoking a program on a temporary file."""355 import tempfile356 filename = tempfile.mktemp()357 # TODO: This never terminates if the passed generator never terminates.358 text = "".join(generator)359 if not color:360 text = strip_ansi(text)361 encoding = get_best_encoding(sys.stdout)362 with open_stream(filename, 'wb')[0] as f:
3 unmodified lines
366 finally:367 os.unlink(filename)368369365def _nullpager(stream, text, color):370def _nullpager(stream, generator, color):371 """Simply print unformatted text. This is the ultimate fallback."""372 for text in generator:367 if not color:368 text = strip_ansi(text)369 stream.write(text)373 if not color:374 text = strip_ansi(text)375 stream.write(text)376377378class Editor(object):379
183 unmodified lines
modified:click/termui.py+18 added-5 removed
1import os2import sys3import struct4import inspect5import itertools67from ._compat import raw_input, text_type, string_types, \8 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN9from .utils import echo
194 unmodified lines
204 os.environ.get('COLUMNS', DEFAULT_COLUMNS))205 return int(cr[1]), int(cr[0])206207206def echo_via_pager(text, color=None):208def echo_via_pager(text_or_generator, color=None):209 """This function takes a text and shows it via an environment specific210 pager on stdout.211212 .. versionchanged:: 3.0213 Added the `color` flag.214213 :param text: the text to page.215 :param text_or_generator: the text to page, or alternatively, a216 generator emitting the text to page.217 :param color: controls if the pager supports ANSI colors or not. The218 default is autodetection.219 """220 color = resolve_color_default(color)218 if not isinstance(text, string_types):219 text = text_type(text)221222 if inspect.isgeneratorfunction(text_or_generator):223 i = text_or_generator()224 elif isinstance(text_or_generator, string_types):225 i = [text_or_generator]226 else:227 i = iter(text_or_generator)228229 # convert every element of i to a text type if necessary230 text_generator = (el if isinstance(el, string_types) else text_type(el)231 for el in i)232233 from ._termui_impl import pager221 return pager(text + '\n', color)234 return pager(itertools.chain(text_generator, "\n"), color)235236237def progressbar(iterable=None, length=None, label=None, show_eta=True,238 show_percent=None, show_pos=False,
324 unmodified lines
modified:docs/utils.rst+11 added
112 unmodified lines
113 def less():114 click.echo_via_pager('\n'.join('Line %d' % idx115 for idx in range(200)))116117If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string:118119.. click:example::120 def _generate_output():121 for idx in range(50000):122 yield "Line %d\n" % idx123124 @click.command()125 def less():126 click.echo_via_pager(_generate_output())127128129Screen Clearing130---------------131132.. versionadded:: 2.0
277 unmodified lines
modified:tests/test_utils.py+25 added-3 removed
144 unmodified lines
145 out, err = capsys.readouterr()146 assert out == 'Password: \nScrew you.\n'147148149def _test_gen_func():150 yield 'a'151 yield 'b'152 yield 'c'153 yield 'abc'154155156@pytest.mark.skipif(WIN, reason='Different behavior on windows.')157@pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])158@pytest.mark.parametrize('test', [159 # We need lambda here, because pytest will160 # reuse the parameters, and then the generators161 # are already used and will not yield anymore162 ('just text\n', lambda: 'just text'),163 ('iterable\n', lambda: ["itera", "ble"]),164 ('abcabc\n', lambda: _test_gen_func),165 ('abcabc\n', lambda: _test_gen_func()),166 ('012345\n', lambda: (c for c in range(6))),167])151def test_echo_via_pager(monkeypatch, capfd, cat):168def test_echo_via_pager(monkeypatch, capfd, cat, test):169 monkeypatch.setitem(os.environ, 'PAGER', cat)170 monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)171172 expected_output = test[0]173 test_input = test[1]()174154 click.echo_via_pager('haha')175 click.echo_via_pager(test_input)176177 out, err = capfd.readouterr()156 assert out == 'haha\n'178 assert out == expected_output179180181@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')182def test_echo_color_flag(monkeypatch, capfd):
123 unmodified lines