Added progressbar function.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 3a0aacb · Browse files · 4 files·+296 added−1 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+296 added−1 removed
- other:+296 added−1 removed
Provenance
- Commit
64d7fcf- Tree
ca31eba- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
3a0aacb
4 files changed+296 added−1 removed
modified:click/__init__.py+3 added-1 removed
30 unmodified lines31 from .utils import echo, get_binary_stream, get_text_stream, \32 format_filename, get_app_dir33 34 # Terminal functions35-from .termui import prompt, confirm, get_terminal_size, echo_via_pager35+from .termui import prompt, confirm, get_terminal_size, echo_via_pager, \36+ progressbar37 38 # Exceptions39 from .exceptions import ClickException, UsageError, BadParameter, \40 FileError, Abort24 unmodified lines65 'get_app_dir',66 67 # Terminal functions68 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',69+ 'progressbar',70 71 # Exceptions72 'ClickException', 'UsageError', 'BadParameter', 'FileError',73 'Abort',7 unmodified linesmodified:click/_compat.py+2 added
114 unmodified lines115 bytes = str116 raw_input = raw_input117 string_types = (str, unicode)118 iteritems = lambda x: x.iteritems()119+ range_type = xrange120 121 _identifier_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')122 123 # For Windows we need to force stdout/stdin/stderr to binary if it's48 unmodified lines172 import io173 text_type = str174 raw_input = input175 string_types = (str,)176+ range_type = range177 isidentifier = lambda x: x.isidentifier()178 iteritems = lambda x: iter(x.items())179 180 def _is_binary_reader(stream, default=False):260 unmodified linesadded:click/_termui_impl.py+225 added
1+"""2+ click._termui_impl3+ ~~~~~~~~~~~~~~~~~~4+5+ This module contains implementations for the termui module. To keep the6+ import time of click down some infrequently used functionality is placed7+ in this module and only imported as needed.8+9+ :copyright: (c) 2014 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+import os13+import time14+import math15+from ._compat import get_text_stdout, range_type, PY216+from .utils import echo17+18+19+if os.name == 'nt':20+ BEFORE_BAR = '\r'21+ AFTER_BAR = '\n'22+else:23+ BEFORE_BAR = '\r\033[?25l'24+ AFTER_BAR = '\033[?25h\n'25+26+27+def _length_hint(obj):28+ """Returns the length hint of an object."""29+ try:30+ return len(obj)31+ except TypeError:32+ try:33+ get_hint = type(obj).__length_hint__34+ except AttributeError:35+ return None36+ try:37+ hint = get_hint(obj)38+ except TypeError:39+ return None40+ if hint is NotImplemented or \41+ not isinstance(hint, (int, long)) or \42+ hint < 0:43+ return None44+ return hint45+46+47+class ProgressBar(object):48+49+ def __init__(self, iterable, length=None, fill_char='#', empty_char=' ',50+ bar_template='%(bar)s', info_sep=' ', show_eta=True,51+ show_percent=None, show_pos=None, label=None, file=None,52+ width=30):53+ self.fill_char = fill_char54+ self.empty_char = empty_char55+ self.bar_template = bar_template56+ self.info_sep = info_sep57+ self.show_eta = show_eta58+ self.show_percent = show_percent59+ self.show_pos = show_pos60+ self.label = label or ''61+ if file is None:62+ file = get_text_stdout()63+ self.file = file64+ self.width = width65+66+ if length is None:67+ length = _length_hint(iterable)68+ if iterable is None:69+ if length is None:70+ raise TypeError('iterable or length is required')71+ iterable = range_type(length)72+ self.iter = iter(iterable)73+ self.length = length74+ self.length_known = length is not None75+ self.pos = 076+ self.avg = []77+ self.start = self.last_eta = time.time()78+ self.eta_known = False79+ self.finished = False80+ self.max_width = None81+ self.entered = False82+83+ try:84+ self.is_hidden = not self.file.isatty()85+ except Exception:86+ self.is_hidden = True87+88+ def __enter__(self):89+ self.entered = True90+ return self91+92+ def __exit__(self, exc_type, exc_value, tb):93+ self.render_finish()94+95+ def __iter__(self):96+ if not self.entered:97+ raise RuntimeError('You need to use progress bars in a with block.')98+ self.render_progress()99+ return self100+101+ def render_finish(self):102+ if self.is_hidden:103+ return104+ self.file.write(AFTER_BAR)105+ self.file.flush()106+107+ @property108+ def pct(self):109+ if self.finished:110+ return 1.0111+ return min(self.pos / (float(self.length) or 1), 1.0)112+113+ @property114+ def time_per_iteration(self):115+ if not self.avg:116+ return 0.0117+ return sum(self.avg) / float(len(self.avg))118+119+ @property120+ def eta(self):121+ if self.length_known and not self.finished:122+ return self.time_per_iteration * (self.length - self.pos)123+ return 0.0124+125+ def format_eta(self):126+ if self.eta_known:127+ return time.strftime('%H:%M:%S', time.gmtime(self.eta + 1))128+ return ''129+130+ def format_pos(self):131+ pos = str(self.pos)132+ if self.length_known:133+ pos += '/%s' % self.length134+ return pos135+136+ def format_pct(self):137+ return ('% 4d%%' % int(self.pct * 100))[1:]138+139+ def format_progress_line(self):140+ show_percent = self.show_percent141+ show_pos = self.show_pos142+143+ info_bits = []144+ if self.length_known:145+ bar = self.fill_char * int(self.pct * self.width)146+ bar += self.empty_char * (self.width - len(bar))147+ if show_percent is None:148+ show_percent = not show_pos149+ else:150+ if self.finished:151+ bar = self.fill_char * self.width152+ else:153+ bar = list(self.empty_char * self.width)154+ if self.time_per_iteration != 0:155+ bar[int((math.cos(self.pos * self.time_per_iteration)156+ / 2.0 + 0.5) * len(bar))] = self.fill_char157+ bar = ''.join(bar)158+ if show_pos is None:159+ show_pos = True160+161+ if show_pos:162+ info_bits.append(self.format_pos())163+ if show_percent:164+ info_bits.append(self.format_pct())165+ if self.show_eta and self.eta_known and not self.finished:166+ info_bits.append(self.format_eta())167+168+ return (self.bar_template % {169+ 'label': self.label,170+ 'bar': bar,171+ 'info': self.info_sep.join(info_bits)172+ }).strip()173+174+ def render_progress(self):175+ if self.is_hidden:176+ echo(self.label, file=self.file)177+ self.file.flush()178+ return179+180+ clear_width = self.width181+ if self.max_width is not None:182+ clear_width = self.max_width183+ self.file.write(BEFORE_BAR)184+ line = self.format_progress_line()185+ line_len = len(line)186+ if self.max_width is None or self.max_width < line_len:187+ self.max_width = line_len188+ self.file.write(line)189+ self.file.write(' ' * (clear_width - line_len))190+ self.file.flush()191+192+ def make_step(self):193+ self.pos += 1194+ if self.length_known and self.pos >= self.length:195+ self.finished = True196+197+ if (time.time() - self.last_eta) < 1.0:198+ return199+200+ self.last_eta = time.time()201+ self.avg = self.avg[-6:] + [-(self.start - time.time()) / (self.pos)]202+203+ self.eta_known = self.length_known204+205+ def finish(self):206+ self.eta_known = 0207+ self.finished = True208+209+ def next(self):210+ if self.is_hidden:211+ return next(self.iter)212+ try:213+ rv = next(self.iter)214+ except StopIteration:215+ self.finish()216+ self.render_progress()217+ raise218+ else:219+ self.make_step()220+ self.render_progress()221+ return rv222+223+ if not PY2:224+ __next__ = next225+ del nextmodified:click/termui.py+66 added
179 unmodified lines180 # I don't feel like reimplementing it given that it works on Python 2181 # and seems reasonably stable otherwise.182 import pydoc183 pydoc.pager(text)184+185+186+def progressbar(iterable=None, length=None, label=None, show_eta=True,187+ show_percent=None, show_pos=None, fill_char='#',188+ empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s',189+ info_sep=' ', width=36, file=None):190+ """This function creates an iterable context manager that can be used191+ to iterate over something while showing a progress bar. It will192+ either iterate over the `iterable` or `length` items (that are counted193+ up). While iteration happens this function will print a rendered194+ progress bar to the given `file` (defaults to stdout) and will attempt195+ to calculate remaining time and more. By default this progress bar196+ will not be rendered if the file is not a terminal.197+198+ The context manager creates the progress bar. When the context199+ manager is entered the progress bar is already displayed. With every200+ iteration over the progress bar the iterable passed to the bar is201+ advanced and the bar is updated. When the context manager is exited202+ a newline is printed and the progress bar is finalized on screen.203+204+ No printing must happen or the progress bar will be unintentionally205+ destroyed.206+207+ Example usage::208+209+ with progressbar(items) as bar:210+ for item in bar:211+ do_something_with(item)212+213+ :param iterable: an iterable to iterate over. If not provided the length214+ is required.215+ :param length: the number of items to iterate over. By default the216+ progressbar will attempt to ask the iterator about it's217+ length with might or might not work. If an iterable is218+ also provided this parameter can be used to override the219+ length. If an iterable is not provided the progress bar220+ will iterate over a range of that length.221+ :param label: the label to show next to the progress bar.222+ :param show_eta: enables or disables the estimated time display. This is223+ automatically disabled if the length cannot be224+ determined.225+ :param show_percent: enables or disables the percentage display. The226+ default is `True` if the iterable has a length or227+ `False` if not.228+ :param show_pos: enables or disables the absolute position display. The229+ deafult is `False` if the iterable has a length or230+ `True` if not.231+ :param fill_char: the character to use to show the filled part of the232+ progress bar.233+ :param empty_char: the character to use to show the non filled part of234+ the progress bar.235+ :param bar_template: the format string to use as template for the bar.236+ The parameters in it are ``label`` for the label,237+ ``bar`` for the progress bar and ``info`` for the238+ info section.239+ :param info_sep: the separator between multiple info items (eta etc.)240+ :param width: the width of the progress bar in characters.241+ :param file: the file to write to. If this is not a terminal then242+ only the label is printed.243+ """244+ from ._termui_impl import ProgressBar245+ return ProgressBar(iterable=iterable, length=length, show_eta=show_eta,246+ show_percent=show_percent, show_pos=show_pos,247+ fill_char=fill_char, empty_char=empty_char,248+ bar_template=bar_template, info_sep=info_sep,249+ file=file, label=label, width=width)