std.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  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, timezone
  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().__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 f'{num:1.2f}{unit}{suffix}'
  347. return f'{num:2.1f}{unit}{suffix}'
  348. return f'{num:3.0f}{unit}{suffix}'
  349. num /= divisor
  350. return f'{num:3.1f}Y{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. return f'{h:d}:{m:02d}:{s:02d}' if h else f'{m:02d}:{s:02d}'
  367. @staticmethod
  368. def format_num(n):
  369. """
  370. Intelligent scientific notation (.3g).
  371. Parameters
  372. ----------
  373. n : int or float or Numeric
  374. A Number.
  375. Returns
  376. -------
  377. out : str
  378. Formatted number.
  379. """
  380. f = f'{n:.3g}'.replace('e+0', 'e+').replace('e-0', 'e-')
  381. n = str(n)
  382. return f if len(f) < len(n) else n
  383. @staticmethod
  384. def status_printer(file):
  385. """
  386. Manage the printing and in-place updating of a line of characters.
  387. Note that if the string is longer than a line, then in-place
  388. updating may not work (it will print a new line at each refresh).
  389. """
  390. fp = file
  391. fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover
  392. if fp in (sys.stderr, sys.stdout):
  393. getattr(sys.stderr, 'flush', lambda: None)()
  394. getattr(sys.stdout, 'flush', lambda: None)()
  395. def fp_write(s):
  396. fp.write(str(s))
  397. fp_flush()
  398. last_len = [0]
  399. def print_status(s):
  400. len_s = disp_len(s)
  401. fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
  402. last_len[0] = len_s
  403. return print_status
  404. @staticmethod
  405. def format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it',
  406. unit_scale=False, rate=None, bar_format=None, postfix=None,
  407. unit_divisor=1000, initial=0, colour=None, **extra_kwargs):
  408. """
  409. Return a string-based progress bar given some parameters
  410. Parameters
  411. ----------
  412. n : int or float
  413. Number of finished iterations.
  414. total : int or float
  415. The expected total number of iterations. If meaningless (None),
  416. only basic progress statistics are displayed (no ETA).
  417. elapsed : float
  418. Number of seconds passed since start.
  419. ncols : int, optional
  420. The width of the entire output message. If specified,
  421. dynamically resizes `{bar}` to stay within this bound
  422. [default: None]. If `0`, will not print any bar (only stats).
  423. The fallback is `{bar:10}`.
  424. prefix : str, optional
  425. Prefix message (included in total width) [default: ''].
  426. Use as {desc} in bar_format string.
  427. ascii : bool, optional or str, optional
  428. If not set, use unicode (smooth blocks) to fill the meter
  429. [default: False]. The fallback is to use ASCII characters
  430. " 123456789#".
  431. unit : str, optional
  432. The iteration unit [default: 'it'].
  433. unit_scale : bool or int or float, optional
  434. If 1 or True, the number of iterations will be printed with an
  435. appropriate SI metric prefix (k = 10^3, M = 10^6, etc.)
  436. [default: False]. If any other non-zero number, will scale
  437. `total` and `n`.
  438. rate : float, optional
  439. Manual override for iteration rate.
  440. If [default: None], uses n/elapsed.
  441. bar_format : str, optional
  442. Specify a custom bar string formatting. May impact performance.
  443. [default: '{l_bar}{bar}{r_bar}'], where
  444. l_bar='{desc}: {percentage:3.0f}%|' and
  445. r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
  446. '{rate_fmt}{postfix}]'
  447. Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
  448. percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
  449. rate, rate_fmt, rate_noinv, rate_noinv_fmt,
  450. rate_inv, rate_inv_fmt, postfix, unit_divisor,
  451. remaining, remaining_s, eta.
  452. Note that a trailing ": " is automatically removed after {desc}
  453. if the latter is empty.
  454. postfix : *, optional
  455. Similar to `prefix`, but placed at the end
  456. (e.g. for additional stats).
  457. Note: postfix is usually a string (not a dict) for this method,
  458. and will if possible be set to postfix = ', ' + postfix.
  459. However other types are supported (#382).
  460. unit_divisor : float, optional
  461. [default: 1000], ignored unless `unit_scale` is True.
  462. initial : int or float, optional
  463. The initial counter value [default: 0].
  464. colour : str, optional
  465. Bar colour (e.g. 'green', '#00ff00').
  466. Returns
  467. -------
  468. out : Formatted meter and stats, ready to display.
  469. """
  470. # sanity check: total
  471. if total and n >= (total + 0.5): # allow float imprecision (#849)
  472. total = None
  473. # apply custom scale if necessary
  474. if unit_scale and unit_scale not in (True, 1):
  475. if total:
  476. total *= unit_scale
  477. n *= unit_scale
  478. if rate:
  479. rate *= unit_scale # by default rate = self.avg_dn / self.avg_dt
  480. unit_scale = False
  481. elapsed_str = tqdm.format_interval(elapsed)
  482. # if unspecified, attempt to use rate = average speed
  483. # (we allow manual override since predicting time is an arcane art)
  484. if rate is None and elapsed:
  485. rate = (n - initial) / elapsed
  486. inv_rate = 1 / rate if rate else None
  487. format_sizeof = tqdm.format_sizeof
  488. rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else f'{rate:5.2f}')
  489. if rate else '?') + unit + '/s'
  490. rate_inv_fmt = (
  491. (format_sizeof(inv_rate) if unit_scale else f'{inv_rate:5.2f}')
  492. if inv_rate else '?') + 's/' + unit
  493. rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt
  494. if unit_scale:
  495. n_fmt = format_sizeof(n, divisor=unit_divisor)
  496. total_fmt = format_sizeof(total, divisor=unit_divisor) if total is not None else '?'
  497. else:
  498. n_fmt = str(n)
  499. total_fmt = str(total) if total is not None else '?'
  500. try:
  501. postfix = ', ' + postfix if postfix else ''
  502. except TypeError:
  503. pass
  504. remaining = (total - n) / rate if rate and total else 0
  505. remaining_str = tqdm.format_interval(remaining) if rate else '?'
  506. try:
  507. eta_dt = (datetime.now() + timedelta(seconds=remaining)
  508. if rate and total else datetime.fromtimestamp(0, timezone.utc))
  509. except OverflowError:
  510. eta_dt = datetime.max
  511. # format the stats displayed to the left and right sides of the bar
  512. if prefix:
  513. # old prefix setup work around
  514. bool_prefix_colon_already = (prefix[-2:] == ": ")
  515. l_bar = prefix if bool_prefix_colon_already else prefix + ": "
  516. else:
  517. l_bar = ''
  518. r_bar = f'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}{postfix}]'
  519. # Custom bar formatting
  520. # Populate a dict with all available progress indicators
  521. format_dict = {
  522. # slight extension of self.format_dict
  523. 'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt,
  524. 'elapsed': elapsed_str, 'elapsed_s': elapsed,
  525. 'ncols': ncols, 'desc': prefix or '', 'unit': unit,
  526. 'rate': inv_rate if inv_rate and inv_rate > 1 else rate,
  527. 'rate_fmt': rate_fmt, 'rate_noinv': rate,
  528. 'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate,
  529. 'rate_inv_fmt': rate_inv_fmt,
  530. 'postfix': postfix, 'unit_divisor': unit_divisor,
  531. 'colour': colour,
  532. # plus more useful definitions
  533. 'remaining': remaining_str, 'remaining_s': remaining,
  534. 'l_bar': l_bar, 'r_bar': r_bar, 'eta': eta_dt,
  535. **extra_kwargs}
  536. # total is known: we can predict some stats
  537. if total:
  538. # fractional and percentage progress
  539. frac = n / total
  540. percentage = frac * 100
  541. l_bar += f'{percentage:3.0f}%|'
  542. if ncols == 0:
  543. return l_bar[:-1] + r_bar[1:]
  544. format_dict.update(l_bar=l_bar)
  545. if bar_format:
  546. format_dict.update(percentage=percentage)
  547. # auto-remove colon for empty `{desc}`
  548. if not prefix:
  549. bar_format = bar_format.replace("{desc}: ", '')
  550. else:
  551. bar_format = "{l_bar}{bar}{r_bar}"
  552. full_bar = FormatReplace()
  553. nobar = bar_format.format(bar=full_bar, **format_dict)
  554. if not full_bar.format_called:
  555. return nobar # no `{bar}`; nothing else to do
  556. # Formatting progress bar space available for bar's display
  557. full_bar = Bar(frac,
  558. max(1, ncols - disp_len(nobar)) if ncols else 10,
  559. charset=Bar.ASCII if ascii is True else ascii or Bar.UTF,
  560. colour=colour)
  561. if not _is_ascii(full_bar.charset) and _is_ascii(bar_format):
  562. bar_format = str(bar_format)
  563. res = bar_format.format(bar=full_bar, **format_dict)
  564. return disp_trim(res, ncols) if ncols else res
  565. elif bar_format:
  566. # user-specified bar_format but no total
  567. l_bar += '|'
  568. format_dict.update(l_bar=l_bar, percentage=0)
  569. full_bar = FormatReplace()
  570. nobar = bar_format.format(bar=full_bar, **format_dict)
  571. if not full_bar.format_called:
  572. return nobar
  573. full_bar = Bar(0,
  574. max(1, ncols - disp_len(nobar)) if ncols else 10,
  575. charset=Bar.BLANK, colour=colour)
  576. res = bar_format.format(bar=full_bar, **format_dict)
  577. return disp_trim(res, ncols) if ncols else res
  578. else:
  579. # no total: no progressbar, ETA, just progress stats
  580. return (f'{(prefix + ": ") if prefix else ""}'
  581. f'{n_fmt}{unit} [{elapsed_str}, {rate_fmt}{postfix}]')
  582. def __new__(cls, *_, **__):
  583. instance = object.__new__(cls)
  584. with cls.get_lock(): # also constructs lock if non-existent
  585. cls._instances.add(instance)
  586. # create monitoring thread
  587. if cls.monitor_interval and (cls.monitor is None
  588. or not cls.monitor.report()):
  589. try:
  590. cls.monitor = TMonitor(cls, cls.monitor_interval)
  591. except Exception as e: # pragma: nocover
  592. warn("tqdm:disabling monitor support"
  593. " (monitor_interval = 0) due to:\n" + str(e),
  594. TqdmMonitorWarning, stacklevel=2)
  595. cls.monitor_interval = 0
  596. return instance
  597. @classmethod
  598. def _get_free_pos(cls, instance=None):
  599. """Skips specified instance."""
  600. positions = {abs(inst.pos) for inst in cls._instances
  601. if inst is not instance and hasattr(inst, "pos")}
  602. return min(set(range(len(positions) + 1)).difference(positions))
  603. @classmethod
  604. def _decr_instances(cls, instance):
  605. """
  606. Remove from list and reposition another unfixed bar
  607. to fill the new gap.
  608. This means that by default (where all nested bars are unfixed),
  609. order is not maintained but screen flicker/blank space is minimised.
  610. (tqdm<=4.44.1 moved ALL subsequent unfixed bars up.)
  611. """
  612. with cls._lock:
  613. try:
  614. cls._instances.remove(instance)
  615. except KeyError:
  616. # if not instance.gui: # pragma: no cover
  617. # raise
  618. pass # py2: maybe magically removed already
  619. # else:
  620. if not instance.gui:
  621. last = (instance.nrows or 20) - 1
  622. # find unfixed (`pos >= 0`) overflow (`pos >= nrows - 1`)
  623. instances = list(filter(
  624. lambda i: hasattr(i, "pos") and last <= i.pos,
  625. cls._instances))
  626. # set first found to current `pos`
  627. if instances:
  628. inst = min(instances, key=lambda i: i.pos)
  629. inst.clear(nolock=True)
  630. inst.pos = abs(instance.pos)
  631. @classmethod
  632. def write(cls, s, file=None, end="\n", nolock=False):
  633. """Print a message via tqdm (without overlap with bars)."""
  634. fp = file if file is not None else sys.stdout
  635. with cls.external_write_mode(file=file, nolock=nolock):
  636. # Write the message
  637. fp.write(s)
  638. fp.write(end)
  639. @classmethod
  640. @contextmanager
  641. def external_write_mode(cls, file=None, nolock=False):
  642. """
  643. Disable tqdm within context and refresh tqdm when exits.
  644. Useful when writing to standard output stream
  645. """
  646. fp = file if file is not None else sys.stdout
  647. try:
  648. if not nolock:
  649. cls.get_lock().acquire()
  650. # Clear all bars
  651. inst_cleared = []
  652. for inst in getattr(cls, '_instances', []):
  653. # Clear instance if in the target output file
  654. # or if write output + tqdm output are both either
  655. # sys.stdout or sys.stderr (because both are mixed in terminal)
  656. if hasattr(inst, "start_t") and (inst.fp == fp or all(
  657. f in (sys.stdout, sys.stderr) for f in (fp, inst.fp))):
  658. inst.clear(nolock=True)
  659. inst_cleared.append(inst)
  660. yield
  661. # Force refresh display of bars we cleared
  662. for inst in inst_cleared:
  663. inst.refresh(nolock=True)
  664. finally:
  665. if not nolock:
  666. cls._lock.release()
  667. @classmethod
  668. def set_lock(cls, lock):
  669. """Set the global lock."""
  670. cls._lock = lock
  671. @classmethod
  672. def get_lock(cls):
  673. """Get the global lock. Construct it if it does not exist."""
  674. if not hasattr(cls, '_lock'):
  675. cls._lock = TqdmDefaultWriteLock()
  676. return cls._lock
  677. @classmethod
  678. def pandas(cls, **tqdm_kwargs):
  679. """
  680. Registers the current `tqdm` class with
  681. pandas.core.
  682. ( frame.DataFrame
  683. | series.Series
  684. | groupby.(generic.)DataFrameGroupBy
  685. | groupby.(generic.)SeriesGroupBy
  686. ).progress_apply
  687. A new instance will be created every time `progress_apply` is called,
  688. and each instance will automatically `close()` upon completion.
  689. Parameters
  690. ----------
  691. tqdm_kwargs : arguments for the tqdm instance
  692. Examples
  693. --------
  694. >>> import pandas as pd
  695. >>> import numpy as np
  696. >>> from tqdm import tqdm
  697. >>> from tqdm.gui import tqdm as tqdm_gui
  698. >>>
  699. >>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
  700. >>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc
  701. >>> # Now you can use `progress_apply` instead of `apply`
  702. >>> df.groupby(0).progress_apply(lambda x: x**2)
  703. References
  704. ----------
  705. <https://stackoverflow.com/questions/18603270/\
  706. progress-indicator-during-pandas-operations-python>
  707. """
  708. from warnings import catch_warnings, simplefilter
  709. from pandas.core.frame import DataFrame
  710. from pandas.core.series import Series
  711. try:
  712. with catch_warnings():
  713. simplefilter("ignore", category=FutureWarning)
  714. from pandas import Panel
  715. except ImportError: # pandas>=1.2.0
  716. Panel = None
  717. Rolling, Expanding = None, None
  718. try: # pandas>=1.0.0
  719. from pandas.core.window.rolling import _Rolling_and_Expanding
  720. except ImportError:
  721. try: # pandas>=0.18.0
  722. from pandas.core.window import _Rolling_and_Expanding
  723. except ImportError: # pandas>=1.2.0
  724. try: # pandas>=1.2.0
  725. from pandas.core.window.expanding import Expanding
  726. from pandas.core.window.rolling import Rolling
  727. _Rolling_and_Expanding = Rolling, Expanding
  728. except ImportError: # pragma: no cover
  729. _Rolling_and_Expanding = None
  730. try: # pandas>=0.25.0
  731. from pandas.core.groupby.generic import SeriesGroupBy # , NDFrameGroupBy
  732. from pandas.core.groupby.generic import DataFrameGroupBy
  733. except ImportError: # pragma: no cover
  734. try: # pandas>=0.23.0
  735. from pandas.core.groupby.groupby import DataFrameGroupBy, SeriesGroupBy
  736. except ImportError:
  737. from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy
  738. try: # pandas>=0.23.0
  739. from pandas.core.groupby.groupby import GroupBy
  740. except ImportError: # pragma: no cover
  741. from pandas.core.groupby import GroupBy
  742. try: # pandas>=0.23.0
  743. from pandas.core.groupby.groupby import PanelGroupBy
  744. except ImportError:
  745. try:
  746. from pandas.core.groupby import PanelGroupBy
  747. except ImportError: # pandas>=0.25.0
  748. PanelGroupBy = None
  749. tqdm_kwargs = tqdm_kwargs.copy()
  750. deprecated_t = [tqdm_kwargs.pop('deprecated_t', None)]
  751. def inner_generator(df_function='apply'):
  752. def inner(df, func, *args, **kwargs):
  753. """
  754. Parameters
  755. ----------
  756. df : (DataFrame|Series)[GroupBy]
  757. Data (may be grouped).
  758. func : function
  759. To be applied on the (grouped) data.
  760. **kwargs : optional
  761. Transmitted to `df.apply()`.
  762. """
  763. # Precompute total iterations
  764. total = tqdm_kwargs.pop("total", getattr(df, 'ngroups', None))
  765. if total is None: # not grouped
  766. if df_function == 'applymap':
  767. total = df.size
  768. elif isinstance(df, Series):
  769. total = len(df)
  770. elif (_Rolling_and_Expanding is None or
  771. not isinstance(df, _Rolling_and_Expanding)):
  772. # DataFrame or Panel
  773. axis = kwargs.get('axis', 0)
  774. if axis == 'index':
  775. axis = 0
  776. elif axis == 'columns':
  777. axis = 1
  778. # when axis=0, total is shape[axis1]
  779. total = df.size // df.shape[axis]
  780. # Init bar
  781. if deprecated_t[0] is not None:
  782. t = deprecated_t[0]
  783. deprecated_t[0] = None
  784. else:
  785. t = cls(total=total, **tqdm_kwargs)
  786. if len(args) > 0:
  787. # *args intentionally not supported (see #244, #299)
  788. TqdmDeprecationWarning(
  789. "Except func, normal arguments are intentionally" +
  790. " not supported by" +
  791. " `(DataFrame|Series|GroupBy).progress_apply`." +
  792. " Use keyword arguments instead.",
  793. fp_write=getattr(t.fp, 'write', sys.stderr.write))
  794. try: # pandas>=1.3.0
  795. from pandas.core.common import is_builtin_func
  796. except ImportError:
  797. is_builtin_func = df._is_builtin_func
  798. try:
  799. func = is_builtin_func(func)
  800. except TypeError:
  801. pass
  802. # Define bar updating wrapper
  803. def wrapper(*args, **kwargs):
  804. # update tbar correctly
  805. # it seems `pandas apply` calls `func` twice
  806. # on the first column/row to decide whether it can
  807. # take a fast or slow code path; so stop when t.total==t.n
  808. t.update(n=1 if not t.total or t.n < t.total else 0)
  809. return func(*args, **kwargs)
  810. # Apply the provided function (in **kwargs)
  811. # on the df using our wrapper (which provides bar updating)
  812. try:
  813. return getattr(df, df_function)(wrapper, **kwargs)
  814. finally:
  815. t.close()
  816. return inner
  817. # Monkeypatch pandas to provide easy methods
  818. # Enable custom tqdm progress in pandas!
  819. Series.progress_apply = inner_generator()
  820. SeriesGroupBy.progress_apply = inner_generator()
  821. Series.progress_map = inner_generator('map')
  822. SeriesGroupBy.progress_map = inner_generator('map')
  823. DataFrame.progress_apply = inner_generator()
  824. DataFrameGroupBy.progress_apply = inner_generator()
  825. DataFrame.progress_applymap = inner_generator('applymap')
  826. DataFrame.progress_map = inner_generator('map')
  827. DataFrameGroupBy.progress_map = inner_generator('map')
  828. if Panel is not None:
  829. Panel.progress_apply = inner_generator()
  830. if PanelGroupBy is not None:
  831. PanelGroupBy.progress_apply = inner_generator()
  832. GroupBy.progress_apply = inner_generator()
  833. GroupBy.progress_aggregate = inner_generator('aggregate')
  834. GroupBy.progress_transform = inner_generator('transform')
  835. if Rolling is not None and Expanding is not None:
  836. Rolling.progress_apply = inner_generator()
  837. Expanding.progress_apply = inner_generator()
  838. elif _Rolling_and_Expanding is not None:
  839. _Rolling_and_Expanding.progress_apply = inner_generator()
  840. # override defaults via env vars
  841. @envwrap("TQDM_", is_method=True, types={'total': float, 'ncols': int, 'miniters': float,
  842. 'position': int, 'nrows': int})
  843. def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
  844. ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None,
  845. ascii=None, disable=False, unit='it', unit_scale=False,
  846. dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0,
  847. position=None, postfix=None, unit_divisor=1000, write_bytes=False,
  848. lock_args=None, nrows=None, colour=None, delay=0.0, gui=False,
  849. **kwargs):
  850. """see tqdm.tqdm for arguments"""
  851. if file is None:
  852. file = sys.stderr
  853. if write_bytes:
  854. # Despite coercing unicode into bytes, py2 sys.std* streams
  855. # should have bytes written to them.
  856. file = SimpleTextIOWrapper(
  857. file, encoding=getattr(file, 'encoding', None) or 'utf-8')
  858. file = DisableOnWriteError(file, tqdm_instance=self)
  859. if disable is None and hasattr(file, "isatty") and not file.isatty():
  860. disable = True
  861. if total is None and iterable is not None:
  862. try:
  863. total = len(iterable)
  864. except (TypeError, AttributeError):
  865. total = None
  866. if total == float("inf"):
  867. # Infinite iterations, behave same as unknown
  868. total = None
  869. if disable:
  870. self.iterable = iterable
  871. self.disable = disable
  872. with self._lock:
  873. self.pos = self._get_free_pos(self)
  874. self._instances.remove(self)
  875. self.n = initial
  876. self.total = total
  877. self.leave = leave
  878. return
  879. if kwargs:
  880. self.disable = True
  881. with self._lock:
  882. self.pos = self._get_free_pos(self)
  883. self._instances.remove(self)
  884. raise (
  885. TqdmDeprecationWarning(
  886. "`nested` is deprecated and automated.\n"
  887. "Use `position` instead for manual control.\n",
  888. fp_write=getattr(file, 'write', sys.stderr.write))
  889. if "nested" in kwargs else
  890. TqdmKeyError("Unknown argument(s): " + str(kwargs)))
  891. # Preprocess the arguments
  892. if (
  893. (ncols is None or nrows is None) and (file in (sys.stderr, sys.stdout))
  894. ) or dynamic_ncols: # pragma: no cover
  895. if dynamic_ncols:
  896. dynamic_ncols = _screen_shape_wrapper()
  897. if dynamic_ncols:
  898. ncols, nrows = dynamic_ncols(file)
  899. else:
  900. _dynamic_ncols = _screen_shape_wrapper()
  901. if _dynamic_ncols:
  902. _ncols, _nrows = _dynamic_ncols(file)
  903. if ncols is None:
  904. ncols = _ncols
  905. if nrows is None:
  906. nrows = _nrows
  907. if miniters is None:
  908. miniters = 0
  909. dynamic_miniters = True
  910. else:
  911. dynamic_miniters = False
  912. if mininterval is None:
  913. mininterval = 0
  914. if maxinterval is None:
  915. maxinterval = 0
  916. if ascii is None:
  917. ascii = not _supports_unicode(file)
  918. if bar_format and ascii is not True and not _is_ascii(ascii):
  919. # Convert bar format into unicode since terminal uses unicode
  920. bar_format = str(bar_format)
  921. if smoothing is None:
  922. smoothing = 0
  923. # Store the arguments
  924. self.iterable = iterable
  925. self.desc = desc or ''
  926. self.total = total
  927. self.leave = leave
  928. self.fp = file
  929. self.ncols = ncols
  930. self.nrows = nrows
  931. self.mininterval = mininterval
  932. self.maxinterval = maxinterval
  933. self.miniters = miniters
  934. self.dynamic_miniters = dynamic_miniters
  935. self.ascii = ascii
  936. self.disable = disable
  937. self.unit = unit
  938. self.unit_scale = unit_scale
  939. self.unit_divisor = unit_divisor
  940. self.initial = initial
  941. self.lock_args = lock_args
  942. self.delay = delay
  943. self.gui = gui
  944. self.dynamic_ncols = dynamic_ncols
  945. self.smoothing = smoothing
  946. self._ema_dn = EMA(smoothing)
  947. self._ema_dt = EMA(smoothing)
  948. self._ema_miniters = EMA(smoothing)
  949. self.bar_format = bar_format
  950. self.postfix = None
  951. self.colour = colour
  952. self._time = time
  953. if postfix:
  954. try:
  955. self.set_postfix(refresh=False, **postfix)
  956. except TypeError:
  957. self.postfix = postfix
  958. # Init the iterations counters
  959. self.last_print_n = initial
  960. self.n = initial
  961. # if nested, at initial sp() call we replace '\r' by '\n' to
  962. # not overwrite the outer progress bar
  963. with self._lock:
  964. # mark fixed positions as negative
  965. self.pos = self._get_free_pos(self) if position is None else -position
  966. if not gui:
  967. # Initialize the screen printer
  968. self.sp = self.status_printer(self.fp)
  969. if delay <= 0:
  970. self.refresh(lock_args=self.lock_args)
  971. # Init the time counter
  972. self.last_print_t = self._time()
  973. # NB: Avoid race conditions by setting start_t at the very end of init
  974. self.start_t = self.last_print_t
  975. def __bool__(self):
  976. if self.total is not None:
  977. return self.total > 0
  978. if self.iterable is None:
  979. raise TypeError('bool() undefined when iterable == total == None')
  980. return bool(self.iterable)
  981. def __len__(self):
  982. return (
  983. self.total if self.iterable is None
  984. else self.iterable.shape[0] if hasattr(self.iterable, "shape")
  985. else len(self.iterable) if hasattr(self.iterable, "__len__")
  986. else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__")
  987. else getattr(self, "total", None))
  988. def __reversed__(self):
  989. try:
  990. orig = self.iterable
  991. except AttributeError:
  992. raise TypeError("'tqdm' object is not reversible")
  993. else:
  994. self.iterable = reversed(self.iterable)
  995. return self.__iter__()
  996. finally:
  997. self.iterable = orig
  998. def __contains__(self, item):
  999. contains = getattr(self.iterable, '__contains__', None)
  1000. return contains(item) if contains is not None else item in self.__iter__()
  1001. def __enter__(self):
  1002. return self
  1003. def __exit__(self, exc_type, exc_value, traceback):
  1004. try:
  1005. self.close()
  1006. except AttributeError:
  1007. # maybe eager thread cleanup upon external error
  1008. if (exc_type, exc_value, traceback) == (None, None, None):
  1009. raise
  1010. warn("AttributeError ignored", TqdmWarning, stacklevel=2)
  1011. def __del__(self):
  1012. self.close()
  1013. def __str__(self):
  1014. return self.format_meter(**self.format_dict)
  1015. @property
  1016. def _comparable(self):
  1017. return abs(getattr(self, "pos", 1 << 31))
  1018. def __hash__(self):
  1019. return id(self)
  1020. def __iter__(self):
  1021. """Backward-compatibility to use: for x in tqdm(iterable)"""
  1022. # Inlining instance variables as locals (speed optimisation)
  1023. iterable = self.iterable
  1024. # If the bar is disabled, then just walk the iterable
  1025. # (note: keep this check outside the loop for performance)
  1026. if self.disable:
  1027. for obj in iterable:
  1028. yield obj
  1029. return
  1030. mininterval = self.mininterval
  1031. last_print_t = self.last_print_t
  1032. last_print_n = self.last_print_n
  1033. min_start_t = self.start_t + self.delay
  1034. n = self.n
  1035. time = self._time
  1036. try:
  1037. for obj in iterable:
  1038. yield obj
  1039. # Update and possibly print the progressbar.
  1040. # Note: does not call self.update(1) for speed optimisation.
  1041. n += 1
  1042. if n - last_print_n >= self.miniters:
  1043. cur_t = time()
  1044. dt = cur_t - last_print_t
  1045. if dt >= mininterval and cur_t >= min_start_t:
  1046. self.update(n - last_print_n)
  1047. last_print_n = self.last_print_n
  1048. last_print_t = self.last_print_t
  1049. finally:
  1050. self.n = n
  1051. self.close()
  1052. def update(self, n=1):
  1053. """
  1054. Manually update the progress bar, useful for streams
  1055. such as reading files.
  1056. E.g.:
  1057. >>> t = tqdm(total=filesize) # Initialise
  1058. >>> for current_buffer in stream:
  1059. ... ...
  1060. ... t.update(len(current_buffer))
  1061. >>> t.close()
  1062. The last line is highly recommended, but possibly not necessary if
  1063. `t.update()` will be called in such a way that `filesize` will be
  1064. exactly reached and printed.
  1065. Parameters
  1066. ----------
  1067. n : int or float, optional
  1068. Increment to add to the internal counter of iterations
  1069. [default: 1]. If using float, consider specifying `{n:.3f}`
  1070. or similar in `bar_format`, or specifying `unit_scale`.
  1071. Returns
  1072. -------
  1073. out : bool or None
  1074. True if a `display()` was triggered.
  1075. """
  1076. if self.disable:
  1077. return
  1078. if n < 0:
  1079. self.last_print_n += n # for auto-refresh logic to work
  1080. self.n += n
  1081. # check counter first to reduce calls to time()
  1082. if self.n - self.last_print_n >= self.miniters:
  1083. cur_t = self._time()
  1084. dt = cur_t - self.last_print_t
  1085. if dt >= self.mininterval and cur_t >= self.start_t + self.delay:
  1086. cur_t = self._time()
  1087. dn = self.n - self.last_print_n # >= n
  1088. if self.smoothing and dt and dn:
  1089. # EMA (not just overall average)
  1090. self._ema_dn(dn)
  1091. self._ema_dt(dt)
  1092. self.refresh(lock_args=self.lock_args)
  1093. if self.dynamic_miniters:
  1094. # If no `miniters` was specified, adjust automatically to the
  1095. # maximum iteration rate seen so far between two prints.
  1096. # e.g.: After running `tqdm.update(5)`, subsequent
  1097. # calls to `tqdm.update()` will only cause an update after
  1098. # at least 5 more iterations.
  1099. if self.maxinterval and dt >= self.maxinterval:
  1100. self.miniters = dn * (self.mininterval or self.maxinterval) / dt
  1101. elif self.smoothing:
  1102. # EMA miniters update
  1103. self.miniters = self._ema_miniters(
  1104. dn * (self.mininterval / dt if self.mininterval and dt
  1105. else 1))
  1106. else:
  1107. # max iters between two prints
  1108. self.miniters = max(self.miniters, dn)
  1109. # Store old values for next call
  1110. self.last_print_n = self.n
  1111. self.last_print_t = cur_t
  1112. return True
  1113. def close(self):
  1114. """Cleanup and (if leave=False) close the progressbar."""
  1115. if self.disable:
  1116. return
  1117. # Prevent multiple closures
  1118. self.disable = True
  1119. # decrement instance pos and remove from internal set
  1120. pos = abs(self.pos)
  1121. self._decr_instances(self)
  1122. if self.last_print_t < self.start_t + self.delay:
  1123. # haven't ever displayed; nothing to clear
  1124. return
  1125. # GUI mode
  1126. if getattr(self, 'sp', None) is None:
  1127. return
  1128. # annoyingly, _supports_unicode isn't good enough
  1129. def fp_write(s):
  1130. self.fp.write(str(s))
  1131. try:
  1132. fp_write('')
  1133. except ValueError as e:
  1134. if 'closed' in str(e):
  1135. return
  1136. raise # pragma: no cover
  1137. leave = pos == 0 if self.leave is None else self.leave
  1138. with self._lock:
  1139. if leave:
  1140. # stats for overall rate (no weighted average)
  1141. self._ema_dt = lambda: None
  1142. self.display(pos=0)
  1143. fp_write('\n')
  1144. else:
  1145. # clear previous display
  1146. if self.display(msg='', pos=pos) and not pos:
  1147. fp_write('\r')
  1148. def clear(self, nolock=False):
  1149. """Clear current bar display."""
  1150. if self.disable:
  1151. return
  1152. if not nolock:
  1153. self._lock.acquire()
  1154. pos = abs(self.pos)
  1155. if pos < (self.nrows or 20):
  1156. self.moveto(pos)
  1157. self.sp('')
  1158. self.fp.write('\r') # place cursor back at the beginning of line
  1159. self.moveto(-pos)
  1160. if not nolock:
  1161. self._lock.release()
  1162. def refresh(self, nolock=False, lock_args=None):
  1163. """
  1164. Force refresh the display of this bar.
  1165. Parameters
  1166. ----------
  1167. nolock : bool, optional
  1168. If `True`, does not lock.
  1169. If [default: `False`]: calls `acquire()` on internal lock.
  1170. lock_args : tuple, optional
  1171. Passed to internal lock's `acquire()`.
  1172. If specified, will only `display()` if `acquire()` returns `True`.
  1173. """
  1174. if self.disable:
  1175. return
  1176. if not nolock:
  1177. if lock_args:
  1178. if not self._lock.acquire(*lock_args):
  1179. return False
  1180. else:
  1181. self._lock.acquire()
  1182. self.display()
  1183. if not nolock:
  1184. self._lock.release()
  1185. return True
  1186. def unpause(self):
  1187. """Restart tqdm timer from last print time."""
  1188. if self.disable:
  1189. return
  1190. cur_t = self._time()
  1191. self.start_t += cur_t - self.last_print_t
  1192. self.last_print_t = cur_t
  1193. def reset(self, total=None):
  1194. """
  1195. Resets to 0 iterations for repeated use.
  1196. Consider combining with `leave=True`.
  1197. Parameters
  1198. ----------
  1199. total : int or float, optional. Total to use for the new bar.
  1200. """
  1201. self.n = 0
  1202. if total is not None:
  1203. self.total = total
  1204. if self.disable:
  1205. return
  1206. self.last_print_n = 0
  1207. self.last_print_t = self.start_t = self._time()
  1208. self._ema_dn = EMA(self.smoothing)
  1209. self._ema_dt = EMA(self.smoothing)
  1210. self._ema_miniters = EMA(self.smoothing)
  1211. self.refresh()
  1212. def set_description(self, desc=None, refresh=True):
  1213. """
  1214. Set/modify description of the progress bar.
  1215. Parameters
  1216. ----------
  1217. desc : str, optional
  1218. refresh : bool, optional
  1219. Forces refresh [default: True].
  1220. """
  1221. self.desc = desc + ': ' if desc else ''
  1222. if refresh:
  1223. self.refresh()
  1224. def set_description_str(self, desc=None, refresh=True):
  1225. """Set/modify description without ': ' appended."""
  1226. self.desc = desc or ''
  1227. if refresh:
  1228. self.refresh()
  1229. def set_postfix(self, ordered_dict=None, refresh=True, **kwargs):
  1230. """
  1231. Set/modify postfix (additional stats)
  1232. with automatic formatting based on datatype.
  1233. Parameters
  1234. ----------
  1235. ordered_dict : dict or OrderedDict, optional
  1236. refresh : bool, optional
  1237. Forces refresh [default: True].
  1238. kwargs : dict, optional
  1239. """
  1240. # Sort in alphabetical order to be more deterministic
  1241. postfix = OrderedDict([] if ordered_dict is None else ordered_dict)
  1242. for key in sorted(kwargs.keys()):
  1243. postfix[key] = kwargs[key]
  1244. # Preprocess stats according to datatype
  1245. for key in postfix.keys():
  1246. # Number: limit the length of the string
  1247. if isinstance(postfix[key], Number):
  1248. postfix[key] = self.format_num(postfix[key])
  1249. # Else for any other type, try to get the string conversion
  1250. elif not isinstance(postfix[key], str):
  1251. postfix[key] = str(postfix[key])
  1252. # Else if it's a string, don't need to preprocess anything
  1253. # Stitch together to get the final postfix
  1254. self.postfix = ', '.join(key + '=' + postfix[key].strip()
  1255. for key in postfix.keys())
  1256. if refresh:
  1257. self.refresh()
  1258. def set_postfix_str(self, s='', refresh=True):
  1259. """
  1260. Postfix without dictionary expansion, similar to prefix handling.
  1261. """
  1262. self.postfix = str(s)
  1263. if refresh:
  1264. self.refresh()
  1265. def moveto(self, n):
  1266. # TODO: private method
  1267. self.fp.write('\n' * n + _term_move_up() * -n)
  1268. getattr(self.fp, 'flush', lambda: None)()
  1269. @property
  1270. def format_dict(self):
  1271. """Public API for read-only member access."""
  1272. if self.disable and not hasattr(self, 'unit'):
  1273. return defaultdict(lambda: None, {
  1274. 'n': self.n, 'total': self.total, 'elapsed': 0, 'unit': 'it'})
  1275. if self.dynamic_ncols:
  1276. self.ncols, self.nrows = self.dynamic_ncols(self.fp)
  1277. return {
  1278. 'n': self.n, 'total': self.total,
  1279. 'elapsed': self._time() - self.start_t if hasattr(self, 'start_t') else 0,
  1280. 'ncols': self.ncols, 'nrows': self.nrows, 'prefix': self.desc,
  1281. 'ascii': self.ascii, 'unit': self.unit, 'unit_scale': self.unit_scale,
  1282. 'rate': self._ema_dn() / self._ema_dt() if self._ema_dt() else None,
  1283. 'bar_format': self.bar_format, 'postfix': self.postfix,
  1284. 'unit_divisor': self.unit_divisor, 'initial': self.initial,
  1285. 'colour': self.colour}
  1286. def display(self, msg=None, pos=None):
  1287. """
  1288. Use `self.sp` to display `msg` in the specified `pos`.
  1289. Consider overloading this function when inheriting to use e.g.:
  1290. `self.some_frontend(**self.format_dict)` instead of `self.sp`.
  1291. Parameters
  1292. ----------
  1293. msg : str, optional. What to display (default: `repr(self)`).
  1294. pos : int, optional. Position to `moveto`
  1295. (default: `abs(self.pos)`).
  1296. """
  1297. if pos is None:
  1298. pos = abs(self.pos)
  1299. nrows = self.nrows or 20
  1300. if pos >= nrows - 1:
  1301. if pos >= nrows:
  1302. return False
  1303. if msg or msg is None: # override at `nrows - 1`
  1304. msg = " ... (more hidden) ..."
  1305. if not hasattr(self, "sp"):
  1306. raise TqdmDeprecationWarning(
  1307. "Please use `tqdm.gui.tqdm(...)`"
  1308. " instead of `tqdm(..., gui=True)`\n",
  1309. fp_write=getattr(self.fp, 'write', sys.stderr.write))
  1310. if pos:
  1311. self.moveto(pos)
  1312. self.sp(self.__str__() if msg is None else msg)
  1313. if pos:
  1314. self.moveto(-pos)
  1315. return True
  1316. @classmethod
  1317. @contextmanager
  1318. def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs):
  1319. """
  1320. stream : file-like object.
  1321. method : str, "read" or "write". The result of `read()` and
  1322. the first argument of `write()` should have a `len()`.
  1323. >>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
  1324. ... while True:
  1325. ... chunk = fobj.read(chunk_size)
  1326. ... if not chunk:
  1327. ... break
  1328. """
  1329. with cls(total=total, **tqdm_kwargs) as t:
  1330. if bytes:
  1331. t.unit = "B"
  1332. t.unit_scale = True
  1333. t.unit_divisor = 1024
  1334. yield CallbackIOWrapper(t.update, stream, method)
  1335. def trange(*args, **kwargs):
  1336. """Shortcut for tqdm(range(*args), **kwargs)."""
  1337. return tqdm(range(*args), **kwargs)