std.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  1. """
  2. Customisable progressbar decorator for iterators.
  3. Includes a default `range` iterator printing to `stderr`.
  4. Usage:
  5. >>> from tqdm import trange, tqdm
  6. >>> for i in trange(10):
  7. ... ...
  8. """
  9. import sys
  10. from collections import OrderedDict, defaultdict
  11. from contextlib import contextmanager
  12. from datetime import datetime, timedelta
  13. from numbers import Number
  14. from time import time
  15. from warnings import warn
  16. from weakref import WeakSet
  17. from ._monitor import TMonitor
  18. from .utils import (
  19. CallbackIOWrapper, Comparable, DisableOnWriteError, FormatReplace, SimpleTextIOWrapper,
  20. _is_ascii, _screen_shape_wrapper, _supports_unicode, _term_move_up, disp_len, disp_trim)
  21. __author__ = "https://github.com/tqdm/tqdm#contributions"
  22. __all__ = ['tqdm', 'trange',
  23. 'TqdmTypeError', 'TqdmKeyError', 'TqdmWarning',
  24. 'TqdmExperimentalWarning', 'TqdmDeprecationWarning',
  25. 'TqdmMonitorWarning']
  26. class TqdmTypeError(TypeError):
  27. pass
  28. class TqdmKeyError(KeyError):
  29. pass
  30. class TqdmWarning(Warning):
  31. """base class for all tqdm warnings.
  32. Used for non-external-code-breaking errors, such as garbled printing.
  33. """
  34. def __init__(self, msg, fp_write=None, *a, **k):
  35. if fp_write is not None:
  36. fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n')
  37. else:
  38. super(TqdmWarning, self).__init__(msg, *a, **k)
  39. class TqdmExperimentalWarning(TqdmWarning, FutureWarning):
  40. """beta feature, unstable API and behaviour"""
  41. pass
  42. class TqdmDeprecationWarning(TqdmWarning, DeprecationWarning):
  43. # not suppressed if raised
  44. pass
  45. class TqdmMonitorWarning(TqdmWarning, RuntimeWarning):
  46. """tqdm monitor errors which do not affect external functionality"""
  47. pass
  48. def TRLock(*args, **kwargs):
  49. """threading RLock"""
  50. try:
  51. from threading import RLock
  52. return RLock(*args, **kwargs)
  53. except (ImportError, OSError): # pragma: no cover
  54. pass
  55. class TqdmDefaultWriteLock(object):
  56. """
  57. Provide a default write lock for thread and multiprocessing safety.
  58. Works only on platforms supporting `fork` (so Windows is excluded).
  59. You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance
  60. before forking in order for the write lock to work.
  61. On Windows, you need to supply the lock from the parent to the children as
  62. an argument to joblib or the parallelism lib you use.
  63. """
  64. # global thread lock so no setup required for multithreading.
  65. # NB: Do not create multiprocessing lock as it sets the multiprocessing
  66. # context, disallowing `spawn()`/`forkserver()`
  67. th_lock = TRLock()
  68. def __init__(self):
  69. # Create global parallelism locks to avoid racing issues with parallel
  70. # bars works only if fork available (Linux/MacOSX, but not Windows)
  71. cls = type(self)
  72. root_lock = cls.th_lock
  73. if root_lock is not None:
  74. root_lock.acquire()
  75. cls.create_mp_lock()
  76. self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None]
  77. if root_lock is not None:
  78. root_lock.release()
  79. def acquire(self, *a, **k):
  80. for lock in self.locks:
  81. lock.acquire(*a, **k)
  82. def release(self):
  83. for lock in self.locks[::-1]: # Release in inverse order of acquisition
  84. lock.release()
  85. def __enter__(self):
  86. self.acquire()
  87. def __exit__(self, *exc):
  88. self.release()
  89. @classmethod
  90. def create_mp_lock(cls):
  91. if not hasattr(cls, 'mp_lock'):
  92. try:
  93. from multiprocessing import RLock
  94. cls.mp_lock = RLock()
  95. except (ImportError, OSError): # pragma: no cover
  96. cls.mp_lock = None
  97. @classmethod
  98. def create_th_lock(cls):
  99. assert hasattr(cls, 'th_lock')
  100. warn("create_th_lock not needed anymore", TqdmDeprecationWarning, stacklevel=2)
  101. class Bar(object):
  102. """
  103. `str.format`-able bar with format specifiers: `[width][type]`
  104. - `width`
  105. + unspecified (default): use `self.default_len`
  106. + `int >= 0`: overrides `self.default_len`
  107. + `int < 0`: subtract from `self.default_len`
  108. - `type`
  109. + `a`: ascii (`charset=self.ASCII` override)
  110. + `u`: unicode (`charset=self.UTF` override)
  111. + `b`: blank (`charset=" "` override)
  112. """
  113. ASCII = " 123456789#"
  114. UTF = u" " + u''.join(map(chr, range(0x258F, 0x2587, -1)))
  115. BLANK = " "
  116. COLOUR_RESET = '\x1b[0m'
  117. COLOUR_RGB = '\x1b[38;2;%d;%d;%dm'
  118. COLOURS = {'BLACK': '\x1b[30m', 'RED': '\x1b[31m', 'GREEN': '\x1b[32m',
  119. 'YELLOW': '\x1b[33m', 'BLUE': '\x1b[34m', 'MAGENTA': '\x1b[35m',
  120. 'CYAN': '\x1b[36m', 'WHITE': '\x1b[37m'}
  121. def __init__(self, frac, default_len=10, charset=UTF, colour=None):
  122. if not 0 <= frac <= 1:
  123. warn("clamping frac to range [0, 1]", TqdmWarning, stacklevel=2)
  124. frac = max(0, min(1, frac))
  125. assert default_len > 0
  126. self.frac = frac
  127. self.default_len = default_len
  128. self.charset = charset
  129. self.colour = colour
  130. @property
  131. def colour(self):
  132. return self._colour
  133. @colour.setter
  134. def colour(self, value):
  135. if not value:
  136. self._colour = None
  137. return
  138. try:
  139. if value.upper() in self.COLOURS:
  140. self._colour = self.COLOURS[value.upper()]
  141. elif value[0] == '#' and len(value) == 7:
  142. self._colour = self.COLOUR_RGB % tuple(
  143. int(i, 16) for i in (value[1:3], value[3:5], value[5:7]))
  144. else:
  145. raise KeyError
  146. except (KeyError, AttributeError):
  147. warn("Unknown colour (%s); valid choices: [hex (#00ff00), %s]" % (
  148. value, ", ".join(self.COLOURS)),
  149. TqdmWarning, stacklevel=2)
  150. self._colour = None
  151. def __format__(self, format_spec):
  152. if format_spec:
  153. _type = format_spec[-1].lower()
  154. try:
  155. charset = {'a': self.ASCII, 'u': self.UTF, 'b': self.BLANK}[_type]
  156. except KeyError:
  157. charset = self.charset
  158. else:
  159. format_spec = format_spec[:-1]
  160. if format_spec:
  161. N_BARS = int(format_spec)
  162. if N_BARS < 0:
  163. N_BARS += self.default_len
  164. else:
  165. N_BARS = self.default_len
  166. else:
  167. charset = self.charset
  168. N_BARS = self.default_len
  169. nsyms = len(charset) - 1
  170. bar_length, frac_bar_length = divmod(int(self.frac * N_BARS * nsyms), nsyms)
  171. res = charset[-1] * bar_length
  172. if bar_length < N_BARS: # whitespace padding
  173. res = res + charset[frac_bar_length] + charset[0] * (N_BARS - bar_length - 1)
  174. return self.colour + res + self.COLOUR_RESET if self.colour else res
  175. class EMA(object):
  176. """
  177. Exponential moving average: smoothing to give progressively lower
  178. weights to older values.
  179. Parameters
  180. ----------
  181. smoothing : float, optional
  182. Smoothing factor in range [0, 1], [default: 0.3].
  183. Increase to give more weight to recent values.
  184. Ranges from 0 (yields old value) to 1 (yields new value).
  185. """
  186. def __init__(self, smoothing=0.3):
  187. self.alpha = smoothing
  188. self.last = 0
  189. self.calls = 0
  190. def __call__(self, x=None):
  191. """
  192. Parameters
  193. ----------
  194. x : float
  195. New value to include in EMA.
  196. """
  197. beta = 1 - self.alpha
  198. if x is not None:
  199. self.last = self.alpha * x + beta * self.last
  200. self.calls += 1
  201. return self.last / (1 - beta ** self.calls) if self.calls else self.last
  202. class tqdm(Comparable):
  203. """
  204. Decorate an iterable object, returning an iterator which acts exactly
  205. like the original iterable, but prints a dynamically updating
  206. progressbar every time a value is requested.
  207. """
  208. monitor_interval = 10 # set to 0 to disable the thread
  209. monitor = None
  210. _instances = WeakSet()
  211. @staticmethod
  212. def format_sizeof(num, suffix='', divisor=1000):
  213. """
  214. Formats a number (greater than unity) with SI Order of Magnitude
  215. prefixes.
  216. Parameters
  217. ----------
  218. num : float
  219. Number ( >= 1) to format.
  220. suffix : str, optional
  221. Post-postfix [default: ''].
  222. divisor : float, optional
  223. Divisor between prefixes [default: 1000].
  224. Returns
  225. -------
  226. out : str
  227. Number with Order of Magnitude SI unit postfix.
  228. """
  229. for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
  230. if abs(num) < 999.5:
  231. if abs(num) < 99.95:
  232. if abs(num) < 9.995:
  233. return '{0:1.2f}'.format(num) + unit + suffix
  234. return '{0:2.1f}'.format(num) + unit + suffix
  235. return '{0:3.0f}'.format(num) + unit + suffix
  236. num /= divisor
  237. return '{0:3.1f}Y'.format(num) + suffix
  238. @staticmethod
  239. def format_interval(t):
  240. """
  241. Formats a number of seconds as a clock time, [H:]MM:SS
  242. Parameters
  243. ----------
  244. t : int
  245. Number of seconds.
  246. Returns
  247. -------
  248. out : str
  249. [H:]MM:SS
  250. """
  251. mins, s = divmod(int(t), 60)
  252. h, m = divmod(mins, 60)
  253. if h:
  254. return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s)
  255. else:
  256. return '{0:02d}:{1:02d}'.format(m, s)
  257. @staticmethod
  258. def format_num(n):
  259. """
  260. Intelligent scientific notation (.3g).
  261. Parameters
  262. ----------
  263. n : int or float or Numeric
  264. A Number.
  265. Returns
  266. -------
  267. out : str
  268. Formatted number.
  269. """
  270. f = '{0:.3g}'.format(n).replace('+0', '+').replace('-0', '-')
  271. n = str(n)
  272. return f if len(f) < len(n) else n
  273. @staticmethod
  274. def status_printer(file):
  275. """
  276. Manage the printing and in-place updating of a line of characters.
  277. Note that if the string is longer than a line, then in-place
  278. updating may not work (it will print a new line at each refresh).
  279. """
  280. fp = file
  281. fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover
  282. if fp in (sys.stderr, sys.stdout):
  283. getattr(sys.stderr, 'flush', lambda: None)()
  284. getattr(sys.stdout, 'flush', lambda: None)()
  285. def fp_write(s):
  286. fp.write(str(s))
  287. fp_flush()
  288. last_len = [0]
  289. def print_status(s):
  290. len_s = disp_len(s)
  291. fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
  292. last_len[0] = len_s
  293. return print_status
  294. @staticmethod
  295. def format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it',
  296. unit_scale=False, rate=None, bar_format=None, postfix=None,
  297. unit_divisor=1000, initial=0, colour=None, **extra_kwargs):
  298. """
  299. Return a string-based progress bar given some parameters
  300. Parameters
  301. ----------
  302. n : int or float
  303. Number of finished iterations.
  304. total : int or float
  305. The expected total number of iterations. If meaningless (None),
  306. only basic progress statistics are displayed (no ETA).
  307. elapsed : float
  308. Number of seconds passed since start.
  309. ncols : int, optional
  310. The width of the entire output message. If specified,
  311. dynamically resizes `{bar}` to stay within this bound
  312. [default: None]. If `0`, will not print any bar (only stats).
  313. The fallback is `{bar:10}`.
  314. prefix : str, optional
  315. Prefix message (included in total width) [default: ''].
  316. Use as {desc} in bar_format string.
  317. ascii : bool, optional or str, optional
  318. If not set, use unicode (smooth blocks) to fill the meter
  319. [default: False]. The fallback is to use ASCII characters
  320. " 123456789#".
  321. unit : str, optional
  322. The iteration unit [default: 'it'].
  323. unit_scale : bool or int or float, optional
  324. If 1 or True, the number of iterations will be printed with an
  325. appropriate SI metric prefix (k = 10^3, M = 10^6, etc.)
  326. [default: False]. If any other non-zero number, will scale
  327. `total` and `n`.
  328. rate : float, optional
  329. Manual override for iteration rate.
  330. If [default: None], uses n/elapsed.
  331. bar_format : str, optional
  332. Specify a custom bar string formatting. May impact performance.
  333. [default: '{l_bar}{bar}{r_bar}'], where
  334. l_bar='{desc}: {percentage:3.0f}%|' and
  335. r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
  336. '{rate_fmt}{postfix}]'
  337. Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
  338. percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
  339. rate, rate_fmt, rate_noinv, rate_noinv_fmt,
  340. rate_inv, rate_inv_fmt, postfix, unit_divisor,
  341. remaining, remaining_s, eta.
  342. Note that a trailing ": " is automatically removed after {desc}
  343. if the latter is empty.
  344. postfix : *, optional
  345. Similar to `prefix`, but placed at the end
  346. (e.g. for additional stats).
  347. Note: postfix is usually a string (not a dict) for this method,
  348. and will if possible be set to postfix = ', ' + postfix.
  349. However other types are supported (#382).
  350. unit_divisor : float, optional
  351. [default: 1000], ignored unless `unit_scale` is True.
  352. initial : int or float, optional
  353. The initial counter value [default: 0].
  354. colour : str, optional
  355. Bar colour (e.g. 'green', '#00ff00').
  356. Returns
  357. -------
  358. out : Formatted meter and stats, ready to display.
  359. """
  360. # sanity check: total
  361. if total and n >= (total + 0.5): # allow float imprecision (#849)
  362. total = None
  363. # apply custom scale if necessary
  364. if unit_scale and unit_scale not in (True, 1):
  365. if total:
  366. total *= unit_scale
  367. n *= unit_scale
  368. if rate:
  369. rate *= unit_scale # by default rate = self.avg_dn / self.avg_dt
  370. unit_scale = False
  371. elapsed_str = tqdm.format_interval(elapsed)
  372. # if unspecified, attempt to use rate = average speed
  373. # (we allow manual override since predicting time is an arcane art)
  374. if rate is None and elapsed:
  375. rate = (n - initial) / elapsed
  376. inv_rate = 1 / rate if rate else None
  377. format_sizeof = tqdm.format_sizeof
  378. rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else
  379. '{0:5.2f}'.format(rate)) if rate else '?') + unit + '/s'
  380. rate_inv_fmt = (
  381. (format_sizeof(inv_rate) if unit_scale else '{0:5.2f}'.format(inv_rate))
  382. if inv_rate else '?') + 's/' + unit
  383. rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt
  384. if unit_scale:
  385. n_fmt = format_sizeof(n, divisor=unit_divisor)
  386. total_fmt = format_sizeof(total, divisor=unit_divisor) if total is not None else '?'
  387. else:
  388. n_fmt = str(n)
  389. total_fmt = str(total) if total is not None else '?'
  390. try:
  391. postfix = ', ' + postfix if postfix else ''
  392. except TypeError:
  393. pass
  394. remaining = (total - n) / rate if rate and total else 0
  395. remaining_str = tqdm.format_interval(remaining) if rate else '?'
  396. try:
  397. eta_dt = (datetime.now() + timedelta(seconds=remaining)
  398. if rate and total else datetime.utcfromtimestamp(0))
  399. except OverflowError:
  400. eta_dt = datetime.max
  401. # format the stats displayed to the left and right sides of the bar
  402. if prefix:
  403. # old prefix setup work around
  404. bool_prefix_colon_already = (prefix[-2:] == ": ")
  405. l_bar = prefix if bool_prefix_colon_already else prefix + ": "
  406. else:
  407. l_bar = ''
  408. r_bar = f'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}{postfix}]'
  409. # Custom bar formatting
  410. # Populate a dict with all available progress indicators
  411. format_dict = {
  412. # slight extension of self.format_dict
  413. 'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt,
  414. 'elapsed': elapsed_str, 'elapsed_s': elapsed,
  415. 'ncols': ncols, 'desc': prefix or '', 'unit': unit,
  416. 'rate': inv_rate if inv_rate and inv_rate > 1 else rate,
  417. 'rate_fmt': rate_fmt, 'rate_noinv': rate,
  418. 'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate,
  419. 'rate_inv_fmt': rate_inv_fmt,
  420. 'postfix': postfix, 'unit_divisor': unit_divisor,
  421. 'colour': colour,
  422. # plus more useful definitions
  423. 'remaining': remaining_str, 'remaining_s': remaining,
  424. 'l_bar': l_bar, 'r_bar': r_bar, 'eta': eta_dt,
  425. **extra_kwargs}
  426. # total is known: we can predict some stats
  427. if total:
  428. # fractional and percentage progress
  429. frac = n / total
  430. percentage = frac * 100
  431. l_bar += '{0:3.0f}%|'.format(percentage)
  432. if ncols == 0:
  433. return l_bar[:-1] + r_bar[1:]
  434. format_dict.update(l_bar=l_bar)
  435. if bar_format:
  436. format_dict.update(percentage=percentage)
  437. # auto-remove colon for empty `{desc}`
  438. if not prefix:
  439. bar_format = bar_format.replace("{desc}: ", '')
  440. else:
  441. bar_format = "{l_bar}{bar}{r_bar}"
  442. full_bar = FormatReplace()
  443. nobar = bar_format.format(bar=full_bar, **format_dict)
  444. if not full_bar.format_called:
  445. return nobar # no `{bar}`; nothing else to do
  446. # Formatting progress bar space available for bar's display
  447. full_bar = Bar(frac,
  448. max(1, ncols - disp_len(nobar)) if ncols else 10,
  449. charset=Bar.ASCII if ascii is True else ascii or Bar.UTF,
  450. colour=colour)
  451. if not _is_ascii(full_bar.charset) and _is_ascii(bar_format):
  452. bar_format = str(bar_format)
  453. res = bar_format.format(bar=full_bar, **format_dict)
  454. return disp_trim(res, ncols) if ncols else res
  455. elif bar_format:
  456. # user-specified bar_format but no total
  457. l_bar += '|'
  458. format_dict.update(l_bar=l_bar, percentage=0)
  459. full_bar = FormatReplace()
  460. nobar = bar_format.format(bar=full_bar, **format_dict)
  461. if not full_bar.format_called:
  462. return nobar
  463. full_bar = Bar(0,
  464. max(1, ncols - disp_len(nobar)) if ncols else 10,
  465. charset=Bar.BLANK, colour=colour)
  466. res = bar_format.format(bar=full_bar, **format_dict)
  467. return disp_trim(res, ncols) if ncols else res
  468. else:
  469. # no total: no progressbar, ETA, just progress stats
  470. return (f'{(prefix + ": ") if prefix else ""}'
  471. f'{n_fmt}{unit} [{elapsed_str}, {rate_fmt}{postfix}]')
  472. def __new__(cls, *_, **__):
  473. instance = object.__new__(cls)
  474. with cls.get_lock(): # also constructs lock if non-existent
  475. cls._instances.add(instance)
  476. # create monitoring thread
  477. if cls.monitor_interval and (cls.monitor is None
  478. or not cls.monitor.report()):
  479. try:
  480. cls.monitor = TMonitor(cls, cls.monitor_interval)
  481. except Exception as e: # pragma: nocover
  482. warn("tqdm:disabling monitor support"
  483. " (monitor_interval = 0) due to:\n" + str(e),
  484. TqdmMonitorWarning, stacklevel=2)
  485. cls.monitor_interval = 0
  486. return instance
  487. @classmethod
  488. def _get_free_pos(cls, instance=None):
  489. """Skips specified instance."""
  490. positions = {abs(inst.pos) for inst in cls._instances
  491. if inst is not instance and hasattr(inst, "pos")}
  492. return min(set(range(len(positions) + 1)).difference(positions))
  493. @classmethod
  494. def _decr_instances(cls, instance):
  495. """
  496. Remove from list and reposition another unfixed bar
  497. to fill the new gap.
  498. This means that by default (where all nested bars are unfixed),
  499. order is not maintained but screen flicker/blank space is minimised.
  500. (tqdm<=4.44.1 moved ALL subsequent unfixed bars up.)
  501. """
  502. with cls._lock:
  503. try:
  504. cls._instances.remove(instance)
  505. except KeyError:
  506. # if not instance.gui: # pragma: no cover
  507. # raise
  508. pass # py2: maybe magically removed already
  509. # else:
  510. if not instance.gui:
  511. last = (instance.nrows or 20) - 1
  512. # find unfixed (`pos >= 0`) overflow (`pos >= nrows - 1`)
  513. instances = list(filter(
  514. lambda i: hasattr(i, "pos") and last <= i.pos,
  515. cls._instances))
  516. # set first found to current `pos`
  517. if instances:
  518. inst = min(instances, key=lambda i: i.pos)
  519. inst.clear(nolock=True)
  520. inst.pos = abs(instance.pos)
  521. @classmethod
  522. def write(cls, s, file=None, end="\n", nolock=False):
  523. """Print a message via tqdm (without overlap with bars)."""
  524. fp = file if file is not None else sys.stdout
  525. with cls.external_write_mode(file=file, nolock=nolock):
  526. # Write the message
  527. fp.write(s)
  528. fp.write(end)
  529. @classmethod
  530. @contextmanager
  531. def external_write_mode(cls, file=None, nolock=False):
  532. """
  533. Disable tqdm within context and refresh tqdm when exits.
  534. Useful when writing to standard output stream
  535. """
  536. fp = file if file is not None else sys.stdout
  537. try:
  538. if not nolock:
  539. cls.get_lock().acquire()
  540. # Clear all bars
  541. inst_cleared = []
  542. for inst in getattr(cls, '_instances', []):
  543. # Clear instance if in the target output file
  544. # or if write output + tqdm output are both either
  545. # sys.stdout or sys.stderr (because both are mixed in terminal)
  546. if hasattr(inst, "start_t") and (inst.fp == fp or all(
  547. f in (sys.stdout, sys.stderr) for f in (fp, inst.fp))):
  548. inst.clear(nolock=True)
  549. inst_cleared.append(inst)
  550. yield
  551. # Force refresh display of bars we cleared
  552. for inst in inst_cleared:
  553. inst.refresh(nolock=True)
  554. finally:
  555. if not nolock:
  556. cls._lock.release()
  557. @classmethod
  558. def set_lock(cls, lock):
  559. """Set the global lock."""
  560. cls._lock = lock
  561. @classmethod
  562. def get_lock(cls):
  563. """Get the global lock. Construct it if it does not exist."""
  564. if not hasattr(cls, '_lock'):
  565. cls._lock = TqdmDefaultWriteLock()
  566. return cls._lock
  567. @classmethod
  568. def pandas(cls, **tqdm_kwargs):
  569. """
  570. Registers the current `tqdm` class with
  571. pandas.core.
  572. ( frame.DataFrame
  573. | series.Series
  574. | groupby.(generic.)DataFrameGroupBy
  575. | groupby.(generic.)SeriesGroupBy
  576. ).progress_apply
  577. A new instance will be created every time `progress_apply` is called,
  578. and each instance will automatically `close()` upon completion.
  579. Parameters
  580. ----------
  581. tqdm_kwargs : arguments for the tqdm instance
  582. Examples
  583. --------
  584. >>> import pandas as pd
  585. >>> import numpy as np
  586. >>> from tqdm import tqdm
  587. >>> from tqdm.gui import tqdm as tqdm_gui
  588. >>>
  589. >>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
  590. >>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc
  591. >>> # Now you can use `progress_apply` instead of `apply`
  592. >>> df.groupby(0).progress_apply(lambda x: x**2)
  593. References
  594. ----------
  595. <https://stackoverflow.com/questions/18603270/\
  596. progress-indicator-during-pandas-operations-python>
  597. """
  598. from warnings import catch_warnings, simplefilter
  599. from pandas.core.frame import DataFrame
  600. from pandas.core.series import Series
  601. try:
  602. with catch_warnings():
  603. simplefilter("ignore", category=FutureWarning)
  604. from pandas import Panel
  605. except ImportError: # pandas>=1.2.0
  606. Panel = None
  607. Rolling, Expanding = None, None
  608. try: # pandas>=1.0.0
  609. from pandas.core.window.rolling import _Rolling_and_Expanding
  610. except ImportError:
  611. try: # pandas>=0.18.0
  612. from pandas.core.window import _Rolling_and_Expanding
  613. except ImportError: # pandas>=1.2.0
  614. try: # pandas>=1.2.0
  615. from pandas.core.window.expanding import Expanding
  616. from pandas.core.window.rolling import Rolling
  617. _Rolling_and_Expanding = Rolling, Expanding
  618. except ImportError: # pragma: no cover
  619. _Rolling_and_Expanding = None
  620. try: # pandas>=0.25.0
  621. from pandas.core.groupby.generic import SeriesGroupBy # , NDFrameGroupBy
  622. from pandas.core.groupby.generic import DataFrameGroupBy
  623. except ImportError: # pragma: no cover
  624. try: # pandas>=0.23.0
  625. from pandas.core.groupby.groupby import DataFrameGroupBy, SeriesGroupBy
  626. except ImportError:
  627. from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy
  628. try: # pandas>=0.23.0
  629. from pandas.core.groupby.groupby import GroupBy
  630. except ImportError: # pragma: no cover
  631. from pandas.core.groupby import GroupBy
  632. try: # pandas>=0.23.0
  633. from pandas.core.groupby.groupby import PanelGroupBy
  634. except ImportError:
  635. try:
  636. from pandas.core.groupby import PanelGroupBy
  637. except ImportError: # pandas>=0.25.0
  638. PanelGroupBy = None
  639. tqdm_kwargs = tqdm_kwargs.copy()
  640. deprecated_t = [tqdm_kwargs.pop('deprecated_t', None)]
  641. def inner_generator(df_function='apply'):
  642. def inner(df, func, *args, **kwargs):
  643. """
  644. Parameters
  645. ----------
  646. df : (DataFrame|Series)[GroupBy]
  647. Data (may be grouped).
  648. func : function
  649. To be applied on the (grouped) data.
  650. **kwargs : optional
  651. Transmitted to `df.apply()`.
  652. """
  653. # Precompute total iterations
  654. total = tqdm_kwargs.pop("total", getattr(df, 'ngroups', None))
  655. if total is None: # not grouped
  656. if df_function == 'applymap':
  657. total = df.size
  658. elif isinstance(df, Series):
  659. total = len(df)
  660. elif (_Rolling_and_Expanding is None or
  661. not isinstance(df, _Rolling_and_Expanding)):
  662. # DataFrame or Panel
  663. axis = kwargs.get('axis', 0)
  664. if axis == 'index':
  665. axis = 0
  666. elif axis == 'columns':
  667. axis = 1
  668. # when axis=0, total is shape[axis1]
  669. total = df.size // df.shape[axis]
  670. # Init bar
  671. if deprecated_t[0] is not None:
  672. t = deprecated_t[0]
  673. deprecated_t[0] = None
  674. else:
  675. t = cls(total=total, **tqdm_kwargs)
  676. if len(args) > 0:
  677. # *args intentionally not supported (see #244, #299)
  678. TqdmDeprecationWarning(
  679. "Except func, normal arguments are intentionally" +
  680. " not supported by" +
  681. " `(DataFrame|Series|GroupBy).progress_apply`." +
  682. " Use keyword arguments instead.",
  683. fp_write=getattr(t.fp, 'write', sys.stderr.write))
  684. try: # pandas>=1.3.0
  685. from pandas.core.common import is_builtin_func
  686. except ImportError:
  687. is_builtin_func = df._is_builtin_func
  688. try:
  689. func = is_builtin_func(func)
  690. except TypeError:
  691. pass
  692. # Define bar updating wrapper
  693. def wrapper(*args, **kwargs):
  694. # update tbar correctly
  695. # it seems `pandas apply` calls `func` twice
  696. # on the first column/row to decide whether it can
  697. # take a fast or slow code path; so stop when t.total==t.n
  698. t.update(n=1 if not t.total or t.n < t.total else 0)
  699. return func(*args, **kwargs)
  700. # Apply the provided function (in **kwargs)
  701. # on the df using our wrapper (which provides bar updating)
  702. try:
  703. return getattr(df, df_function)(wrapper, **kwargs)
  704. finally:
  705. t.close()
  706. return inner
  707. # Monkeypatch pandas to provide easy methods
  708. # Enable custom tqdm progress in pandas!
  709. Series.progress_apply = inner_generator()
  710. SeriesGroupBy.progress_apply = inner_generator()
  711. Series.progress_map = inner_generator('map')
  712. SeriesGroupBy.progress_map = inner_generator('map')
  713. DataFrame.progress_apply = inner_generator()
  714. DataFrameGroupBy.progress_apply = inner_generator()
  715. DataFrame.progress_applymap = inner_generator('applymap')
  716. if Panel is not None:
  717. Panel.progress_apply = inner_generator()
  718. if PanelGroupBy is not None:
  719. PanelGroupBy.progress_apply = inner_generator()
  720. GroupBy.progress_apply = inner_generator()
  721. GroupBy.progress_aggregate = inner_generator('aggregate')
  722. GroupBy.progress_transform = inner_generator('transform')
  723. if Rolling is not None and Expanding is not None:
  724. Rolling.progress_apply = inner_generator()
  725. Expanding.progress_apply = inner_generator()
  726. elif _Rolling_and_Expanding is not None:
  727. _Rolling_and_Expanding.progress_apply = inner_generator()
  728. def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
  729. ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None,
  730. ascii=None, disable=False, unit='it', unit_scale=False,
  731. dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0,
  732. position=None, postfix=None, unit_divisor=1000, write_bytes=False,
  733. lock_args=None, nrows=None, colour=None, delay=0, gui=False,
  734. **kwargs):
  735. """
  736. Parameters
  737. ----------
  738. iterable : iterable, optional
  739. Iterable to decorate with a progressbar.
  740. Leave blank to manually manage the updates.
  741. desc : str, optional
  742. Prefix for the progressbar.
  743. total : int or float, optional
  744. The number of expected iterations. If unspecified,
  745. len(iterable) is used if possible. If float("inf") or as a last
  746. resort, only basic progress statistics are displayed
  747. (no ETA, no progressbar).
  748. If `gui` is True and this parameter needs subsequent updating,
  749. specify an initial arbitrary large positive number,
  750. e.g. 9e9.
  751. leave : bool, optional
  752. If [default: True], keeps all traces of the progressbar
  753. upon termination of iteration.
  754. If `None`, will leave only if `position` is `0`.
  755. file : `io.TextIOWrapper` or `io.StringIO`, optional
  756. Specifies where to output the progress messages
  757. (default: sys.stderr). Uses `file.write(str)` and `file.flush()`
  758. methods. For encoding, see `write_bytes`.
  759. ncols : int, optional
  760. The width of the entire output message. If specified,
  761. dynamically resizes the progressbar to stay within this bound.
  762. If unspecified, attempts to use environment width. The
  763. fallback is a meter width of 10 and no limit for the counter and
  764. statistics. If 0, will not print any meter (only stats).
  765. mininterval : float, optional
  766. Minimum progress display update interval [default: 0.1] seconds.
  767. maxinterval : float, optional
  768. Maximum progress display update interval [default: 10] seconds.
  769. Automatically adjusts `miniters` to correspond to `mininterval`
  770. after long display update lag. Only works if `dynamic_miniters`
  771. or monitor thread is enabled.
  772. miniters : int or float, optional
  773. Minimum progress display update interval, in iterations.
  774. If 0 and `dynamic_miniters`, will automatically adjust to equal
  775. `mininterval` (more CPU efficient, good for tight loops).
  776. If > 0, will skip display of specified number of iterations.
  777. Tweak this and `mininterval` to get very efficient loops.
  778. If your progress is erratic with both fast and slow iterations
  779. (network, skipping items, etc) you should set miniters=1.
  780. ascii : bool or str, optional
  781. If unspecified or False, use unicode (smooth blocks) to fill
  782. the meter. The fallback is to use ASCII characters " 123456789#".
  783. disable : bool, optional
  784. Whether to disable the entire progressbar wrapper
  785. [default: False]. If set to None, disable on non-TTY.
  786. unit : str, optional
  787. String that will be used to define the unit of each iteration
  788. [default: it].
  789. unit_scale : bool or int or float, optional
  790. If 1 or True, the number of iterations will be reduced/scaled
  791. automatically and a metric prefix following the
  792. International System of Units standard will be added
  793. (kilo, mega, etc.) [default: False]. If any other non-zero
  794. number, will scale `total` and `n`.
  795. dynamic_ncols : bool, optional
  796. If set, constantly alters `ncols` and `nrows` to the
  797. environment (allowing for window resizes) [default: False].
  798. smoothing : float, optional
  799. Exponential moving average smoothing factor for speed estimates
  800. (ignored in GUI mode). Ranges from 0 (average speed) to 1
  801. (current/instantaneous speed) [default: 0.3].
  802. bar_format : str, optional
  803. Specify a custom bar string formatting. May impact performance.
  804. [default: '{l_bar}{bar}{r_bar}'], where
  805. l_bar='{desc}: {percentage:3.0f}%|' and
  806. r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
  807. '{rate_fmt}{postfix}]'
  808. Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
  809. percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
  810. rate, rate_fmt, rate_noinv, rate_noinv_fmt,
  811. rate_inv, rate_inv_fmt, postfix, unit_divisor,
  812. remaining, remaining_s, eta.
  813. Note that a trailing ": " is automatically removed after {desc}
  814. if the latter is empty.
  815. initial : int or float, optional
  816. The initial counter value. Useful when restarting a progress
  817. bar [default: 0]. If using float, consider specifying `{n:.3f}`
  818. or similar in `bar_format`, or specifying `unit_scale`.
  819. position : int, optional
  820. Specify the line offset to print this bar (starting from 0)
  821. Automatic if unspecified.
  822. Useful to manage multiple bars at once (eg, from threads).
  823. postfix : dict or *, optional
  824. Specify additional stats to display at the end of the bar.
  825. Calls `set_postfix(**postfix)` if possible (dict).
  826. unit_divisor : float, optional
  827. [default: 1000], ignored unless `unit_scale` is True.
  828. write_bytes : bool, optional
  829. Whether to write bytes. If (default: False) will write unicode.
  830. lock_args : tuple, optional
  831. Passed to `refresh` for intermediate output
  832. (initialisation, iterating, and updating).
  833. nrows : int, optional
  834. The screen height. If specified, hides nested bars outside this
  835. bound. If unspecified, attempts to use environment height.
  836. The fallback is 20.
  837. colour : str, optional
  838. Bar colour (e.g. 'green', '#00ff00').
  839. delay : float, optional
  840. Don't display until [default: 0] seconds have elapsed.
  841. gui : bool, optional
  842. WARNING: internal parameter - do not use.
  843. Use tqdm.gui.tqdm(...) instead. If set, will attempt to use
  844. matplotlib animations for a graphical output [default: False].
  845. Returns
  846. -------
  847. out : decorated iterator.
  848. """
  849. if file is None:
  850. file = sys.stderr
  851. if write_bytes:
  852. # Despite coercing unicode into bytes, py2 sys.std* streams
  853. # should have bytes written to them.
  854. file = SimpleTextIOWrapper(
  855. file, encoding=getattr(file, 'encoding', None) or 'utf-8')
  856. file = DisableOnWriteError(file, tqdm_instance=self)
  857. if disable is None and hasattr(file, "isatty") and not file.isatty():
  858. disable = True
  859. if total is None and iterable is not None:
  860. try:
  861. total = len(iterable)
  862. except (TypeError, AttributeError):
  863. total = None
  864. if total == float("inf"):
  865. # Infinite iterations, behave same as unknown
  866. total = None
  867. if disable:
  868. self.iterable = iterable
  869. self.disable = disable
  870. with self._lock:
  871. self.pos = self._get_free_pos(self)
  872. self._instances.remove(self)
  873. self.n = initial
  874. self.total = total
  875. self.leave = leave
  876. return
  877. if kwargs:
  878. self.disable = True
  879. with self._lock:
  880. self.pos = self._get_free_pos(self)
  881. self._instances.remove(self)
  882. raise (
  883. TqdmDeprecationWarning(
  884. "`nested` is deprecated and automated.\n"
  885. "Use `position` instead for manual control.\n",
  886. fp_write=getattr(file, 'write', sys.stderr.write))
  887. if "nested" in kwargs else
  888. TqdmKeyError("Unknown argument(s): " + str(kwargs)))
  889. # Preprocess the arguments
  890. if (
  891. (ncols is None or nrows is None) and (file in (sys.stderr, sys.stdout))
  892. ) or dynamic_ncols: # pragma: no cover
  893. if dynamic_ncols:
  894. dynamic_ncols = _screen_shape_wrapper()
  895. if dynamic_ncols:
  896. ncols, nrows = dynamic_ncols(file)
  897. else:
  898. _dynamic_ncols = _screen_shape_wrapper()
  899. if _dynamic_ncols:
  900. _ncols, _nrows = _dynamic_ncols(file)
  901. if ncols is None:
  902. ncols = _ncols
  903. if nrows is None:
  904. nrows = _nrows
  905. if miniters is None:
  906. miniters = 0
  907. dynamic_miniters = True
  908. else:
  909. dynamic_miniters = False
  910. if mininterval is None:
  911. mininterval = 0
  912. if maxinterval is None:
  913. maxinterval = 0
  914. if ascii is None:
  915. ascii = not _supports_unicode(file)
  916. if bar_format and ascii is not True and not _is_ascii(ascii):
  917. # Convert bar format into unicode since terminal uses unicode
  918. bar_format = str(bar_format)
  919. if smoothing is None:
  920. smoothing = 0
  921. # Store the arguments
  922. self.iterable = iterable
  923. self.desc = desc or ''
  924. self.total = total
  925. self.leave = leave
  926. self.fp = file
  927. self.ncols = ncols
  928. self.nrows = nrows
  929. self.mininterval = mininterval
  930. self.maxinterval = maxinterval
  931. self.miniters = miniters
  932. self.dynamic_miniters = dynamic_miniters
  933. self.ascii = ascii
  934. self.disable = disable
  935. self.unit = unit
  936. self.unit_scale = unit_scale
  937. self.unit_divisor = unit_divisor
  938. self.initial = initial
  939. self.lock_args = lock_args
  940. self.delay = delay
  941. self.gui = gui
  942. self.dynamic_ncols = dynamic_ncols
  943. self.smoothing = smoothing
  944. self._ema_dn = EMA(smoothing)
  945. self._ema_dt = EMA(smoothing)
  946. self._ema_miniters = EMA(smoothing)
  947. self.bar_format = bar_format
  948. self.postfix = None
  949. self.colour = colour
  950. self._time = time
  951. if postfix:
  952. try:
  953. self.set_postfix(refresh=False, **postfix)
  954. except TypeError:
  955. self.postfix = postfix
  956. # Init the iterations counters
  957. self.last_print_n = initial
  958. self.n = initial
  959. # if nested, at initial sp() call we replace '\r' by '\n' to
  960. # not overwrite the outer progress bar
  961. with self._lock:
  962. # mark fixed positions as negative
  963. self.pos = self._get_free_pos(self) if position is None else -position
  964. if not gui:
  965. # Initialize the screen printer
  966. self.sp = self.status_printer(self.fp)
  967. if delay <= 0:
  968. self.refresh(lock_args=self.lock_args)
  969. # Init the time counter
  970. self.last_print_t = self._time()
  971. # NB: Avoid race conditions by setting start_t at the very end of init
  972. self.start_t = self.last_print_t
  973. def __bool__(self):
  974. if self.total is not None:
  975. return self.total > 0
  976. if self.iterable is None:
  977. raise TypeError('bool() undefined when iterable == total == None')
  978. return bool(self.iterable)
  979. def __len__(self):
  980. return (
  981. self.total if self.iterable is None
  982. else self.iterable.shape[0] if hasattr(self.iterable, "shape")
  983. else len(self.iterable) if hasattr(self.iterable, "__len__")
  984. else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__")
  985. else getattr(self, "total", None))
  986. def __reversed__(self):
  987. try:
  988. orig = self.iterable
  989. except AttributeError:
  990. raise TypeError("'tqdm' object is not reversible")
  991. else:
  992. self.iterable = reversed(self.iterable)
  993. return self.__iter__()
  994. finally:
  995. self.iterable = orig
  996. def __contains__(self, item):
  997. contains = getattr(self.iterable, '__contains__', None)
  998. return contains(item) if contains is not None else item in self.__iter__()
  999. def __enter__(self):
  1000. return self
  1001. def __exit__(self, exc_type, exc_value, traceback):
  1002. try:
  1003. self.close()
  1004. except AttributeError:
  1005. # maybe eager thread cleanup upon external error
  1006. if (exc_type, exc_value, traceback) == (None, None, None):
  1007. raise
  1008. warn("AttributeError ignored", TqdmWarning, stacklevel=2)
  1009. def __del__(self):
  1010. self.close()
  1011. def __str__(self):
  1012. return self.format_meter(**self.format_dict)
  1013. @property
  1014. def _comparable(self):
  1015. return abs(getattr(self, "pos", 1 << 31))
  1016. def __hash__(self):
  1017. return id(self)
  1018. def __iter__(self):
  1019. """Backward-compatibility to use: for x in tqdm(iterable)"""
  1020. # Inlining instance variables as locals (speed optimisation)
  1021. iterable = self.iterable
  1022. # If the bar is disabled, then just walk the iterable
  1023. # (note: keep this check outside the loop for performance)
  1024. if self.disable:
  1025. for obj in iterable:
  1026. yield obj
  1027. return
  1028. mininterval = self.mininterval
  1029. last_print_t = self.last_print_t
  1030. last_print_n = self.last_print_n
  1031. min_start_t = self.start_t + self.delay
  1032. n = self.n
  1033. time = self._time
  1034. try:
  1035. for obj in iterable:
  1036. yield obj
  1037. # Update and possibly print the progressbar.
  1038. # Note: does not call self.update(1) for speed optimisation.
  1039. n += 1
  1040. if n - last_print_n >= self.miniters:
  1041. cur_t = time()
  1042. dt = cur_t - last_print_t
  1043. if dt >= mininterval and cur_t >= min_start_t:
  1044. self.update(n - last_print_n)
  1045. last_print_n = self.last_print_n
  1046. last_print_t = self.last_print_t
  1047. finally:
  1048. self.n = n
  1049. self.close()
  1050. def update(self, n=1):
  1051. """
  1052. Manually update the progress bar, useful for streams
  1053. such as reading files.
  1054. E.g.:
  1055. >>> t = tqdm(total=filesize) # Initialise
  1056. >>> for current_buffer in stream:
  1057. ... ...
  1058. ... t.update(len(current_buffer))
  1059. >>> t.close()
  1060. The last line is highly recommended, but possibly not necessary if
  1061. `t.update()` will be called in such a way that `filesize` will be
  1062. exactly reached and printed.
  1063. Parameters
  1064. ----------
  1065. n : int or float, optional
  1066. Increment to add to the internal counter of iterations
  1067. [default: 1]. If using float, consider specifying `{n:.3f}`
  1068. or similar in `bar_format`, or specifying `unit_scale`.
  1069. Returns
  1070. -------
  1071. out : bool or None
  1072. True if a `display()` was triggered.
  1073. """
  1074. if self.disable:
  1075. return
  1076. if n < 0:
  1077. self.last_print_n += n # for auto-refresh logic to work
  1078. self.n += n
  1079. # check counter first to reduce calls to time()
  1080. if self.n - self.last_print_n >= self.miniters:
  1081. cur_t = self._time()
  1082. dt = cur_t - self.last_print_t
  1083. if dt >= self.mininterval and cur_t >= self.start_t + self.delay:
  1084. cur_t = self._time()
  1085. dn = self.n - self.last_print_n # >= n
  1086. if self.smoothing and dt and dn:
  1087. # EMA (not just overall average)
  1088. self._ema_dn(dn)
  1089. self._ema_dt(dt)
  1090. self.refresh(lock_args=self.lock_args)
  1091. if self.dynamic_miniters:
  1092. # If no `miniters` was specified, adjust automatically to the
  1093. # maximum iteration rate seen so far between two prints.
  1094. # e.g.: After running `tqdm.update(5)`, subsequent
  1095. # calls to `tqdm.update()` will only cause an update after
  1096. # at least 5 more iterations.
  1097. if self.maxinterval and dt >= self.maxinterval:
  1098. self.miniters = dn * (self.mininterval or self.maxinterval) / dt
  1099. elif self.smoothing:
  1100. # EMA miniters update
  1101. self.miniters = self._ema_miniters(
  1102. dn * (self.mininterval / dt if self.mininterval and dt
  1103. else 1))
  1104. else:
  1105. # max iters between two prints
  1106. self.miniters = max(self.miniters, dn)
  1107. # Store old values for next call
  1108. self.last_print_n = self.n
  1109. self.last_print_t = cur_t
  1110. return True
  1111. def close(self):
  1112. """Cleanup and (if leave=False) close the progressbar."""
  1113. if self.disable:
  1114. return
  1115. # Prevent multiple closures
  1116. self.disable = True
  1117. # decrement instance pos and remove from internal set
  1118. pos = abs(self.pos)
  1119. self._decr_instances(self)
  1120. if self.last_print_t < self.start_t + self.delay:
  1121. # haven't ever displayed; nothing to clear
  1122. return
  1123. # GUI mode
  1124. if getattr(self, 'sp', None) is None:
  1125. return
  1126. # annoyingly, _supports_unicode isn't good enough
  1127. def fp_write(s):
  1128. self.fp.write(str(s))
  1129. try:
  1130. fp_write('')
  1131. except ValueError as e:
  1132. if 'closed' in str(e):
  1133. return
  1134. raise # pragma: no cover
  1135. leave = pos == 0 if self.leave is None else self.leave
  1136. with self._lock:
  1137. if leave:
  1138. # stats for overall rate (no weighted average)
  1139. self._ema_dt = lambda: None
  1140. self.display(pos=0)
  1141. fp_write('\n')
  1142. else:
  1143. # clear previous display
  1144. if self.display(msg='', pos=pos) and not pos:
  1145. fp_write('\r')
  1146. def clear(self, nolock=False):
  1147. """Clear current bar display."""
  1148. if self.disable:
  1149. return
  1150. if not nolock:
  1151. self._lock.acquire()
  1152. pos = abs(self.pos)
  1153. if pos < (self.nrows or 20):
  1154. self.moveto(pos)
  1155. self.sp('')
  1156. self.fp.write('\r') # place cursor back at the beginning of line
  1157. self.moveto(-pos)
  1158. if not nolock:
  1159. self._lock.release()
  1160. def refresh(self, nolock=False, lock_args=None):
  1161. """
  1162. Force refresh the display of this bar.
  1163. Parameters
  1164. ----------
  1165. nolock : bool, optional
  1166. If `True`, does not lock.
  1167. If [default: `False`]: calls `acquire()` on internal lock.
  1168. lock_args : tuple, optional
  1169. Passed to internal lock's `acquire()`.
  1170. If specified, will only `display()` if `acquire()` returns `True`.
  1171. """
  1172. if self.disable:
  1173. return
  1174. if not nolock:
  1175. if lock_args:
  1176. if not self._lock.acquire(*lock_args):
  1177. return False
  1178. else:
  1179. self._lock.acquire()
  1180. self.display()
  1181. if not nolock:
  1182. self._lock.release()
  1183. return True
  1184. def unpause(self):
  1185. """Restart tqdm timer from last print time."""
  1186. if self.disable:
  1187. return
  1188. cur_t = self._time()
  1189. self.start_t += cur_t - self.last_print_t
  1190. self.last_print_t = cur_t
  1191. def reset(self, total=None):
  1192. """
  1193. Resets to 0 iterations for repeated use.
  1194. Consider combining with `leave=True`.
  1195. Parameters
  1196. ----------
  1197. total : int or float, optional. Total to use for the new bar.
  1198. """
  1199. self.n = 0
  1200. if total is not None:
  1201. self.total = total
  1202. if self.disable:
  1203. return
  1204. self.last_print_n = 0
  1205. self.last_print_t = self.start_t = self._time()
  1206. self._ema_dn = EMA(self.smoothing)
  1207. self._ema_dt = EMA(self.smoothing)
  1208. self._ema_miniters = EMA(self.smoothing)
  1209. self.refresh()
  1210. def set_description(self, desc=None, refresh=True):
  1211. """
  1212. Set/modify description of the progress bar.
  1213. Parameters
  1214. ----------
  1215. desc : str, optional
  1216. refresh : bool, optional
  1217. Forces refresh [default: True].
  1218. """
  1219. self.desc = desc + ': ' if desc else ''
  1220. if refresh:
  1221. self.refresh()
  1222. def set_description_str(self, desc=None, refresh=True):
  1223. """Set/modify description without ': ' appended."""
  1224. self.desc = desc or ''
  1225. if refresh:
  1226. self.refresh()
  1227. def set_postfix(self, ordered_dict=None, refresh=True, **kwargs):
  1228. """
  1229. Set/modify postfix (additional stats)
  1230. with automatic formatting based on datatype.
  1231. Parameters
  1232. ----------
  1233. ordered_dict : dict or OrderedDict, optional
  1234. refresh : bool, optional
  1235. Forces refresh [default: True].
  1236. kwargs : dict, optional
  1237. """
  1238. # Sort in alphabetical order to be more deterministic
  1239. postfix = OrderedDict([] if ordered_dict is None else ordered_dict)
  1240. for key in sorted(kwargs.keys()):
  1241. postfix[key] = kwargs[key]
  1242. # Preprocess stats according to datatype
  1243. for key in postfix.keys():
  1244. # Number: limit the length of the string
  1245. if isinstance(postfix[key], Number):
  1246. postfix[key] = self.format_num(postfix[key])
  1247. # Else for any other type, try to get the string conversion
  1248. elif not isinstance(postfix[key], str):
  1249. postfix[key] = str(postfix[key])
  1250. # Else if it's a string, don't need to preprocess anything
  1251. # Stitch together to get the final postfix
  1252. self.postfix = ', '.join(key + '=' + postfix[key].strip()
  1253. for key in postfix.keys())
  1254. if refresh:
  1255. self.refresh()
  1256. def set_postfix_str(self, s='', refresh=True):
  1257. """
  1258. Postfix without dictionary expansion, similar to prefix handling.
  1259. """
  1260. self.postfix = str(s)
  1261. if refresh:
  1262. self.refresh()
  1263. def moveto(self, n):
  1264. # TODO: private method
  1265. self.fp.write('\n' * n + _term_move_up() * -n)
  1266. getattr(self.fp, 'flush', lambda: None)()
  1267. @property
  1268. def format_dict(self):
  1269. """Public API for read-only member access."""
  1270. if self.disable and not hasattr(self, 'unit'):
  1271. return defaultdict(lambda: None, {
  1272. 'n': self.n, 'total': self.total, 'elapsed': 0, 'unit': 'it'})
  1273. if self.dynamic_ncols:
  1274. self.ncols, self.nrows = self.dynamic_ncols(self.fp)
  1275. return {
  1276. 'n': self.n, 'total': self.total,
  1277. 'elapsed': self._time() - self.start_t if hasattr(self, 'start_t') else 0,
  1278. 'ncols': self.ncols, 'nrows': self.nrows, 'prefix': self.desc,
  1279. 'ascii': self.ascii, 'unit': self.unit, 'unit_scale': self.unit_scale,
  1280. 'rate': self._ema_dn() / self._ema_dt() if self._ema_dt() else None,
  1281. 'bar_format': self.bar_format, 'postfix': self.postfix,
  1282. 'unit_divisor': self.unit_divisor, 'initial': self.initial,
  1283. 'colour': self.colour}
  1284. def display(self, msg=None, pos=None):
  1285. """
  1286. Use `self.sp` to display `msg` in the specified `pos`.
  1287. Consider overloading this function when inheriting to use e.g.:
  1288. `self.some_frontend(**self.format_dict)` instead of `self.sp`.
  1289. Parameters
  1290. ----------
  1291. msg : str, optional. What to display (default: `repr(self)`).
  1292. pos : int, optional. Position to `moveto`
  1293. (default: `abs(self.pos)`).
  1294. """
  1295. if pos is None:
  1296. pos = abs(self.pos)
  1297. nrows = self.nrows or 20
  1298. if pos >= nrows - 1:
  1299. if pos >= nrows:
  1300. return False
  1301. if msg or msg is None: # override at `nrows - 1`
  1302. msg = " ... (more hidden) ..."
  1303. if not hasattr(self, "sp"):
  1304. raise TqdmDeprecationWarning(
  1305. "Please use `tqdm.gui.tqdm(...)`"
  1306. " instead of `tqdm(..., gui=True)`\n",
  1307. fp_write=getattr(self.fp, 'write', sys.stderr.write))
  1308. if pos:
  1309. self.moveto(pos)
  1310. self.sp(self.__str__() if msg is None else msg)
  1311. if pos:
  1312. self.moveto(-pos)
  1313. return True
  1314. @classmethod
  1315. @contextmanager
  1316. def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs):
  1317. """
  1318. stream : file-like object.
  1319. method : str, "read" or "write". The result of `read()` and
  1320. the first argument of `write()` should have a `len()`.
  1321. >>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
  1322. ... while True:
  1323. ... chunk = fobj.read(chunk_size)
  1324. ... if not chunk:
  1325. ... break
  1326. """
  1327. with cls(total=total, **tqdm_kwargs) as t:
  1328. if bytes:
  1329. t.unit = "B"
  1330. t.unit_scale = True
  1331. t.unit_divisor = 1024
  1332. yield CallbackIOWrapper(t.update, stream, method)
  1333. def trange(*args, **kwargs):
  1334. """Shortcut for tqdm(range(*args), **kwargs)."""
  1335. return tqdm(range(*args), **kwargs)