std.py 56 KB

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