Merge pull request #889 from stefreak/master
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Implement streaming pager. Fixes #409
authored by Dan Sully · committed by GitHub · parents da4a508, 6ca05be · 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
Provenance
- Commit
b1b4449- Tree
6ce8f13- Author
Dan Sully <daniel-github@electricrain.com>- Committer
GitHub <noreply@github.com>- Parent 1
da4a508- Parent 2
6ca05be
4 files changed+80 added−28 removed
modified:click/_termui_impl.py+26 added-20 removed
11 unmodified lines12 import os13 import sys14 import time15 import math16+17 from ._compat import _default_text_stdout, range_type, PY2, isatty, \18 open_stream, strip_ansi, term_len, get_best_encoding, WIN, int_types, \19 CYGWIN20 from .utils import echo248 unmodified lines269 __next__ = next270 del next271 272 272-def pager(text, color=None):273+def pager(generator, color=None):274 """Decide what method to use for paging through text."""275 stdout = _default_text_stdout()276 if not isatty(sys.stdin) or not isatty(stdout):276- return _nullpager(stdout, text, color)277+ return _nullpager(stdout, generator, color)278 pager_cmd = (os.environ.get('PAGER', None) or '').strip()279 if pager_cmd:280 if WIN:280- return _tempfilepager(text, pager_cmd, color)281- return _pipepager(text, pager_cmd, color)281+ return _tempfilepager(generator, pager_cmd, color)282+ return _pipepager(generator, pager_cmd, color)283 if os.environ.get('TERM') in ('dumb', 'emacs'):283- return _nullpager(stdout, text, color)284+ return _nullpager(stdout, generator, color)285 if WIN or sys.platform.startswith('os2'):285- return _tempfilepager(text, 'more <', color)286+ return _tempfilepager(generator, 'more <', color)287 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:287- return _pipepager(text, 'less', color)288+ return _pipepager(generator, 'less', color)289 290 import tempfile291 fd, filename = tempfile.mkstemp()292 os.close(fd)293 try:294 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:294- return _pipepager(text, 'more', color)295- return _nullpager(stdout, text, color)295+ return _pipepager(generator, 'more', color)296+ return _nullpager(stdout, generator, color)297 finally:298 os.unlink(filename)299 300 300-def _pipepager(text, cmd, color):301+def _pipepager(generator, cmd, color):302 """Page through text by feeding it to another program. Invoking a303 pager through this might support colors.304 """305 import subprocess9 unmodified lines315 color = True316 elif 'r' in less_flags or 'R' in less_flags:317 color = True318 318- if not color:319- text = strip_ansi(text)320-319 c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,320 env=env)321 encoding = get_best_encoding(c.stdin)322 try:325- c.stdin.write(text.encode(encoding, 'replace'))326- c.stdin.close()323+ for text in generator:324+ if not color:325+ text = strip_ansi(text)326+327+ c.stdin.write(text.encode(encoding, 'replace'))328 except (IOError, KeyboardInterrupt):329 pass330+ else:331+ c.stdin.close()332 333 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting334 # search or other commands inside less).335 #10 unmodified lines346 else:347 break348 349 347-def _tempfilepager(text, cmd, color):350+def _tempfilepager(generator, cmd, color):351 """Page through text by invoking a program on a temporary file."""352 import tempfile353 filename = tempfile.mktemp()354+ # TODO: This never terminates if the passed generator never terminates.355+ text = "".join(generator)356 if not color:357 text = strip_ansi(text)358 encoding = get_best_encoding(sys.stdout)359 with open_stream(filename, 'wb')[0] as f:3 unmodified lines363 finally:364 os.unlink(filename)365 366 362-def _nullpager(stream, text, color):367+def _nullpager(stream, generator, color):368 """Simply print unformatted text. This is the ultimate fallback."""369+ for text in generator:364- if not color:365- text = strip_ansi(text)366- stream.write(text)370+ if not color:371+ text = strip_ansi(text)372+ stream.write(text)373 374 375 class Editor(object):376 183 unmodified linesmodified:click/termui.py+18 added-5 removed
1 import os2 import sys3 import struct4+import inspect5+import itertools6 7 from ._compat import raw_input, text_type, string_types, \8 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN9 from .utils import echo194 unmodified lines204 os.environ.get('COLUMNS', DEFAULT_COLUMNS))205 return int(cr[1]), int(cr[0])206 207 206-def echo_via_pager(text, color=None):208+def echo_via_pager(text_or_generator, color=None):209 """This function takes a text and shows it via an environment specific210 pager on stdout.211 212 .. versionchanged:: 3.0213 Added the `color` flag.214 213- :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)221+222+ 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)228+229+ # 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)232+233 from ._termui_impl import pager221- return pager(text + '\n', color)234+ return pager(itertools.chain(text_generator, "\n"), color)235 236 237 def progressbar(iterable=None, length=None, label=None, show_eta=True,238 show_percent=None, show_pos=False,324 unmodified linesmodified:docs/utils.rst+11 added
112 unmodified lines113 def less():114 click.echo_via_pager('\n'.join('Line %d' % idx115 for idx in range(200)))116 117+If 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:118 119+.. click:example::120+ def _generate_output():121+ for idx in range(50000):122+ yield "Line %d\n" % idx123+124+ @click.command()125+ def less():126+ click.echo_via_pager(_generate_output())127+128+129 Screen Clearing130 ---------------131 132 .. versionadded:: 2.0277 unmodified linesmodified:tests/test_utils.py+25 added-3 removed
144 unmodified lines145 out, err = capsys.readouterr()146 assert out == 'Password: \nScrew you.\n'147 148 149+def _test_gen_func():150+ yield 'a'151+ yield 'b'152+ yield 'c'153+ yield 'abc'154+155+156 @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+])151-def test_echo_via_pager(monkeypatch, capfd, cat):168+def 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)171+172+ expected_output = test[0]173+ test_input = test[1]()174+154- click.echo_via_pager('haha')175+ click.echo_via_pager(test_input)176+177 out, err = capfd.readouterr()156- assert out == 'haha\n'178+ assert out == expected_output179 180 181 @pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')182 def test_echo_color_flag(monkeypatch, capfd):124 unmodified lines