Incremental GSC parsing (exact copy of the tutorials shared as a separate project) / tqdm / _tqdm.py
1576 views"""1Customisable progressbar decorator for iterators.2Includes a default (x)range iterator printing to stderr.34Usage:5>>> from tqdm import trange[, tqdm]6>>> for i in trange(10): #same as: for i in tqdm(xrange(10))7... ...8"""9from __future__ import absolute_import10# future division is important to divide integers and get as11# a result precise floating numbers (instead of truncated int)12from __future__ import division13# import compatibility functions and utilities14from ._utils import _supports_unicode, _environ_cols_wrapper, _range, _unich, \15_term_move_up, _unicode, WeakSet16import sys17from time import time181920__author__ = {"github.com/": ["noamraph", "obiwanus", "kmike", "hadim",21"casperdcl", "lrq3000"]}22__all__ = ['tqdm', 'trange',23'TqdmTypeError', 'TqdmKeyError', 'TqdmDeprecationWarning']242526class TqdmTypeError(TypeError):27pass282930class TqdmKeyError(KeyError):31pass323334class TqdmDeprecationWarning(Exception):35# not suppressed if raised36def __init__(self, msg, fp_write=None, *a, **k):37if fp_write is not None:38fp_write("\nTqdmDeprecationWarning: " + str(msg).rstrip() + '\n')39else:40super(TqdmDeprecationWarning, self).__init__(msg, *a, **k)414243class tqdm(object):44"""45Decorate an iterable object, returning an iterator which acts exactly46like the original iterable, but prints a dynamically updating47progressbar every time a value is requested.48"""49@staticmethod50def format_sizeof(num, suffix=''):51"""52Formats a number (greater than unity) with SI Order of Magnitude53prefixes.5455Parameters56----------57num : float58Number ( >= 1) to format.59suffix : str, optional60Post-postfix [default: ''].6162Returns63-------64out : str65Number with Order of Magnitude SI unit postfix.66"""67for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:68if abs(num) < 999.95:69if abs(num) < 99.95:70if abs(num) < 9.995:71return '{0:1.2f}'.format(num) + unit + suffix72return '{0:2.1f}'.format(num) + unit + suffix73return '{0:3.0f}'.format(num) + unit + suffix74num /= 1000.075return '{0:3.1f}Y'.format(num) + suffix7677@staticmethod78def format_interval(t):79"""80Formats a number of seconds as a clock time, [H:]MM:SS8182Parameters83----------84t : int85Number of seconds.86Returns87-------88out : str89[H:]MM:SS90"""91mins, s = divmod(int(t), 60)92h, m = divmod(mins, 60)93if h:94return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s)95else:96return '{0:02d}:{1:02d}'.format(m, s)9798@staticmethod99def status_printer(file):100"""101Manage the printing and in-place updating of a line of characters.102Note that if the string is longer than a line, then in-place103updating may not work (it will print a new line at each refresh).104"""105fp = file106fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover107108def fp_write(s):109fp.write(_unicode(s))110fp_flush()111112last_len = [0]113114def print_status(s):115len_s = len(s)116fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))117last_len[0] = len_s118return print_status119120@staticmethod121def format_meter(n, total, elapsed, ncols=None, prefix='',122ascii=False, unit='it', unit_scale=False, rate=None,123bar_format=None):124"""125Return a string-based progress bar given some parameters126127Parameters128----------129n : int130Number of finished iterations.131total : int132The expected total number of iterations. If meaningless (), only133basic progress statistics are displayed (no ETA).134elapsed : float135Number of seconds passed since start.136ncols : int, optional137The width of the entire output message. If specified,138dynamically resizes the progress meter to stay within this bound139[default: None]. The fallback meter width is 10 for the progress140bar + no limit for the iterations counter and statistics. If 0,141will not print any meter (only stats).142prefix : str, optional143Prefix message (included in total width) [default: ''].144ascii : bool, optional145If not set, use unicode (smooth blocks) to fill the meter146[default: False]. The fallback is to use ASCII characters147(1-9 #).148unit : str, optional149The iteration unit [default: 'it'].150unit_scale : bool, optional151If set, the number of iterations will printed with an152appropriate SI metric prefix (K = 10^3, M = 10^6, etc.)153[default: False].154rate : float, optional155Manual override for iteration rate.156If [default: None], uses n/elapsed.157bar_format : str, optional158Specify a custom bar string formatting. May impact performance.159[default: '{l_bar}{bar}{r_bar}'], where l_bar is160'{desc}{percentage:3.0f}%|' and r_bar is161'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}]'162Possible vars: bar, n, n_fmt, total, total_fmt, percentage,163rate, rate_fmt, elapsed, remaining, l_bar, r_bar, desc.164165Returns166-------167out : Formatted meter and stats, ready to display.168"""169170# sanity check: total171if total and n > total:172total = None173174format_interval = tqdm.format_interval175elapsed_str = format_interval(elapsed)176177# if unspecified, attempt to use rate = average speed178# (we allow manual override since predicting time is an arcane art)179if rate is None and elapsed:180rate = n / elapsed181inv_rate = 1 / rate if (rate and (rate < 1)) else None182format_sizeof = tqdm.format_sizeof183rate_fmt = ((format_sizeof(inv_rate if inv_rate else rate)184if unit_scale else185'{0:5.2f}'.format(inv_rate if inv_rate else rate))186if rate else '?') \187+ ('s' if inv_rate else unit) + '/' + (unit if inv_rate else 's')188189if unit_scale:190n_fmt = format_sizeof(n)191total_fmt = format_sizeof(total) if total else None192else:193n_fmt = str(n)194total_fmt = str(total)195196# total is known: we can predict some stats197if total:198# fractional and percentage progress199frac = n / total200percentage = frac * 100201202remaining_str = format_interval((total - n) / rate) \203if rate else '?'204205# format the stats displayed to the left and right sides of the bar206l_bar = (prefix if prefix else '') + \207'{0:3.0f}%|'.format(percentage)208r_bar = '| {0}/{1} [{2}<{3}, {4}]'.format(209n_fmt, total_fmt, elapsed_str, remaining_str, rate_fmt)210211if ncols == 0:212return l_bar[:-1] + r_bar[1:]213214if bar_format:215# Custom bar formatting216# Populate a dict with all available progress indicators217bar_args = {'n': n,218'n_fmt': n_fmt,219'total': total,220'total_fmt': total_fmt,221'percentage': percentage,222'rate': rate if inv_rate is None else inv_rate,223'rate_noinv': rate,224'rate_noinv_fmt': ((format_sizeof(rate)225if unit_scale else226'{0:5.2f}'.format(rate))227if rate else '?') + unit + '/s',228'rate_fmt': rate_fmt,229'elapsed': elapsed_str,230'remaining': remaining_str,231'l_bar': l_bar,232'r_bar': r_bar,233'desc': prefix if prefix else '',234# 'bar': full_bar # replaced by procedure below235}236237# Interpolate supplied bar format with the dict238if '{bar}' in bar_format:239# Format left/right sides of the bar, and format the bar240# later in the remaining space (avoid breaking display)241l_bar_user, r_bar_user = bar_format.split('{bar}')242l_bar = l_bar_user.format(**bar_args)243r_bar = r_bar_user.format(**bar_args)244else:245# Else no progress bar, we can just format and return246return bar_format.format(**bar_args)247248# Formatting progress bar249# space available for bar's display250N_BARS = max(1, ncols - len(l_bar) - len(r_bar)) if ncols \251else 10252253# format bar depending on availability of unicode/ascii chars254if ascii:255bar_length, frac_bar_length = divmod(256int(frac * N_BARS * 10), 10)257258bar = '#' * bar_length259frac_bar = chr(48 + frac_bar_length) if frac_bar_length \260else ' '261262else:263bar_length, frac_bar_length = divmod(int(frac * N_BARS * 8), 8)264265bar = _unich(0x2588) * bar_length266frac_bar = _unich(0x2590 - frac_bar_length) \267if frac_bar_length else ' '268269# whitespace padding270if bar_length < N_BARS:271full_bar = bar + frac_bar + \272' ' * max(N_BARS - bar_length - 1, 0)273else:274full_bar = bar + \275' ' * max(N_BARS - bar_length, 0)276277# Piece together the bar parts278return l_bar + full_bar + r_bar279280# no total: no progressbar, ETA, just progress stats281else:282return (prefix if prefix else '') + '{0}{1} [{2}, {3}]'.format(283n_fmt, unit, elapsed_str, rate_fmt)284285def __new__(cls, *args, **kwargs):286# Create a new instance287instance = object.__new__(cls)288# Add to the list of instances289if "_instances" not in cls.__dict__:290cls._instances = WeakSet()291cls._instances.add(instance)292# Return the instance293return instance294295@classmethod296def _get_free_pos(cls, instance=None):297""" Skips specified instance """298try:299return max(inst.pos for inst in cls._instances300if inst is not instance) + 1301except ValueError as e:302if "arg is an empty sequence" in str(e):303return 0304raise # pragma: no cover305306@classmethod307def _decr_instances(cls, instance):308"""309Remove from list and reposition other bars310so that newer bars won't overlap previous bars311"""312try: # in case instance was explicitly positioned, it won't be in set313cls._instances.remove(instance)314for inst in cls._instances:315if inst.pos > instance.pos:316inst.pos -= 1317except KeyError:318pass319320@classmethod321def write(cls, s, file=sys.stdout, end="\n"):322"""323Print a message via tqdm (without overlap with bars)324"""325fp = file326327# Clear all bars328inst_cleared = []329for inst in getattr(cls, '_instances', []):330# Clear instance if in the target output file331# or if write output + tqdm output are both either332# sys.stdout or sys.stderr (because both are mixed in terminal)333if inst.fp == fp or all(f in (sys.stdout, sys.stderr)334for f in (fp, inst.fp)):335inst.clear()336inst_cleared.append(inst)337# Write the message338fp.write(s)339fp.write(end)340# Force refresh display of bars we cleared341for inst in inst_cleared:342inst.refresh()343# TODO: make list of all instances incl. absolutely positioned ones?344345@classmethod346def pandas(tclass, *targs, **tkwargs):347"""348Registers the given `tqdm` class with349pandas.core.350( frame.DataFrame351| series.Series352| groupby.DataFrameGroupBy353| groupby.SeriesGroupBy354).progress_apply355356A new instance will be create every time `progress_apply` is called,357and each instance will automatically close() upon completion.358359Parameters360----------361targs, tkwargs : arguments for the tqdm instance362363Examples364--------365>>> import pandas as pd366>>> import numpy as np367>>> from tqdm import tqdm, tqdm_gui368>>>369>>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))370>>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc371>>> # Now you can use `progress_apply` instead of `apply`372>>> df.groupby(0).progress_apply(lambda x: x**2)373374References375----------376https://stackoverflow.com/questions/18603270/377progress-indicator-during-pandas-operations-python378"""379from pandas.core.frame import DataFrame380from pandas.core.series import Series381from pandas.core.groupby import DataFrameGroupBy382from pandas.core.groupby import SeriesGroupBy383from pandas.core.groupby import GroupBy384from pandas.core.groupby import PanelGroupBy385from pandas import Panel386387deprecated_t = [tkwargs.pop('deprecated_t', None)]388389def inner_generator(df_function='apply'):390def inner(df, func, *args, **kwargs):391"""392Parameters393----------394df : (DataFrame|Series)[GroupBy]395Data (may be grouped).396func : function397To be applied on the (grouped) data.398*args, *kwargs : optional399Transmitted to `df.apply()`.400"""401# Precompute total iterations402total = getattr(df, 'ngroups', None)403if total is None: # not grouped404total = len(df) if isinstance(df, Series) \405else df.size // len(df)406else:407total += 1 # pandas calls update once too many408409# Init bar410if deprecated_t[0] is not None:411t = deprecated_t[0]412deprecated_t[0] = None413else:414t = tclass(*targs, total=total, **tkwargs)415416# Define bar updating wrapper417def wrapper(*args, **kwargs):418t.update()419return func(*args, **kwargs)420421# Apply the provided function (in *args and **kwargs)422# on the df using our wrapper (which provides bar updating)423result = getattr(df, df_function)(wrapper, *args, **kwargs)424425# Close bar and return pandas calculation result426t.close()427return result428return inner429430# Monkeypatch pandas to provide easy methods431# Enable custom tqdm progress in pandas!432Series.progress_apply = inner_generator()433SeriesGroupBy.progress_apply = inner_generator()434Series.progress_map = inner_generator('map')435SeriesGroupBy.progress_map = inner_generator('map')436437DataFrame.progress_apply = inner_generator()438DataFrameGroupBy.progress_apply = inner_generator()439DataFrame.progress_applymap = inner_generator('applymap')440441Panel.progress_apply = inner_generator()442PanelGroupBy.progress_apply = inner_generator()443444GroupBy.progress_apply = inner_generator()445GroupBy.progress_aggregate = inner_generator('aggregate')446GroupBy.progress_transform = inner_generator('transform')447448def __init__(self, iterable=None, desc=None, total=None, leave=True,449file=sys.stderr, ncols=None, mininterval=0.1,450maxinterval=10.0, miniters=None, ascii=None, disable=False,451unit='it', unit_scale=False, dynamic_ncols=False,452smoothing=0.3, bar_format=None, initial=0, position=None,453gui=False, **kwargs):454"""455Parameters456----------457iterable : iterable, optional458Iterable to decorate with a progressbar.459Leave blank to manually manage the updates.460desc : str, optional461Prefix for the progressbar.462total : int, optional463The number of expected iterations. If unspecified,464len(iterable) is used if possible. As a last resort, only basic465progress statistics are displayed (no ETA, no progressbar).466If `gui` is True and this parameter needs subsequent updating,467specify an initial arbitrary large positive integer,468e.g. int(9e9).469leave : bool, optional470If [default: True], keeps all traces of the progressbar471upon termination of iteration.472file : `io.TextIOWrapper` or `io.StringIO`, optional473Specifies where to output the progress messages474[default: sys.stderr]. Uses `file.write(str)` and `file.flush()`475methods.476ncols : int, optional477The width of the entire output message. If specified,478dynamically resizes the progressbar to stay within this bound.479If unspecified, attempts to use environment width. The480fallback is a meter width of 10 and no limit for the counter and481statistics. If 0, will not print any meter (only stats).482mininterval : float, optional483Minimum progress update interval, in seconds [default: 0.1].484maxinterval : float, optional485Maximum progress update interval, in seconds [default: 10.0].486miniters : int, optional487Minimum progress update interval, in iterations.488If specified, will set `mininterval` to 0.489ascii : bool, optional490If unspecified or False, use unicode (smooth blocks) to fill491the meter. The fallback is to use ASCII characters `1-9 #`.492disable : bool, optional493Whether to disable the entire progressbar wrapper494[default: False].495unit : str, optional496String that will be used to define the unit of each iteration497[default: it].498unit_scale : bool, optional499If set, the number of iterations will be reduced/scaled500automatically and a metric prefix following the501International System of Units standard will be added502(kilo, mega, etc.) [default: False].503dynamic_ncols : bool, optional504If set, constantly alters `ncols` to the environment (allowing505for window resizes) [default: False].506smoothing : float, optional507Exponential moving average smoothing factor for speed estimates508(ignored in GUI mode). Ranges from 0 (average speed) to 1509(current/instantaneous speed) [default: 0.3].510bar_format : str, optional511Specify a custom bar string formatting. May impact performance.512If unspecified, will use '{l_bar}{bar}{r_bar}', where l_bar is513'{desc}{percentage:3.0f}%|' and r_bar is514'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}]'515Possible vars: bar, n, n_fmt, total, total_fmt, percentage,516rate, rate_fmt, elapsed, remaining, l_bar, r_bar, desc.517initial : int, optional518The initial counter value. Useful when restarting a progress519bar [default: 0].520position : int, optional521Specify the line offset to print this bar (starting from 0)522Automatic if unspecified.523Useful to manage multiple bars at once (eg, from threads).524gui : bool, optional525WARNING: internal parameter - do not use.526Use tqdm_gui(...) instead. If set, will attempt to use527matplotlib animations for a graphical output [default: False].528529Returns530-------531out : decorated iterator.532"""533if disable:534self.iterable = iterable535self.disable = disable536self.pos = self._get_free_pos(self)537self._instances.remove(self)538return539540if kwargs:541self.disable = True542self.pos = self._get_free_pos(self)543self._instances.remove(self)544raise (TqdmDeprecationWarning("""\545`nested` is deprecated and automated. Use position instead for manual control.546""", fp_write=getattr(file, 'write', sys.stderr.write))547if "nested" in kwargs else548TqdmKeyError("Unknown argument(s): " + str(kwargs)))549550# Preprocess the arguments551if total is None and iterable is not None:552try:553total = len(iterable)554except (TypeError, AttributeError):555total = None556557if ((ncols is None) and (file in (sys.stderr, sys.stdout))) or \558dynamic_ncols: # pragma: no cover559if dynamic_ncols:560dynamic_ncols = _environ_cols_wrapper()561ncols = dynamic_ncols(file)562else:563ncols = _environ_cols_wrapper()(file)564565if miniters is None:566miniters = 0567dynamic_miniters = True568else:569dynamic_miniters = False570571if mininterval is None:572mininterval = 0573574if maxinterval is None:575maxinterval = 0576577if ascii is None:578ascii = not _supports_unicode(file)579580if bar_format and not ascii:581# Convert bar format into unicode since terminal uses unicode582bar_format = _unicode(bar_format)583584if smoothing is None:585smoothing = 0586587# Store the arguments588self.iterable = iterable589self.desc = desc + ': ' if desc else ''590self.total = total591self.leave = leave592self.fp = file593self.ncols = ncols594self.mininterval = mininterval595self.maxinterval = maxinterval596self.miniters = miniters597self.dynamic_miniters = dynamic_miniters598self.ascii = ascii599self.disable = disable600self.unit = unit601self.unit_scale = unit_scale602self.gui = gui603self.dynamic_ncols = dynamic_ncols604self.smoothing = smoothing605self.avg_time = None606self._time = time607self.bar_format = bar_format608609# Init the iterations counters610self.last_print_n = initial611self.n = initial612613# if nested, at initial sp() call we replace '\r' by '\n' to614# not overwrite the outer progress bar615self.pos = self._get_free_pos(self) if position is None else position616617if not gui:618# Initialize the screen printer619self.sp = self.status_printer(self.fp)620if self.pos:621self.moveto(self.pos)622self.sp(self.format_meter(self.n, total, 0,623(dynamic_ncols(file) if dynamic_ncols else ncols),624self.desc, ascii, unit, unit_scale, None, bar_format))625if self.pos:626self.moveto(-self.pos)627628# Init the time counter629self.start_t = self.last_print_t = self._time()630631def __len__(self):632return (self.iterable.shape[0] if hasattr(self.iterable, 'shape')633else len(self.iterable)) if self.iterable is not None \634else self.total635636def __enter__(self):637return self638639def __exit__(self, *exc):640self.close()641return False642643def __del__(self):644self.close()645646def __repr__(self):647return self.format_meter(self.n, self.total,648time() - self.last_print_t,649self.ncols, self.desc, self.ascii, self.unit,650self.unit_scale, 1 / self.avg_time651if self.avg_time else None, self.bar_format)652653def __lt__(self, other):654return self.pos < other.pos655656def __le__(self, other):657return (self < other) or (self == other)658659def __eq__(self, other):660return self.pos == other.pos661662def __ne__(self, other):663return not (self == other)664665def __gt__(self, other):666return not (self <= other)667668def __ge__(self, other):669return not (self < other)670671def __hash__(self):672return id(self)673674def __iter__(self):675''' Backward-compatibility to use: for x in tqdm(iterable) '''676677# Inlining instance variables as locals (speed optimisation)678iterable = self.iterable679680# If the bar is disabled, then just walk the iterable681# (note: keep this check outside the loop for performance)682if self.disable:683for obj in iterable:684yield obj685else:686ncols = self.ncols687mininterval = self.mininterval688maxinterval = self.maxinterval689miniters = self.miniters690dynamic_miniters = self.dynamic_miniters691unit = self.unit692unit_scale = self.unit_scale693ascii = self.ascii694start_t = self.start_t695last_print_t = self.last_print_t696last_print_n = self.last_print_n697n = self.n698dynamic_ncols = self.dynamic_ncols699smoothing = self.smoothing700avg_time = self.avg_time701bar_format = self.bar_format702_time = self._time703format_meter = self.format_meter704705try:706sp = self.sp707except AttributeError:708raise TqdmDeprecationWarning("""\709Please use `tqdm_gui(...)` instead of `tqdm(..., gui=True)`710""", fp_write=getattr(self.fp, 'write', sys.stderr.write))711712for obj in iterable:713yield obj714# Update and print the progressbar.715# Note: does not call self.update(1) for speed optimisation.716n += 1717# check the counter first (avoid calls to time())718if n - last_print_n >= miniters:719delta_t = _time() - last_print_t720if delta_t >= mininterval:721cur_t = _time()722delta_it = n - last_print_n723elapsed = cur_t - start_t724# EMA (not just overall average)725if smoothing and delta_t:726avg_time = delta_t / delta_it \727if avg_time is None \728else smoothing * delta_t / delta_it + \729(1 - smoothing) * avg_time730731if self.pos:732self.moveto(self.pos)733734# Printing the bar's update735sp(format_meter(736n, self.total, elapsed,737(dynamic_ncols(self.fp) if dynamic_ncols738else ncols),739self.desc, ascii, unit, unit_scale,7401 / avg_time if avg_time else None, bar_format))741742if self.pos:743self.moveto(-self.pos)744745# If no `miniters` was specified, adjust automatically746# to the maximum iteration rate seen so far.747if dynamic_miniters:748if maxinterval and delta_t > maxinterval:749# Set miniters to correspond to maxinterval750miniters = delta_it * maxinterval / delta_t751elif mininterval and delta_t:752# EMA-weight miniters to converge753# towards the timeframe of mininterval754miniters = smoothing * delta_it * mininterval \755/ delta_t + (1 - smoothing) * miniters756else:757miniters = smoothing * delta_it + \758(1 - smoothing) * miniters759760# Store old values for next call761self.n = self.last_print_n = last_print_n = n762self.last_print_t = last_print_t = cur_t763764# Closing the progress bar.765# Update some internal variables for close().766self.last_print_n = last_print_n767self.n = n768self.close()769770def update(self, n=1):771"""772Manually update the progress bar, useful for streams773such as reading files.774E.g.:775>>> t = tqdm(total=filesize) # Initialise776>>> for current_buffer in stream:777... ...778... t.update(len(current_buffer))779>>> t.close()780The last line is highly recommended, but possibly not necessary if781`t.update()` will be called in such a way that `filesize` will be782exactly reached and printed.783784Parameters785----------786n : int787Increment to add to the internal counter of iterations788[default: 1].789"""790if self.disable:791return792793if n < 0:794raise ValueError("n ({0}) cannot be negative".format(n))795self.n += n796797if self.n - self.last_print_n >= self.miniters:798# We check the counter first, to reduce the overhead of time()799delta_t = self._time() - self.last_print_t800if delta_t >= self.mininterval:801cur_t = self._time()802delta_it = self.n - self.last_print_n # should be n?803elapsed = cur_t - self.start_t804# EMA (not just overall average)805if self.smoothing and delta_t:806self.avg_time = delta_t / delta_it \807if self.avg_time is None \808else self.smoothing * delta_t / delta_it + \809(1 - self.smoothing) * self.avg_time810811if not hasattr(self, "sp"):812raise TqdmDeprecationWarning("""\813Please use `tqdm_gui(...)` instead of `tqdm(..., gui=True)`814""", fp_write=getattr(self.fp, 'write', sys.stderr.write))815816if self.pos:817self.moveto(self.pos)818819# Print bar's update820self.sp(self.format_meter(821self.n, self.total, elapsed,822(self.dynamic_ncols(self.fp) if self.dynamic_ncols823else self.ncols),824self.desc, self.ascii, self.unit, self.unit_scale,8251 / self.avg_time if self.avg_time else None,826self.bar_format))827828if self.pos:829self.moveto(-self.pos)830831# If no `miniters` was specified, adjust automatically to the832# maximum iteration rate seen so far.833# e.g.: After running `tqdm.update(5)`, subsequent834# calls to `tqdm.update()` will only cause an update after835# at least 5 more iterations.836if self.dynamic_miniters:837if self.maxinterval and delta_t > self.maxinterval:838self.miniters = self.miniters * self.maxinterval \839/ delta_t840elif self.mininterval and delta_t:841self.miniters = self.smoothing * delta_it \842* self.mininterval / delta_t + \843(1 - self.smoothing) * self.miniters844else:845self.miniters = self.smoothing * delta_it + \846(1 - self.smoothing) * self.miniters847848# Store old values for next call849self.last_print_n = self.n850self.last_print_t = cur_t851852def close(self):853"""854Cleanup and (if leave=False) close the progressbar.855"""856if self.disable:857return858859# Prevent multiple closures860self.disable = True861862# decrement instance pos and remove from internal set863pos = self.pos864self._decr_instances(self)865866# GUI mode867if not hasattr(self, "sp"):868return869870# annoyingly, _supports_unicode isn't good enough871def fp_write(s):872self.fp.write(_unicode(s))873874try:875fp_write('')876except ValueError as e:877if 'closed' in str(e):878return879raise # pragma: no cover880881if pos:882self.moveto(pos)883884if self.leave:885if self.last_print_n < self.n:886cur_t = self._time()887# stats for overall rate (no weighted average)888self.sp(self.format_meter(889self.n, self.total, cur_t - self.start_t,890(self.dynamic_ncols(self.fp) if self.dynamic_ncols891else self.ncols),892self.desc, self.ascii, self.unit, self.unit_scale, None,893self.bar_format))894if pos:895self.moveto(-pos)896else:897fp_write('\n')898else:899self.sp('') # clear up last bar900if pos:901self.moveto(-pos)902else:903fp_write('\r')904905def unpause(self):906"""907Restart tqdm timer from last print time.908"""909cur_t = self._time()910self.start_t += cur_t - self.last_print_t911self.last_print_t = cur_t912913def set_description(self, desc=None):914"""915Set/modify description of the progress bar.916"""917self.desc = desc + ': ' if desc else ''918919def moveto(self, n):920self.fp.write(_unicode('\n' * n + _term_move_up() * -n))921922def clear(self, nomove=False):923"""924Clear current bar display925"""926if not nomove:927self.moveto(self.pos)928# clear up the bar (can't rely on sp(''))929self.fp.write('\r')930self.fp.write(' ' * (self.ncols if self.ncols else 10))931self.fp.write('\r') # place cursor back at the beginning of line932if not nomove:933self.moveto(-self.pos)934935def refresh(self):936"""937Force refresh the display of this bar938"""939self.moveto(self.pos)940# clear up this line's content (whatever there was)941self.clear(nomove=True)942# Print current/last bar state943self.fp.write(self.__repr__())944self.moveto(-self.pos)945946947def trange(*args, **kwargs):948"""949A shortcut for tqdm(xrange(*args), **kwargs).950On Python3+ range is used instead of xrange.951"""952return tqdm(_range(*args), **kwargs)953954955