annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/site-packages/tqdm-4.67.1.dist-info/METADATA @ 69:33d812a61356

planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author jpayne
date Tue, 18 Mar 2025 17:55:14 -0400
parents
children
rev   line source
jpayne@69 1 Metadata-Version: 2.1
jpayne@69 2 Name: tqdm
jpayne@69 3 Version: 4.67.1
jpayne@69 4 Summary: Fast, Extensible Progress Meter
jpayne@69 5 Maintainer-email: tqdm developers <devs@tqdm.ml>
jpayne@69 6 License: MPL-2.0 AND MIT
jpayne@69 7 Project-URL: homepage, https://tqdm.github.io
jpayne@69 8 Project-URL: repository, https://github.com/tqdm/tqdm
jpayne@69 9 Project-URL: changelog, https://tqdm.github.io/releases
jpayne@69 10 Project-URL: wiki, https://github.com/tqdm/tqdm/wiki
jpayne@69 11 Keywords: progressbar,progressmeter,progress,bar,meter,rate,eta,console,terminal,time
jpayne@69 12 Classifier: Development Status :: 5 - Production/Stable
jpayne@69 13 Classifier: Environment :: Console
jpayne@69 14 Classifier: Environment :: MacOS X
jpayne@69 15 Classifier: Environment :: Other Environment
jpayne@69 16 Classifier: Environment :: Win32 (MS Windows)
jpayne@69 17 Classifier: Environment :: X11 Applications
jpayne@69 18 Classifier: Framework :: IPython
jpayne@69 19 Classifier: Framework :: Jupyter
jpayne@69 20 Classifier: Intended Audience :: Developers
jpayne@69 21 Classifier: Intended Audience :: Education
jpayne@69 22 Classifier: Intended Audience :: End Users/Desktop
jpayne@69 23 Classifier: Intended Audience :: Other Audience
jpayne@69 24 Classifier: Intended Audience :: System Administrators
jpayne@69 25 Classifier: License :: OSI Approved :: MIT License
jpayne@69 26 Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
jpayne@69 27 Classifier: Operating System :: MacOS
jpayne@69 28 Classifier: Operating System :: MacOS :: MacOS X
jpayne@69 29 Classifier: Operating System :: Microsoft
jpayne@69 30 Classifier: Operating System :: Microsoft :: MS-DOS
jpayne@69 31 Classifier: Operating System :: Microsoft :: Windows
jpayne@69 32 Classifier: Operating System :: POSIX
jpayne@69 33 Classifier: Operating System :: POSIX :: BSD
jpayne@69 34 Classifier: Operating System :: POSIX :: BSD :: FreeBSD
jpayne@69 35 Classifier: Operating System :: POSIX :: Linux
jpayne@69 36 Classifier: Operating System :: POSIX :: SunOS/Solaris
jpayne@69 37 Classifier: Operating System :: Unix
jpayne@69 38 Classifier: Programming Language :: Python
jpayne@69 39 Classifier: Programming Language :: Python :: 3
jpayne@69 40 Classifier: Programming Language :: Python :: 3.7
jpayne@69 41 Classifier: Programming Language :: Python :: 3.8
jpayne@69 42 Classifier: Programming Language :: Python :: 3.9
jpayne@69 43 Classifier: Programming Language :: Python :: 3.10
jpayne@69 44 Classifier: Programming Language :: Python :: 3.11
jpayne@69 45 Classifier: Programming Language :: Python :: 3.12
jpayne@69 46 Classifier: Programming Language :: Python :: 3 :: Only
jpayne@69 47 Classifier: Programming Language :: Python :: Implementation
jpayne@69 48 Classifier: Programming Language :: Python :: Implementation :: IronPython
jpayne@69 49 Classifier: Programming Language :: Python :: Implementation :: PyPy
jpayne@69 50 Classifier: Programming Language :: Unix Shell
jpayne@69 51 Classifier: Topic :: Desktop Environment
jpayne@69 52 Classifier: Topic :: Education :: Computer Aided Instruction (CAI)
jpayne@69 53 Classifier: Topic :: Education :: Testing
jpayne@69 54 Classifier: Topic :: Office/Business
jpayne@69 55 Classifier: Topic :: Other/Nonlisted Topic
jpayne@69 56 Classifier: Topic :: Software Development :: Build Tools
jpayne@69 57 Classifier: Topic :: Software Development :: Libraries
jpayne@69 58 Classifier: Topic :: Software Development :: Libraries :: Python Modules
jpayne@69 59 Classifier: Topic :: Software Development :: Pre-processors
jpayne@69 60 Classifier: Topic :: Software Development :: User Interfaces
jpayne@69 61 Classifier: Topic :: System :: Installation/Setup
jpayne@69 62 Classifier: Topic :: System :: Logging
jpayne@69 63 Classifier: Topic :: System :: Monitoring
jpayne@69 64 Classifier: Topic :: System :: Shells
jpayne@69 65 Classifier: Topic :: Terminals
jpayne@69 66 Classifier: Topic :: Utilities
jpayne@69 67 Requires-Python: >=3.7
jpayne@69 68 Description-Content-Type: text/x-rst
jpayne@69 69 License-File: LICENCE
jpayne@69 70 Requires-Dist: colorama; platform_system == "Windows"
jpayne@69 71 Provides-Extra: dev
jpayne@69 72 Requires-Dist: pytest>=6; extra == "dev"
jpayne@69 73 Requires-Dist: pytest-cov; extra == "dev"
jpayne@69 74 Requires-Dist: pytest-timeout; extra == "dev"
jpayne@69 75 Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
jpayne@69 76 Requires-Dist: nbval; extra == "dev"
jpayne@69 77 Provides-Extra: discord
jpayne@69 78 Requires-Dist: requests; extra == "discord"
jpayne@69 79 Provides-Extra: slack
jpayne@69 80 Requires-Dist: slack-sdk; extra == "slack"
jpayne@69 81 Provides-Extra: telegram
jpayne@69 82 Requires-Dist: requests; extra == "telegram"
jpayne@69 83 Provides-Extra: notebook
jpayne@69 84 Requires-Dist: ipywidgets>=6; extra == "notebook"
jpayne@69 85
jpayne@69 86 |Logo|
jpayne@69 87
jpayne@69 88 tqdm
jpayne@69 89 ====
jpayne@69 90
jpayne@69 91 |Py-Versions| |Versions| |Conda-Forge-Status| |Docker| |Snapcraft|
jpayne@69 92
jpayne@69 93 |Build-Status| |Coverage-Status| |Branch-Coverage-Status| |Codacy-Grade| |Libraries-Rank| |PyPI-Downloads|
jpayne@69 94
jpayne@69 95 |LICENCE| |OpenHub-Status| |binder-demo| |awesome-python|
jpayne@69 96
jpayne@69 97 ``tqdm`` derives from the Arabic word *taqaddum* (تقدّم) which can mean "progress,"
jpayne@69 98 and is an abbreviation for "I love you so much" in Spanish (*te quiero demasiado*).
jpayne@69 99
jpayne@69 100 Instantly make your loops show a smart progress meter - just wrap any
jpayne@69 101 iterable with ``tqdm(iterable)``, and you're done!
jpayne@69 102
jpayne@69 103 .. code:: python
jpayne@69 104
jpayne@69 105 from tqdm import tqdm
jpayne@69 106 for i in tqdm(range(10000)):
jpayne@69 107 ...
jpayne@69 108
jpayne@69 109 ``76%|████████████████████████        | 7568/10000 [00:33<00:10, 229.00it/s]``
jpayne@69 110
jpayne@69 111 ``trange(N)`` can be also used as a convenient shortcut for
jpayne@69 112 ``tqdm(range(N))``.
jpayne@69 113
jpayne@69 114 |Screenshot|
jpayne@69 115 |Video| |Slides| |Merch|
jpayne@69 116
jpayne@69 117 It can also be executed as a module with pipes:
jpayne@69 118
jpayne@69 119 .. code:: sh
jpayne@69 120
jpayne@69 121 $ seq 9999999 | tqdm --bytes | wc -l
jpayne@69 122 75.2MB [00:00, 217MB/s]
jpayne@69 123 9999999
jpayne@69 124
jpayne@69 125 $ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \
jpayne@69 126 > backup.tgz
jpayne@69 127 32%|██████████▍ | 8.89G/27.9G [00:42<01:31, 223MB/s]
jpayne@69 128
jpayne@69 129 Overhead is low -- about 60ns per iteration (80ns with ``tqdm.gui``), and is
jpayne@69 130 unit tested against performance regression.
jpayne@69 131 By comparison, the well-established
jpayne@69 132 `ProgressBar <https://github.com/niltonvolpato/python-progressbar>`__ has
jpayne@69 133 an 800ns/iter overhead.
jpayne@69 134
jpayne@69 135 In addition to its low overhead, ``tqdm`` uses smart algorithms to predict
jpayne@69 136 the remaining time and to skip unnecessary iteration displays, which allows
jpayne@69 137 for a negligible overhead in most cases.
jpayne@69 138
jpayne@69 139 ``tqdm`` works on any platform
jpayne@69 140 (Linux, Windows, Mac, FreeBSD, NetBSD, Solaris/SunOS),
jpayne@69 141 in any console or in a GUI, and is also friendly with IPython/Jupyter notebooks.
jpayne@69 142
jpayne@69 143 ``tqdm`` does not require any dependencies (not even ``curses``!), just
jpayne@69 144 Python and an environment supporting ``carriage return \r`` and
jpayne@69 145 ``line feed \n`` control characters.
jpayne@69 146
jpayne@69 147 ------------------------------------------
jpayne@69 148
jpayne@69 149 .. contents:: Table of contents
jpayne@69 150 :backlinks: top
jpayne@69 151 :local:
jpayne@69 152
jpayne@69 153
jpayne@69 154 Installation
jpayne@69 155 ------------
jpayne@69 156
jpayne@69 157 Latest PyPI stable release
jpayne@69 158 ~~~~~~~~~~~~~~~~~~~~~~~~~~
jpayne@69 159
jpayne@69 160 |Versions| |PyPI-Downloads| |Libraries-Dependents|
jpayne@69 161
jpayne@69 162 .. code:: sh
jpayne@69 163
jpayne@69 164 pip install tqdm
jpayne@69 165
jpayne@69 166 Latest development release on GitHub
jpayne@69 167 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
jpayne@69 168
jpayne@69 169 |GitHub-Status| |GitHub-Stars| |GitHub-Commits| |GitHub-Forks| |GitHub-Updated|
jpayne@69 170
jpayne@69 171 Pull and install pre-release ``devel`` branch:
jpayne@69 172
jpayne@69 173 .. code:: sh
jpayne@69 174
jpayne@69 175 pip install "git+https://github.com/tqdm/tqdm.git@devel#egg=tqdm"
jpayne@69 176
jpayne@69 177 Latest Conda release
jpayne@69 178 ~~~~~~~~~~~~~~~~~~~~
jpayne@69 179
jpayne@69 180 |Conda-Forge-Status|
jpayne@69 181
jpayne@69 182 .. code:: sh
jpayne@69 183
jpayne@69 184 conda install -c conda-forge tqdm
jpayne@69 185
jpayne@69 186 Latest Snapcraft release
jpayne@69 187 ~~~~~~~~~~~~~~~~~~~~~~~~
jpayne@69 188
jpayne@69 189 |Snapcraft|
jpayne@69 190
jpayne@69 191 There are 3 channels to choose from:
jpayne@69 192
jpayne@69 193 .. code:: sh
jpayne@69 194
jpayne@69 195 snap install tqdm # implies --stable, i.e. latest tagged release
jpayne@69 196 snap install tqdm --candidate # master branch
jpayne@69 197 snap install tqdm --edge # devel branch
jpayne@69 198
jpayne@69 199 Note that ``snap`` binaries are purely for CLI use (not ``import``-able), and
jpayne@69 200 automatically set up ``bash`` tab-completion.
jpayne@69 201
jpayne@69 202 Latest Docker release
jpayne@69 203 ~~~~~~~~~~~~~~~~~~~~~
jpayne@69 204
jpayne@69 205 |Docker|
jpayne@69 206
jpayne@69 207 .. code:: sh
jpayne@69 208
jpayne@69 209 docker pull tqdm/tqdm
jpayne@69 210 docker run -i --rm tqdm/tqdm --help
jpayne@69 211
jpayne@69 212 Other
jpayne@69 213 ~~~~~
jpayne@69 214
jpayne@69 215 There are other (unofficial) places where ``tqdm`` may be downloaded, particularly for CLI use:
jpayne@69 216
jpayne@69 217 |Repology|
jpayne@69 218
jpayne@69 219 .. |Repology| image:: https://repology.org/badge/tiny-repos/python:tqdm.svg
jpayne@69 220 :target: https://repology.org/project/python:tqdm/versions
jpayne@69 221
jpayne@69 222 Changelog
jpayne@69 223 ---------
jpayne@69 224
jpayne@69 225 The list of all changes is available either on GitHub's Releases:
jpayne@69 226 |GitHub-Status|, on the
jpayne@69 227 `wiki <https://github.com/tqdm/tqdm/wiki/Releases>`__, or on the
jpayne@69 228 `website <https://tqdm.github.io/releases>`__.
jpayne@69 229
jpayne@69 230
jpayne@69 231 Usage
jpayne@69 232 -----
jpayne@69 233
jpayne@69 234 ``tqdm`` is very versatile and can be used in a number of ways.
jpayne@69 235 The three main ones are given below.
jpayne@69 236
jpayne@69 237 Iterable-based
jpayne@69 238 ~~~~~~~~~~~~~~
jpayne@69 239
jpayne@69 240 Wrap ``tqdm()`` around any iterable:
jpayne@69 241
jpayne@69 242 .. code:: python
jpayne@69 243
jpayne@69 244 from tqdm import tqdm
jpayne@69 245 from time import sleep
jpayne@69 246
jpayne@69 247 text = ""
jpayne@69 248 for char in tqdm(["a", "b", "c", "d"]):
jpayne@69 249 sleep(0.25)
jpayne@69 250 text = text + char
jpayne@69 251
jpayne@69 252 ``trange(i)`` is a special optimised instance of ``tqdm(range(i))``:
jpayne@69 253
jpayne@69 254 .. code:: python
jpayne@69 255
jpayne@69 256 from tqdm import trange
jpayne@69 257
jpayne@69 258 for i in trange(100):
jpayne@69 259 sleep(0.01)
jpayne@69 260
jpayne@69 261 Instantiation outside of the loop allows for manual control over ``tqdm()``:
jpayne@69 262
jpayne@69 263 .. code:: python
jpayne@69 264
jpayne@69 265 pbar = tqdm(["a", "b", "c", "d"])
jpayne@69 266 for char in pbar:
jpayne@69 267 sleep(0.25)
jpayne@69 268 pbar.set_description("Processing %s" % char)
jpayne@69 269
jpayne@69 270 Manual
jpayne@69 271 ~~~~~~
jpayne@69 272
jpayne@69 273 Manual control of ``tqdm()`` updates using a ``with`` statement:
jpayne@69 274
jpayne@69 275 .. code:: python
jpayne@69 276
jpayne@69 277 with tqdm(total=100) as pbar:
jpayne@69 278 for i in range(10):
jpayne@69 279 sleep(0.1)
jpayne@69 280 pbar.update(10)
jpayne@69 281
jpayne@69 282 If the optional variable ``total`` (or an iterable with ``len()``) is
jpayne@69 283 provided, predictive stats are displayed.
jpayne@69 284
jpayne@69 285 ``with`` is also optional (you can just assign ``tqdm()`` to a variable,
jpayne@69 286 but in this case don't forget to ``del`` or ``close()`` at the end:
jpayne@69 287
jpayne@69 288 .. code:: python
jpayne@69 289
jpayne@69 290 pbar = tqdm(total=100)
jpayne@69 291 for i in range(10):
jpayne@69 292 sleep(0.1)
jpayne@69 293 pbar.update(10)
jpayne@69 294 pbar.close()
jpayne@69 295
jpayne@69 296 Module
jpayne@69 297 ~~~~~~
jpayne@69 298
jpayne@69 299 Perhaps the most wonderful use of ``tqdm`` is in a script or on the command
jpayne@69 300 line. Simply inserting ``tqdm`` (or ``python -m tqdm``) between pipes will pass
jpayne@69 301 through all ``stdin`` to ``stdout`` while printing progress to ``stderr``.
jpayne@69 302
jpayne@69 303 The example below demonstrate counting the number of lines in all Python files
jpayne@69 304 in the current directory, with timing information included.
jpayne@69 305
jpayne@69 306 .. code:: sh
jpayne@69 307
jpayne@69 308 $ time find . -name '*.py' -type f -exec cat \{} \; | wc -l
jpayne@69 309 857365
jpayne@69 310
jpayne@69 311 real 0m3.458s
jpayne@69 312 user 0m0.274s
jpayne@69 313 sys 0m3.325s
jpayne@69 314
jpayne@69 315 $ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l
jpayne@69 316 857366it [00:03, 246471.31it/s]
jpayne@69 317 857365
jpayne@69 318
jpayne@69 319 real 0m3.585s
jpayne@69 320 user 0m0.862s
jpayne@69 321 sys 0m3.358s
jpayne@69 322
jpayne@69 323 Note that the usual arguments for ``tqdm`` can also be specified.
jpayne@69 324
jpayne@69 325 .. code:: sh
jpayne@69 326
jpayne@69 327 $ find . -name '*.py' -type f -exec cat \{} \; |
jpayne@69 328 tqdm --unit loc --unit_scale --total 857366 >> /dev/null
jpayne@69 329 100%|█████████████████████████████████| 857K/857K [00:04<00:00, 246Kloc/s]
jpayne@69 330
jpayne@69 331 Backing up a large directory?
jpayne@69 332
jpayne@69 333 .. code:: sh
jpayne@69 334
jpayne@69 335 $ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \
jpayne@69 336 > backup.tgz
jpayne@69 337 44%|██████████████▊ | 153M/352M [00:14<00:18, 11.0MB/s]
jpayne@69 338
jpayne@69 339 This can be beautified further:
jpayne@69 340
jpayne@69 341 .. code:: sh
jpayne@69 342
jpayne@69 343 $ BYTES=$(du -sb docs/ | cut -f1)
jpayne@69 344 $ tar -cf - docs/ \
jpayne@69 345 | tqdm --bytes --total "$BYTES" --desc Processing | gzip \
jpayne@69 346 | tqdm --bytes --total "$BYTES" --desc Compressed --position 1 \
jpayne@69 347 > ~/backup.tgz
jpayne@69 348 Processing: 100%|██████████████████████| 352M/352M [00:14<00:00, 30.2MB/s]
jpayne@69 349 Compressed: 42%|█████████▎ | 148M/352M [00:14<00:19, 10.9MB/s]
jpayne@69 350
jpayne@69 351 Or done on a file level using 7-zip:
jpayne@69 352
jpayne@69 353 .. code:: sh
jpayne@69 354
jpayne@69 355 $ 7z a -bd -r backup.7z docs/ | grep Compressing \
jpayne@69 356 | tqdm --total $(find docs/ -type f | wc -l) --unit files \
jpayne@69 357 | grep -v Compressing
jpayne@69 358 100%|██████████████████████████▉| 15327/15327 [01:00<00:00, 712.96files/s]
jpayne@69 359
jpayne@69 360 Pre-existing CLI programs already outputting basic progress information will
jpayne@69 361 benefit from ``tqdm``'s ``--update`` and ``--update_to`` flags:
jpayne@69 362
jpayne@69 363 .. code:: sh
jpayne@69 364
jpayne@69 365 $ seq 3 0.1 5 | tqdm --total 5 --update_to --null
jpayne@69 366 100%|████████████████████████████████████| 5.0/5 [00:00<00:00, 9673.21it/s]
jpayne@69 367 $ seq 10 | tqdm --update --null # 1 + 2 + ... + 10 = 55 iterations
jpayne@69 368 55it [00:00, 90006.52it/s]
jpayne@69 369
jpayne@69 370 FAQ and Known Issues
jpayne@69 371 --------------------
jpayne@69 372
jpayne@69 373 |GitHub-Issues|
jpayne@69 374
jpayne@69 375 The most common issues relate to excessive output on multiple lines, instead
jpayne@69 376 of a neat one-line progress bar.
jpayne@69 377
jpayne@69 378 - Consoles in general: require support for carriage return (``CR``, ``\r``).
jpayne@69 379
jpayne@69 380 * Some cloud logging consoles which don't support ``\r`` properly
jpayne@69 381 (`cloudwatch <https://github.com/tqdm/tqdm/issues/966>`__,
jpayne@69 382 `K8s <https://github.com/tqdm/tqdm/issues/1319>`__) may benefit from
jpayne@69 383 ``export TQDM_POSITION=-1``.
jpayne@69 384
jpayne@69 385 - Nested progress bars:
jpayne@69 386
jpayne@69 387 * Consoles in general: require support for moving cursors up to the
jpayne@69 388 previous line. For example,
jpayne@69 389 `IDLE <https://github.com/tqdm/tqdm/issues/191#issuecomment-230168030>`__,
jpayne@69 390 `ConEmu <https://github.com/tqdm/tqdm/issues/254>`__ and
jpayne@69 391 `PyCharm <https://github.com/tqdm/tqdm/issues/203>`__ (also
jpayne@69 392 `here <https://github.com/tqdm/tqdm/issues/208>`__,
jpayne@69 393 `here <https://github.com/tqdm/tqdm/issues/307>`__, and
jpayne@69 394 `here <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__)
jpayne@69 395 lack full support.
jpayne@69 396 * Windows: additionally may require the Python module ``colorama``
jpayne@69 397 to ensure nested bars stay within their respective lines.
jpayne@69 398
jpayne@69 399 - Unicode:
jpayne@69 400
jpayne@69 401 * Environments which report that they support unicode will have solid smooth
jpayne@69 402 progressbars. The fallback is an ``ascii``-only bar.
jpayne@69 403 * Windows consoles often only partially support unicode and thus
jpayne@69 404 `often require explicit ascii=True <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__
jpayne@69 405 (also `here <https://github.com/tqdm/tqdm/issues/499>`__). This is due to
jpayne@69 406 either normal-width unicode characters being incorrectly displayed as
jpayne@69 407 "wide", or some unicode characters not rendering.
jpayne@69 408
jpayne@69 409 - Wrapping generators:
jpayne@69 410
jpayne@69 411 * Generator wrapper functions tend to hide the length of iterables.
jpayne@69 412 ``tqdm`` does not.
jpayne@69 413 * Replace ``tqdm(enumerate(...))`` with ``enumerate(tqdm(...))`` or
jpayne@69 414 ``tqdm(enumerate(x), total=len(x), ...)``.
jpayne@69 415 The same applies to ``numpy.ndenumerate``.
jpayne@69 416 * Replace ``tqdm(zip(a, b))`` with ``zip(tqdm(a), b)`` or even
jpayne@69 417 ``zip(tqdm(a), tqdm(b))``.
jpayne@69 418 * The same applies to ``itertools``.
jpayne@69 419 * Some useful convenience functions can be found under ``tqdm.contrib``.
jpayne@69 420
jpayne@69 421 - `No intermediate output in docker-compose <https://github.com/tqdm/tqdm/issues/771>`__:
jpayne@69 422 use ``docker-compose run`` instead of ``docker-compose up`` and ``tty: true``.
jpayne@69 423
jpayne@69 424 - Overriding defaults via environment variables:
jpayne@69 425 e.g. in CI/cloud jobs, ``export TQDM_MININTERVAL=5`` to avoid log spam.
jpayne@69 426 This override logic is handled by the ``tqdm.utils.envwrap`` decorator
jpayne@69 427 (useful independent of ``tqdm``).
jpayne@69 428
jpayne@69 429 If you come across any other difficulties, browse and file |GitHub-Issues|.
jpayne@69 430
jpayne@69 431 Documentation
jpayne@69 432 -------------
jpayne@69 433
jpayne@69 434 |Py-Versions| |README-Hits| (Since 19 May 2016)
jpayne@69 435
jpayne@69 436 .. code:: python
jpayne@69 437
jpayne@69 438 class tqdm():
jpayne@69 439 """
jpayne@69 440 Decorate an iterable object, returning an iterator which acts exactly
jpayne@69 441 like the original iterable, but prints a dynamically updating
jpayne@69 442 progressbar every time a value is requested.
jpayne@69 443 """
jpayne@69 444
jpayne@69 445 @envwrap("TQDM_") # override defaults via env vars
jpayne@69 446 def __init__(self, iterable=None, desc=None, total=None, leave=True,
jpayne@69 447 file=None, ncols=None, mininterval=0.1,
jpayne@69 448 maxinterval=10.0, miniters=None, ascii=None, disable=False,
jpayne@69 449 unit='it', unit_scale=False, dynamic_ncols=False,
jpayne@69 450 smoothing=0.3, bar_format=None, initial=0, position=None,
jpayne@69 451 postfix=None, unit_divisor=1000, write_bytes=False,
jpayne@69 452 lock_args=None, nrows=None, colour=None, delay=0):
jpayne@69 453
jpayne@69 454 Parameters
jpayne@69 455 ~~~~~~~~~~
jpayne@69 456
jpayne@69 457 * iterable : iterable, optional
jpayne@69 458 Iterable to decorate with a progressbar.
jpayne@69 459 Leave blank to manually manage the updates.
jpayne@69 460 * desc : str, optional
jpayne@69 461 Prefix for the progressbar.
jpayne@69 462 * total : int or float, optional
jpayne@69 463 The number of expected iterations. If unspecified,
jpayne@69 464 len(iterable) is used if possible. If float("inf") or as a last
jpayne@69 465 resort, only basic progress statistics are displayed
jpayne@69 466 (no ETA, no progressbar).
jpayne@69 467 If ``gui`` is True and this parameter needs subsequent updating,
jpayne@69 468 specify an initial arbitrary large positive number,
jpayne@69 469 e.g. 9e9.
jpayne@69 470 * leave : bool, optional
jpayne@69 471 If [default: True], keeps all traces of the progressbar
jpayne@69 472 upon termination of iteration.
jpayne@69 473 If ``None``, will leave only if ``position`` is ``0``.
jpayne@69 474 * file : ``io.TextIOWrapper`` or ``io.StringIO``, optional
jpayne@69 475 Specifies where to output the progress messages
jpayne@69 476 (default: sys.stderr). Uses ``file.write(str)`` and ``file.flush()``
jpayne@69 477 methods. For encoding, see ``write_bytes``.
jpayne@69 478 * ncols : int, optional
jpayne@69 479 The width of the entire output message. If specified,
jpayne@69 480 dynamically resizes the progressbar to stay within this bound.
jpayne@69 481 If unspecified, attempts to use environment width. The
jpayne@69 482 fallback is a meter width of 10 and no limit for the counter and
jpayne@69 483 statistics. If 0, will not print any meter (only stats).
jpayne@69 484 * mininterval : float, optional
jpayne@69 485 Minimum progress display update interval [default: 0.1] seconds.
jpayne@69 486 * maxinterval : float, optional
jpayne@69 487 Maximum progress display update interval [default: 10] seconds.
jpayne@69 488 Automatically adjusts ``miniters`` to correspond to ``mininterval``
jpayne@69 489 after long display update lag. Only works if ``dynamic_miniters``
jpayne@69 490 or monitor thread is enabled.
jpayne@69 491 * miniters : int or float, optional
jpayne@69 492 Minimum progress display update interval, in iterations.
jpayne@69 493 If 0 and ``dynamic_miniters``, will automatically adjust to equal
jpayne@69 494 ``mininterval`` (more CPU efficient, good for tight loops).
jpayne@69 495 If > 0, will skip display of specified number of iterations.
jpayne@69 496 Tweak this and ``mininterval`` to get very efficient loops.
jpayne@69 497 If your progress is erratic with both fast and slow iterations
jpayne@69 498 (network, skipping items, etc) you should set miniters=1.
jpayne@69 499 * ascii : bool or str, optional
jpayne@69 500 If unspecified or False, use unicode (smooth blocks) to fill
jpayne@69 501 the meter. The fallback is to use ASCII characters " 123456789#".
jpayne@69 502 * disable : bool, optional
jpayne@69 503 Whether to disable the entire progressbar wrapper
jpayne@69 504 [default: False]. If set to None, disable on non-TTY.
jpayne@69 505 * unit : str, optional
jpayne@69 506 String that will be used to define the unit of each iteration
jpayne@69 507 [default: it].
jpayne@69 508 * unit_scale : bool or int or float, optional
jpayne@69 509 If 1 or True, the number of iterations will be reduced/scaled
jpayne@69 510 automatically and a metric prefix following the
jpayne@69 511 International System of Units standard will be added
jpayne@69 512 (kilo, mega, etc.) [default: False]. If any other non-zero
jpayne@69 513 number, will scale ``total`` and ``n``.
jpayne@69 514 * dynamic_ncols : bool, optional
jpayne@69 515 If set, constantly alters ``ncols`` and ``nrows`` to the
jpayne@69 516 environment (allowing for window resizes) [default: False].
jpayne@69 517 * smoothing : float, optional
jpayne@69 518 Exponential moving average smoothing factor for speed estimates
jpayne@69 519 (ignored in GUI mode). Ranges from 0 (average speed) to 1
jpayne@69 520 (current/instantaneous speed) [default: 0.3].
jpayne@69 521 * bar_format : str, optional
jpayne@69 522 Specify a custom bar string formatting. May impact performance.
jpayne@69 523 [default: '{l_bar}{bar}{r_bar}'], where
jpayne@69 524 l_bar='{desc}: {percentage:3.0f}%|' and
jpayne@69 525 r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
jpayne@69 526 '{rate_fmt}{postfix}]'
jpayne@69 527 Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
jpayne@69 528 percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
jpayne@69 529 rate, rate_fmt, rate_noinv, rate_noinv_fmt,
jpayne@69 530 rate_inv, rate_inv_fmt, postfix, unit_divisor,
jpayne@69 531 remaining, remaining_s, eta.
jpayne@69 532 Note that a trailing ": " is automatically removed after {desc}
jpayne@69 533 if the latter is empty.
jpayne@69 534 * initial : int or float, optional
jpayne@69 535 The initial counter value. Useful when restarting a progress
jpayne@69 536 bar [default: 0]. If using float, consider specifying ``{n:.3f}``
jpayne@69 537 or similar in ``bar_format``, or specifying ``unit_scale``.
jpayne@69 538 * position : int, optional
jpayne@69 539 Specify the line offset to print this bar (starting from 0)
jpayne@69 540 Automatic if unspecified.
jpayne@69 541 Useful to manage multiple bars at once (eg, from threads).
jpayne@69 542 * postfix : dict or ``*``, optional
jpayne@69 543 Specify additional stats to display at the end of the bar.
jpayne@69 544 Calls ``set_postfix(**postfix)`` if possible (dict).
jpayne@69 545 * unit_divisor : float, optional
jpayne@69 546 [default: 1000], ignored unless ``unit_scale`` is True.
jpayne@69 547 * write_bytes : bool, optional
jpayne@69 548 Whether to write bytes. If (default: False) will write unicode.
jpayne@69 549 * lock_args : tuple, optional
jpayne@69 550 Passed to ``refresh`` for intermediate output
jpayne@69 551 (initialisation, iterating, and updating).
jpayne@69 552 * nrows : int, optional
jpayne@69 553 The screen height. If specified, hides nested bars outside this
jpayne@69 554 bound. If unspecified, attempts to use environment height.
jpayne@69 555 The fallback is 20.
jpayne@69 556 * colour : str, optional
jpayne@69 557 Bar colour (e.g. 'green', '#00ff00').
jpayne@69 558 * delay : float, optional
jpayne@69 559 Don't display until [default: 0] seconds have elapsed.
jpayne@69 560
jpayne@69 561 Extra CLI Options
jpayne@69 562 ~~~~~~~~~~~~~~~~~
jpayne@69 563
jpayne@69 564 * delim : chr, optional
jpayne@69 565 Delimiting character [default: '\n']. Use '\0' for null.
jpayne@69 566 N.B.: on Windows systems, Python converts '\n' to '\r\n'.
jpayne@69 567 * buf_size : int, optional
jpayne@69 568 String buffer size in bytes [default: 256]
jpayne@69 569 used when ``delim`` is specified.
jpayne@69 570 * bytes : bool, optional
jpayne@69 571 If true, will count bytes, ignore ``delim``, and default
jpayne@69 572 ``unit_scale`` to True, ``unit_divisor`` to 1024, and ``unit`` to 'B'.
jpayne@69 573 * tee : bool, optional
jpayne@69 574 If true, passes ``stdin`` to both ``stderr`` and ``stdout``.
jpayne@69 575 * update : bool, optional
jpayne@69 576 If true, will treat input as newly elapsed iterations,
jpayne@69 577 i.e. numbers to pass to ``update()``. Note that this is slow
jpayne@69 578 (~2e5 it/s) since every input must be decoded as a number.
jpayne@69 579 * update_to : bool, optional
jpayne@69 580 If true, will treat input as total elapsed iterations,
jpayne@69 581 i.e. numbers to assign to ``self.n``. Note that this is slow
jpayne@69 582 (~2e5 it/s) since every input must be decoded as a number.
jpayne@69 583 * null : bool, optional
jpayne@69 584 If true, will discard input (no stdout).
jpayne@69 585 * manpath : str, optional
jpayne@69 586 Directory in which to install tqdm man pages.
jpayne@69 587 * comppath : str, optional
jpayne@69 588 Directory in which to place tqdm completion.
jpayne@69 589 * log : str, optional
jpayne@69 590 CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
jpayne@69 591
jpayne@69 592 Returns
jpayne@69 593 ~~~~~~~
jpayne@69 594
jpayne@69 595 * out : decorated iterator.
jpayne@69 596
jpayne@69 597 .. code:: python
jpayne@69 598
jpayne@69 599 class tqdm():
jpayne@69 600 def update(self, n=1):
jpayne@69 601 """
jpayne@69 602 Manually update the progress bar, useful for streams
jpayne@69 603 such as reading files.
jpayne@69 604 E.g.:
jpayne@69 605 >>> t = tqdm(total=filesize) # Initialise
jpayne@69 606 >>> for current_buffer in stream:
jpayne@69 607 ... ...
jpayne@69 608 ... t.update(len(current_buffer))
jpayne@69 609 >>> t.close()
jpayne@69 610 The last line is highly recommended, but possibly not necessary if
jpayne@69 611 ``t.update()`` will be called in such a way that ``filesize`` will be
jpayne@69 612 exactly reached and printed.
jpayne@69 613
jpayne@69 614 Parameters
jpayne@69 615 ----------
jpayne@69 616 n : int or float, optional
jpayne@69 617 Increment to add to the internal counter of iterations
jpayne@69 618 [default: 1]. If using float, consider specifying ``{n:.3f}``
jpayne@69 619 or similar in ``bar_format``, or specifying ``unit_scale``.
jpayne@69 620
jpayne@69 621 Returns
jpayne@69 622 -------
jpayne@69 623 out : bool or None
jpayne@69 624 True if a ``display()`` was triggered.
jpayne@69 625 """
jpayne@69 626
jpayne@69 627 def close(self):
jpayne@69 628 """Cleanup and (if leave=False) close the progressbar."""
jpayne@69 629
jpayne@69 630 def clear(self, nomove=False):
jpayne@69 631 """Clear current bar display."""
jpayne@69 632
jpayne@69 633 def refresh(self):
jpayne@69 634 """
jpayne@69 635 Force refresh the display of this bar.
jpayne@69 636
jpayne@69 637 Parameters
jpayne@69 638 ----------
jpayne@69 639 nolock : bool, optional
jpayne@69 640 If ``True``, does not lock.
jpayne@69 641 If [default: ``False``]: calls ``acquire()`` on internal lock.
jpayne@69 642 lock_args : tuple, optional
jpayne@69 643 Passed to internal lock's ``acquire()``.
jpayne@69 644 If specified, will only ``display()`` if ``acquire()`` returns ``True``.
jpayne@69 645 """
jpayne@69 646
jpayne@69 647 def unpause(self):
jpayne@69 648 """Restart tqdm timer from last print time."""
jpayne@69 649
jpayne@69 650 def reset(self, total=None):
jpayne@69 651 """
jpayne@69 652 Resets to 0 iterations for repeated use.
jpayne@69 653
jpayne@69 654 Consider combining with ``leave=True``.
jpayne@69 655
jpayne@69 656 Parameters
jpayne@69 657 ----------
jpayne@69 658 total : int or float, optional. Total to use for the new bar.
jpayne@69 659 """
jpayne@69 660
jpayne@69 661 def set_description(self, desc=None, refresh=True):
jpayne@69 662 """
jpayne@69 663 Set/modify description of the progress bar.
jpayne@69 664
jpayne@69 665 Parameters
jpayne@69 666 ----------
jpayne@69 667 desc : str, optional
jpayne@69 668 refresh : bool, optional
jpayne@69 669 Forces refresh [default: True].
jpayne@69 670 """
jpayne@69 671
jpayne@69 672 def set_postfix(self, ordered_dict=None, refresh=True, **tqdm_kwargs):
jpayne@69 673 """
jpayne@69 674 Set/modify postfix (additional stats)
jpayne@69 675 with automatic formatting based on datatype.
jpayne@69 676
jpayne@69 677 Parameters
jpayne@69 678 ----------
jpayne@69 679 ordered_dict : dict or OrderedDict, optional
jpayne@69 680 refresh : bool, optional
jpayne@69 681 Forces refresh [default: True].
jpayne@69 682 kwargs : dict, optional
jpayne@69 683 """
jpayne@69 684
jpayne@69 685 @classmethod
jpayne@69 686 def write(cls, s, file=sys.stdout, end="\n"):
jpayne@69 687 """Print a message via tqdm (without overlap with bars)."""
jpayne@69 688
jpayne@69 689 @property
jpayne@69 690 def format_dict(self):
jpayne@69 691 """Public API for read-only member access."""
jpayne@69 692
jpayne@69 693 def display(self, msg=None, pos=None):
jpayne@69 694 """
jpayne@69 695 Use ``self.sp`` to display ``msg`` in the specified ``pos``.
jpayne@69 696
jpayne@69 697 Consider overloading this function when inheriting to use e.g.:
jpayne@69 698 ``self.some_frontend(**self.format_dict)`` instead of ``self.sp``.
jpayne@69 699
jpayne@69 700 Parameters
jpayne@69 701 ----------
jpayne@69 702 msg : str, optional. What to display (default: ``repr(self)``).
jpayne@69 703 pos : int, optional. Position to ``moveto``
jpayne@69 704 (default: ``abs(self.pos)``).
jpayne@69 705 """
jpayne@69 706
jpayne@69 707 @classmethod
jpayne@69 708 @contextmanager
jpayne@69 709 def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs):
jpayne@69 710 """
jpayne@69 711 stream : file-like object.
jpayne@69 712 method : str, "read" or "write". The result of ``read()`` and
jpayne@69 713 the first argument of ``write()`` should have a ``len()``.
jpayne@69 714
jpayne@69 715 >>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
jpayne@69 716 ... while True:
jpayne@69 717 ... chunk = fobj.read(chunk_size)
jpayne@69 718 ... if not chunk:
jpayne@69 719 ... break
jpayne@69 720 """
jpayne@69 721
jpayne@69 722 @classmethod
jpayne@69 723 def pandas(cls, *targs, **tqdm_kwargs):
jpayne@69 724 """Registers the current `tqdm` class with `pandas`."""
jpayne@69 725
jpayne@69 726 def trange(*args, **tqdm_kwargs):
jpayne@69 727 """Shortcut for `tqdm(range(*args), **tqdm_kwargs)`."""
jpayne@69 728
jpayne@69 729 Convenience Functions
jpayne@69 730 ~~~~~~~~~~~~~~~~~~~~~
jpayne@69 731
jpayne@69 732 .. code:: python
jpayne@69 733
jpayne@69 734 def tqdm.contrib.tenumerate(iterable, start=0, total=None,
jpayne@69 735 tqdm_class=tqdm.auto.tqdm, **tqdm_kwargs):
jpayne@69 736 """Equivalent of `numpy.ndenumerate` or builtin `enumerate`."""
jpayne@69 737
jpayne@69 738 def tqdm.contrib.tzip(iter1, *iter2plus, **tqdm_kwargs):
jpayne@69 739 """Equivalent of builtin `zip`."""
jpayne@69 740
jpayne@69 741 def tqdm.contrib.tmap(function, *sequences, **tqdm_kwargs):
jpayne@69 742 """Equivalent of builtin `map`."""
jpayne@69 743
jpayne@69 744 Submodules
jpayne@69 745 ~~~~~~~~~~
jpayne@69 746
jpayne@69 747 .. code:: python
jpayne@69 748
jpayne@69 749 class tqdm.notebook.tqdm(tqdm.tqdm):
jpayne@69 750 """IPython/Jupyter Notebook widget."""
jpayne@69 751
jpayne@69 752 class tqdm.auto.tqdm(tqdm.tqdm):
jpayne@69 753 """Automatically chooses beween `tqdm.notebook` and `tqdm.tqdm`."""
jpayne@69 754
jpayne@69 755 class tqdm.asyncio.tqdm(tqdm.tqdm):
jpayne@69 756 """Asynchronous version."""
jpayne@69 757 @classmethod
jpayne@69 758 def as_completed(cls, fs, *, loop=None, timeout=None, total=None,
jpayne@69 759 **tqdm_kwargs):
jpayne@69 760 """Wrapper for `asyncio.as_completed`."""
jpayne@69 761
jpayne@69 762 class tqdm.gui.tqdm(tqdm.tqdm):
jpayne@69 763 """Matplotlib GUI version."""
jpayne@69 764
jpayne@69 765 class tqdm.tk.tqdm(tqdm.tqdm):
jpayne@69 766 """Tkinter GUI version."""
jpayne@69 767
jpayne@69 768 class tqdm.rich.tqdm(tqdm.tqdm):
jpayne@69 769 """`rich.progress` version."""
jpayne@69 770
jpayne@69 771 class tqdm.keras.TqdmCallback(keras.callbacks.Callback):
jpayne@69 772 """Keras callback for epoch and batch progress."""
jpayne@69 773
jpayne@69 774 class tqdm.dask.TqdmCallback(dask.callbacks.Callback):
jpayne@69 775 """Dask callback for task progress."""
jpayne@69 776
jpayne@69 777
jpayne@69 778 ``contrib``
jpayne@69 779 +++++++++++
jpayne@69 780
jpayne@69 781 The ``tqdm.contrib`` package also contains experimental modules:
jpayne@69 782
jpayne@69 783 - ``tqdm.contrib.itertools``: Thin wrappers around ``itertools``
jpayne@69 784 - ``tqdm.contrib.concurrent``: Thin wrappers around ``concurrent.futures``
jpayne@69 785 - ``tqdm.contrib.slack``: Posts to `Slack <https://slack.com>`__ bots
jpayne@69 786 - ``tqdm.contrib.discord``: Posts to `Discord <https://discord.com>`__ bots
jpayne@69 787 - ``tqdm.contrib.telegram``: Posts to `Telegram <https://telegram.org>`__ bots
jpayne@69 788 - ``tqdm.contrib.bells``: Automagically enables all optional features
jpayne@69 789
jpayne@69 790 * ``auto``, ``pandas``, ``slack``, ``discord``, ``telegram``
jpayne@69 791
jpayne@69 792 Examples and Advanced Usage
jpayne@69 793 ---------------------------
jpayne@69 794
jpayne@69 795 - See the `examples <https://github.com/tqdm/tqdm/tree/master/examples>`__
jpayne@69 796 folder;
jpayne@69 797 - import the module and run ``help()``;
jpayne@69 798 - consult the `wiki <https://github.com/tqdm/tqdm/wiki>`__;
jpayne@69 799
jpayne@69 800 * this has an
jpayne@69 801 `excellent article <https://github.com/tqdm/tqdm/wiki/How-to-make-a-great-Progress-Bar>`__
jpayne@69 802 on how to make a **great** progressbar;
jpayne@69 803
jpayne@69 804 - check out the `slides from PyData London <https://tqdm.github.io/PyData2019/slides.html>`__, or
jpayne@69 805 - run the |binder-demo|.
jpayne@69 806
jpayne@69 807 Description and additional stats
jpayne@69 808 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
jpayne@69 809
jpayne@69 810 Custom information can be displayed and updated dynamically on ``tqdm`` bars
jpayne@69 811 with the ``desc`` and ``postfix`` arguments:
jpayne@69 812
jpayne@69 813 .. code:: python
jpayne@69 814
jpayne@69 815 from tqdm import tqdm, trange
jpayne@69 816 from random import random, randint
jpayne@69 817 from time import sleep
jpayne@69 818
jpayne@69 819 with trange(10) as t:
jpayne@69 820 for i in t:
jpayne@69 821 # Description will be displayed on the left
jpayne@69 822 t.set_description('GEN %i' % i)
jpayne@69 823 # Postfix will be displayed on the right,
jpayne@69 824 # formatted automatically based on argument's datatype
jpayne@69 825 t.set_postfix(loss=random(), gen=randint(1,999), str='h',
jpayne@69 826 lst=[1, 2])
jpayne@69 827 sleep(0.1)
jpayne@69 828
jpayne@69 829 with tqdm(total=10, bar_format="{postfix[0]} {postfix[1][value]:>8.2g}",
jpayne@69 830 postfix=["Batch", {"value": 0}]) as t:
jpayne@69 831 for i in range(10):
jpayne@69 832 sleep(0.1)
jpayne@69 833 t.postfix[1]["value"] = i / 2
jpayne@69 834 t.update()
jpayne@69 835
jpayne@69 836 Points to remember when using ``{postfix[...]}`` in the ``bar_format`` string:
jpayne@69 837
jpayne@69 838 - ``postfix`` also needs to be passed as an initial argument in a compatible
jpayne@69 839 format, and
jpayne@69 840 - ``postfix`` will be auto-converted to a string if it is a ``dict``-like
jpayne@69 841 object. To prevent this behaviour, insert an extra item into the dictionary
jpayne@69 842 where the key is not a string.
jpayne@69 843
jpayne@69 844 Additional ``bar_format`` parameters may also be defined by overriding
jpayne@69 845 ``format_dict``, and the bar itself may be modified using ``ascii``:
jpayne@69 846
jpayne@69 847 .. code:: python
jpayne@69 848
jpayne@69 849 from tqdm import tqdm
jpayne@69 850 class TqdmExtraFormat(tqdm):
jpayne@69 851 """Provides a `total_time` format parameter"""
jpayne@69 852 @property
jpayne@69 853 def format_dict(self):
jpayne@69 854 d = super().format_dict
jpayne@69 855 total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1)
jpayne@69 856 d.update(total_time=self.format_interval(total_time) + " in total")
jpayne@69 857 return d
jpayne@69 858
jpayne@69 859 for i in TqdmExtraFormat(
jpayne@69 860 range(9), ascii=" .oO0",
jpayne@69 861 bar_format="{total_time}: {percentage:.0f}%|{bar}{r_bar}"):
jpayne@69 862 if i == 4:
jpayne@69 863 break
jpayne@69 864
jpayne@69 865 .. code::
jpayne@69 866
jpayne@69 867 00:00 in total: 44%|0000. | 4/9 [00:00<00:00, 962.93it/s]
jpayne@69 868
jpayne@69 869 Note that ``{bar}`` also supports a format specifier ``[width][type]``.
jpayne@69 870
jpayne@69 871 - ``width``
jpayne@69 872
jpayne@69 873 * unspecified (default): automatic to fill ``ncols``
jpayne@69 874 * ``int >= 0``: fixed width overriding ``ncols`` logic
jpayne@69 875 * ``int < 0``: subtract from the automatic default
jpayne@69 876
jpayne@69 877 - ``type``
jpayne@69 878
jpayne@69 879 * ``a``: ascii (``ascii=True`` override)
jpayne@69 880 * ``u``: unicode (``ascii=False`` override)
jpayne@69 881 * ``b``: blank (``ascii=" "`` override)
jpayne@69 882
jpayne@69 883 This means a fixed bar with right-justified text may be created by using:
jpayne@69 884 ``bar_format="{l_bar}{bar:10}|{bar:-10b}right-justified"``
jpayne@69 885
jpayne@69 886 Nested progress bars
jpayne@69 887 ~~~~~~~~~~~~~~~~~~~~
jpayne@69 888
jpayne@69 889 ``tqdm`` supports nested progress bars. Here's an example:
jpayne@69 890
jpayne@69 891 .. code:: python
jpayne@69 892
jpayne@69 893 from tqdm.auto import trange
jpayne@69 894 from time import sleep
jpayne@69 895
jpayne@69 896 for i in trange(4, desc='1st loop'):
jpayne@69 897 for j in trange(5, desc='2nd loop'):
jpayne@69 898 for k in trange(50, desc='3rd loop', leave=False):
jpayne@69 899 sleep(0.01)
jpayne@69 900
jpayne@69 901 For manual control over positioning (e.g. for multi-processing use),
jpayne@69 902 you may specify ``position=n`` where ``n=0`` for the outermost bar,
jpayne@69 903 ``n=1`` for the next, and so on.
jpayne@69 904 However, it's best to check if ``tqdm`` can work without manual ``position``
jpayne@69 905 first.
jpayne@69 906
jpayne@69 907 .. code:: python
jpayne@69 908
jpayne@69 909 from time import sleep
jpayne@69 910 from tqdm import trange, tqdm
jpayne@69 911 from multiprocessing import Pool, RLock, freeze_support
jpayne@69 912
jpayne@69 913 L = list(range(9))
jpayne@69 914
jpayne@69 915 def progresser(n):
jpayne@69 916 interval = 0.001 / (n + 2)
jpayne@69 917 total = 5000
jpayne@69 918 text = f"#{n}, est. {interval * total:<04.2}s"
jpayne@69 919 for _ in trange(total, desc=text, position=n):
jpayne@69 920 sleep(interval)
jpayne@69 921
jpayne@69 922 if __name__ == '__main__':
jpayne@69 923 freeze_support() # for Windows support
jpayne@69 924 tqdm.set_lock(RLock()) # for managing output contention
jpayne@69 925 p = Pool(initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),))
jpayne@69 926 p.map(progresser, L)
jpayne@69 927
jpayne@69 928 Note that in Python 3, ``tqdm.write`` is thread-safe:
jpayne@69 929
jpayne@69 930 .. code:: python
jpayne@69 931
jpayne@69 932 from time import sleep
jpayne@69 933 from tqdm import tqdm, trange
jpayne@69 934 from concurrent.futures import ThreadPoolExecutor
jpayne@69 935
jpayne@69 936 L = list(range(9))
jpayne@69 937
jpayne@69 938 def progresser(n):
jpayne@69 939 interval = 0.001 / (n + 2)
jpayne@69 940 total = 5000
jpayne@69 941 text = f"#{n}, est. {interval * total:<04.2}s"
jpayne@69 942 for _ in trange(total, desc=text):
jpayne@69 943 sleep(interval)
jpayne@69 944 if n == 6:
jpayne@69 945 tqdm.write("n == 6 completed.")
jpayne@69 946 tqdm.write("`tqdm.write()` is thread-safe in py3!")
jpayne@69 947
jpayne@69 948 if __name__ == '__main__':
jpayne@69 949 with ThreadPoolExecutor() as p:
jpayne@69 950 p.map(progresser, L)
jpayne@69 951
jpayne@69 952 Hooks and callbacks
jpayne@69 953 ~~~~~~~~~~~~~~~~~~~
jpayne@69 954
jpayne@69 955 ``tqdm`` can easily support callbacks/hooks and manual updates.
jpayne@69 956 Here's an example with ``urllib``:
jpayne@69 957
jpayne@69 958 **``urllib.urlretrieve`` documentation**
jpayne@69 959
jpayne@69 960 | [...]
jpayne@69 961 | If present, the hook function will be called once
jpayne@69 962 | on establishment of the network connection and once after each block read
jpayne@69 963 | thereafter. The hook will be passed three arguments; a count of blocks
jpayne@69 964 | transferred so far, a block size in bytes, and the total size of the file.
jpayne@69 965 | [...]
jpayne@69 966
jpayne@69 967 .. code:: python
jpayne@69 968
jpayne@69 969 import urllib, os
jpayne@69 970 from tqdm import tqdm
jpayne@69 971 urllib = getattr(urllib, 'request', urllib)
jpayne@69 972
jpayne@69 973 class TqdmUpTo(tqdm):
jpayne@69 974 """Provides `update_to(n)` which uses `tqdm.update(delta_n)`."""
jpayne@69 975 def update_to(self, b=1, bsize=1, tsize=None):
jpayne@69 976 """
jpayne@69 977 b : int, optional
jpayne@69 978 Number of blocks transferred so far [default: 1].
jpayne@69 979 bsize : int, optional
jpayne@69 980 Size of each block (in tqdm units) [default: 1].
jpayne@69 981 tsize : int, optional
jpayne@69 982 Total size (in tqdm units). If [default: None] remains unchanged.
jpayne@69 983 """
jpayne@69 984 if tsize is not None:
jpayne@69 985 self.total = tsize
jpayne@69 986 return self.update(b * bsize - self.n) # also sets self.n = b * bsize
jpayne@69 987
jpayne@69 988 eg_link = "https://caspersci.uk.to/matryoshka.zip"
jpayne@69 989 with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1,
jpayne@69 990 desc=eg_link.split('/')[-1]) as t: # all optional kwargs
jpayne@69 991 urllib.urlretrieve(eg_link, filename=os.devnull,
jpayne@69 992 reporthook=t.update_to, data=None)
jpayne@69 993 t.total = t.n
jpayne@69 994
jpayne@69 995 Inspired by `twine#242 <https://github.com/pypa/twine/pull/242>`__.
jpayne@69 996 Functional alternative in
jpayne@69 997 `examples/tqdm_wget.py <https://github.com/tqdm/tqdm/blob/master/examples/tqdm_wget.py>`__.
jpayne@69 998
jpayne@69 999 It is recommend to use ``miniters=1`` whenever there is potentially
jpayne@69 1000 large differences in iteration speed (e.g. downloading a file over
jpayne@69 1001 a patchy connection).
jpayne@69 1002
jpayne@69 1003 **Wrapping read/write methods**
jpayne@69 1004
jpayne@69 1005 To measure throughput through a file-like object's ``read`` or ``write``
jpayne@69 1006 methods, use ``CallbackIOWrapper``:
jpayne@69 1007
jpayne@69 1008 .. code:: python
jpayne@69 1009
jpayne@69 1010 from tqdm.auto import tqdm
jpayne@69 1011 from tqdm.utils import CallbackIOWrapper
jpayne@69 1012
jpayne@69 1013 with tqdm(total=file_obj.size,
jpayne@69 1014 unit='B', unit_scale=True, unit_divisor=1024) as t:
jpayne@69 1015 fobj = CallbackIOWrapper(t.update, file_obj, "read")
jpayne@69 1016 while True:
jpayne@69 1017 chunk = fobj.read(chunk_size)
jpayne@69 1018 if not chunk:
jpayne@69 1019 break
jpayne@69 1020 t.reset()
jpayne@69 1021 # ... continue to use `t` for something else
jpayne@69 1022
jpayne@69 1023 Alternatively, use the even simpler ``wrapattr`` convenience function,
jpayne@69 1024 which would condense both the ``urllib`` and ``CallbackIOWrapper`` examples
jpayne@69 1025 down to:
jpayne@69 1026
jpayne@69 1027 .. code:: python
jpayne@69 1028
jpayne@69 1029 import urllib, os
jpayne@69 1030 from tqdm import tqdm
jpayne@69 1031
jpayne@69 1032 eg_link = "https://caspersci.uk.to/matryoshka.zip"
jpayne@69 1033 response = getattr(urllib, 'request', urllib).urlopen(eg_link)
jpayne@69 1034 with tqdm.wrapattr(open(os.devnull, "wb"), "write",
jpayne@69 1035 miniters=1, desc=eg_link.split('/')[-1],
jpayne@69 1036 total=getattr(response, 'length', None)) as fout:
jpayne@69 1037 for chunk in response:
jpayne@69 1038 fout.write(chunk)
jpayne@69 1039
jpayne@69 1040 The ``requests`` equivalent is nearly identical:
jpayne@69 1041
jpayne@69 1042 .. code:: python
jpayne@69 1043
jpayne@69 1044 import requests, os
jpayne@69 1045 from tqdm import tqdm
jpayne@69 1046
jpayne@69 1047 eg_link = "https://caspersci.uk.to/matryoshka.zip"
jpayne@69 1048 response = requests.get(eg_link, stream=True)
jpayne@69 1049 with tqdm.wrapattr(open(os.devnull, "wb"), "write",
jpayne@69 1050 miniters=1, desc=eg_link.split('/')[-1],
jpayne@69 1051 total=int(response.headers.get('content-length', 0))) as fout:
jpayne@69 1052 for chunk in response.iter_content(chunk_size=4096):
jpayne@69 1053 fout.write(chunk)
jpayne@69 1054
jpayne@69 1055 **Custom callback**
jpayne@69 1056
jpayne@69 1057 ``tqdm`` is known for intelligently skipping unnecessary displays. To make a
jpayne@69 1058 custom callback take advantage of this, simply use the return value of
jpayne@69 1059 ``update()``. This is set to ``True`` if a ``display()`` was triggered.
jpayne@69 1060
jpayne@69 1061 .. code:: python
jpayne@69 1062
jpayne@69 1063 from tqdm.auto import tqdm as std_tqdm
jpayne@69 1064
jpayne@69 1065 def external_callback(*args, **kwargs):
jpayne@69 1066 ...
jpayne@69 1067
jpayne@69 1068 class TqdmExt(std_tqdm):
jpayne@69 1069 def update(self, n=1):
jpayne@69 1070 displayed = super().update(n)
jpayne@69 1071 if displayed:
jpayne@69 1072 external_callback(**self.format_dict)
jpayne@69 1073 return displayed
jpayne@69 1074
jpayne@69 1075 ``asyncio``
jpayne@69 1076 ~~~~~~~~~~~
jpayne@69 1077
jpayne@69 1078 Note that ``break`` isn't currently caught by asynchronous iterators.
jpayne@69 1079 This means that ``tqdm`` cannot clean up after itself in this case:
jpayne@69 1080
jpayne@69 1081 .. code:: python
jpayne@69 1082
jpayne@69 1083 from tqdm.asyncio import tqdm
jpayne@69 1084
jpayne@69 1085 async for i in tqdm(range(9)):
jpayne@69 1086 if i == 2:
jpayne@69 1087 break
jpayne@69 1088
jpayne@69 1089 Instead, either call ``pbar.close()`` manually or use the context manager syntax:
jpayne@69 1090
jpayne@69 1091 .. code:: python
jpayne@69 1092
jpayne@69 1093 from tqdm.asyncio import tqdm
jpayne@69 1094
jpayne@69 1095 with tqdm(range(9)) as pbar:
jpayne@69 1096 async for i in pbar:
jpayne@69 1097 if i == 2:
jpayne@69 1098 break
jpayne@69 1099
jpayne@69 1100 Pandas Integration
jpayne@69 1101 ~~~~~~~~~~~~~~~~~~
jpayne@69 1102
jpayne@69 1103 Due to popular demand we've added support for ``pandas`` -- here's an example
jpayne@69 1104 for ``DataFrame.progress_apply`` and ``DataFrameGroupBy.progress_apply``:
jpayne@69 1105
jpayne@69 1106 .. code:: python
jpayne@69 1107
jpayne@69 1108 import pandas as pd
jpayne@69 1109 import numpy as np
jpayne@69 1110 from tqdm import tqdm
jpayne@69 1111
jpayne@69 1112 df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
jpayne@69 1113
jpayne@69 1114 # Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm`
jpayne@69 1115 # (can use `tqdm.gui.tqdm`, `tqdm.notebook.tqdm`, optional kwargs, etc.)
jpayne@69 1116 tqdm.pandas(desc="my bar!")
jpayne@69 1117
jpayne@69 1118 # Now you can use `progress_apply` instead of `apply`
jpayne@69 1119 # and `progress_map` instead of `map`
jpayne@69 1120 df.progress_apply(lambda x: x**2)
jpayne@69 1121 # can also groupby:
jpayne@69 1122 # df.groupby(0).progress_apply(lambda x: x**2)
jpayne@69 1123
jpayne@69 1124 In case you're interested in how this works (and how to modify it for your
jpayne@69 1125 own callbacks), see the
jpayne@69 1126 `examples <https://github.com/tqdm/tqdm/tree/master/examples>`__
jpayne@69 1127 folder or import the module and run ``help()``.
jpayne@69 1128
jpayne@69 1129 Keras Integration
jpayne@69 1130 ~~~~~~~~~~~~~~~~~
jpayne@69 1131
jpayne@69 1132 A ``keras`` callback is also available:
jpayne@69 1133
jpayne@69 1134 .. code:: python
jpayne@69 1135
jpayne@69 1136 from tqdm.keras import TqdmCallback
jpayne@69 1137
jpayne@69 1138 ...
jpayne@69 1139
jpayne@69 1140 model.fit(..., verbose=0, callbacks=[TqdmCallback()])
jpayne@69 1141
jpayne@69 1142 Dask Integration
jpayne@69 1143 ~~~~~~~~~~~~~~~~
jpayne@69 1144
jpayne@69 1145 A ``dask`` callback is also available:
jpayne@69 1146
jpayne@69 1147 .. code:: python
jpayne@69 1148
jpayne@69 1149 from tqdm.dask import TqdmCallback
jpayne@69 1150
jpayne@69 1151 with TqdmCallback(desc="compute"):
jpayne@69 1152 ...
jpayne@69 1153 arr.compute()
jpayne@69 1154
jpayne@69 1155 # or use callback globally
jpayne@69 1156 cb = TqdmCallback(desc="global")
jpayne@69 1157 cb.register()
jpayne@69 1158 arr.compute()
jpayne@69 1159
jpayne@69 1160 IPython/Jupyter Integration
jpayne@69 1161 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
jpayne@69 1162
jpayne@69 1163 IPython/Jupyter is supported via the ``tqdm.notebook`` submodule:
jpayne@69 1164
jpayne@69 1165 .. code:: python
jpayne@69 1166
jpayne@69 1167 from tqdm.notebook import trange, tqdm
jpayne@69 1168 from time import sleep
jpayne@69 1169
jpayne@69 1170 for i in trange(3, desc='1st loop'):
jpayne@69 1171 for j in tqdm(range(100), desc='2nd loop'):
jpayne@69 1172 sleep(0.01)
jpayne@69 1173
jpayne@69 1174 In addition to ``tqdm`` features, the submodule provides a native Jupyter
jpayne@69 1175 widget (compatible with IPython v1-v4 and Jupyter), fully working nested bars
jpayne@69 1176 and colour hints (blue: normal, green: completed, red: error/interrupt,
jpayne@69 1177 light blue: no ETA); as demonstrated below.
jpayne@69 1178
jpayne@69 1179 |Screenshot-Jupyter1|
jpayne@69 1180 |Screenshot-Jupyter2|
jpayne@69 1181 |Screenshot-Jupyter3|
jpayne@69 1182
jpayne@69 1183 The ``notebook`` version supports percentage or pixels for overall width
jpayne@69 1184 (e.g.: ``ncols='100%'`` or ``ncols='480px'``).
jpayne@69 1185
jpayne@69 1186 It is also possible to let ``tqdm`` automatically choose between
jpayne@69 1187 console or notebook versions by using the ``autonotebook`` submodule:
jpayne@69 1188
jpayne@69 1189 .. code:: python
jpayne@69 1190
jpayne@69 1191 from tqdm.autonotebook import tqdm
jpayne@69 1192 tqdm.pandas()
jpayne@69 1193
jpayne@69 1194 Note that this will issue a ``TqdmExperimentalWarning`` if run in a notebook
jpayne@69 1195 since it is not meant to be possible to distinguish between ``jupyter notebook``
jpayne@69 1196 and ``jupyter console``. Use ``auto`` instead of ``autonotebook`` to suppress
jpayne@69 1197 this warning.
jpayne@69 1198
jpayne@69 1199 Note that notebooks will display the bar in the cell where it was created.
jpayne@69 1200 This may be a different cell from the one where it is used.
jpayne@69 1201 If this is not desired, either
jpayne@69 1202
jpayne@69 1203 - delay the creation of the bar to the cell where it must be displayed, or
jpayne@69 1204 - create the bar with ``display=False``, and in a later cell call
jpayne@69 1205 ``display(bar.container)``:
jpayne@69 1206
jpayne@69 1207 .. code:: python
jpayne@69 1208
jpayne@69 1209 from tqdm.notebook import tqdm
jpayne@69 1210 pbar = tqdm(..., display=False)
jpayne@69 1211
jpayne@69 1212 .. code:: python
jpayne@69 1213
jpayne@69 1214 # different cell
jpayne@69 1215 display(pbar.container)
jpayne@69 1216
jpayne@69 1217 The ``keras`` callback has a ``display()`` method which can be used likewise:
jpayne@69 1218
jpayne@69 1219 .. code:: python
jpayne@69 1220
jpayne@69 1221 from tqdm.keras import TqdmCallback
jpayne@69 1222 cbk = TqdmCallback(display=False)
jpayne@69 1223
jpayne@69 1224 .. code:: python
jpayne@69 1225
jpayne@69 1226 # different cell
jpayne@69 1227 cbk.display()
jpayne@69 1228 model.fit(..., verbose=0, callbacks=[cbk])
jpayne@69 1229
jpayne@69 1230 Another possibility is to have a single bar (near the top of the notebook)
jpayne@69 1231 which is constantly re-used (using ``reset()`` rather than ``close()``).
jpayne@69 1232 For this reason, the notebook version (unlike the CLI version) does not
jpayne@69 1233 automatically call ``close()`` upon ``Exception``.
jpayne@69 1234
jpayne@69 1235 .. code:: python
jpayne@69 1236
jpayne@69 1237 from tqdm.notebook import tqdm
jpayne@69 1238 pbar = tqdm()
jpayne@69 1239
jpayne@69 1240 .. code:: python
jpayne@69 1241
jpayne@69 1242 # different cell
jpayne@69 1243 iterable = range(100)
jpayne@69 1244 pbar.reset(total=len(iterable)) # initialise with new `total`
jpayne@69 1245 for i in iterable:
jpayne@69 1246 pbar.update()
jpayne@69 1247 pbar.refresh() # force print final status but don't `close()`
jpayne@69 1248
jpayne@69 1249 Custom Integration
jpayne@69 1250 ~~~~~~~~~~~~~~~~~~
jpayne@69 1251
jpayne@69 1252 To change the default arguments (such as making ``dynamic_ncols=True``),
jpayne@69 1253 simply use built-in Python magic:
jpayne@69 1254
jpayne@69 1255 .. code:: python
jpayne@69 1256
jpayne@69 1257 from functools import partial
jpayne@69 1258 from tqdm import tqdm as std_tqdm
jpayne@69 1259 tqdm = partial(std_tqdm, dynamic_ncols=True)
jpayne@69 1260
jpayne@69 1261 For further customisation,
jpayne@69 1262 ``tqdm`` may be inherited from to create custom callbacks (as with the
jpayne@69 1263 ``TqdmUpTo`` example `above <#hooks-and-callbacks>`__) or for custom frontends
jpayne@69 1264 (e.g. GUIs such as notebook or plotting packages). In the latter case:
jpayne@69 1265
jpayne@69 1266 1. ``def __init__()`` to call ``super().__init__(..., gui=True)`` to disable
jpayne@69 1267 terminal ``status_printer`` creation.
jpayne@69 1268 2. Redefine: ``close()``, ``clear()``, ``display()``.
jpayne@69 1269
jpayne@69 1270 Consider overloading ``display()`` to use e.g.
jpayne@69 1271 ``self.frontend(**self.format_dict)`` instead of ``self.sp(repr(self))``.
jpayne@69 1272
jpayne@69 1273 Some submodule examples of inheritance:
jpayne@69 1274
jpayne@69 1275 - `tqdm/notebook.py <https://github.com/tqdm/tqdm/blob/master/tqdm/notebook.py>`__
jpayne@69 1276 - `tqdm/gui.py <https://github.com/tqdm/tqdm/blob/master/tqdm/gui.py>`__
jpayne@69 1277 - `tqdm/tk.py <https://github.com/tqdm/tqdm/blob/master/tqdm/tk.py>`__
jpayne@69 1278 - `tqdm/contrib/slack.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/slack.py>`__
jpayne@69 1279 - `tqdm/contrib/discord.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/discord.py>`__
jpayne@69 1280 - `tqdm/contrib/telegram.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/telegram.py>`__
jpayne@69 1281
jpayne@69 1282 Dynamic Monitor/Meter
jpayne@69 1283 ~~~~~~~~~~~~~~~~~~~~~
jpayne@69 1284
jpayne@69 1285 You can use a ``tqdm`` as a meter which is not monotonically increasing.
jpayne@69 1286 This could be because ``n`` decreases (e.g. a CPU usage monitor) or ``total``
jpayne@69 1287 changes.
jpayne@69 1288
jpayne@69 1289 One example would be recursively searching for files. The ``total`` is the
jpayne@69 1290 number of objects found so far, while ``n`` is the number of those objects which
jpayne@69 1291 are files (rather than folders):
jpayne@69 1292
jpayne@69 1293 .. code:: python
jpayne@69 1294
jpayne@69 1295 from tqdm import tqdm
jpayne@69 1296 import os.path
jpayne@69 1297
jpayne@69 1298 def find_files_recursively(path, show_progress=True):
jpayne@69 1299 files = []
jpayne@69 1300 # total=1 assumes `path` is a file
jpayne@69 1301 t = tqdm(total=1, unit="file", disable=not show_progress)
jpayne@69 1302 if not os.path.exists(path):
jpayne@69 1303 raise IOError("Cannot find:" + path)
jpayne@69 1304
jpayne@69 1305 def append_found_file(f):
jpayne@69 1306 files.append(f)
jpayne@69 1307 t.update()
jpayne@69 1308
jpayne@69 1309 def list_found_dir(path):
jpayne@69 1310 """returns os.listdir(path) assuming os.path.isdir(path)"""
jpayne@69 1311 listing = os.listdir(path)
jpayne@69 1312 # subtract 1 since a "file" we found was actually this directory
jpayne@69 1313 t.total += len(listing) - 1
jpayne@69 1314 # fancy way to give info without forcing a refresh
jpayne@69 1315 t.set_postfix(dir=path[-10:], refresh=False)
jpayne@69 1316 t.update(0) # may trigger a refresh
jpayne@69 1317 return listing
jpayne@69 1318
jpayne@69 1319 def recursively_search(path):
jpayne@69 1320 if os.path.isdir(path):
jpayne@69 1321 for f in list_found_dir(path):
jpayne@69 1322 recursively_search(os.path.join(path, f))
jpayne@69 1323 else:
jpayne@69 1324 append_found_file(path)
jpayne@69 1325
jpayne@69 1326 recursively_search(path)
jpayne@69 1327 t.set_postfix(dir=path)
jpayne@69 1328 t.close()
jpayne@69 1329 return files
jpayne@69 1330
jpayne@69 1331 Using ``update(0)`` is a handy way to let ``tqdm`` decide when to trigger a
jpayne@69 1332 display refresh to avoid console spamming.
jpayne@69 1333
jpayne@69 1334 Writing messages
jpayne@69 1335 ~~~~~~~~~~~~~~~~
jpayne@69 1336
jpayne@69 1337 This is a work in progress (see
jpayne@69 1338 `#737 <https://github.com/tqdm/tqdm/issues/737>`__).
jpayne@69 1339
jpayne@69 1340 Since ``tqdm`` uses a simple printing mechanism to display progress bars,
jpayne@69 1341 you should not write any message in the terminal using ``print()`` while
jpayne@69 1342 a progressbar is open.
jpayne@69 1343
jpayne@69 1344 To write messages in the terminal without any collision with ``tqdm`` bar
jpayne@69 1345 display, a ``.write()`` method is provided:
jpayne@69 1346
jpayne@69 1347 .. code:: python
jpayne@69 1348
jpayne@69 1349 from tqdm.auto import tqdm, trange
jpayne@69 1350 from time import sleep
jpayne@69 1351
jpayne@69 1352 bar = trange(10)
jpayne@69 1353 for i in bar:
jpayne@69 1354 # Print using tqdm class method .write()
jpayne@69 1355 sleep(0.1)
jpayne@69 1356 if not (i % 3):
jpayne@69 1357 tqdm.write("Done task %i" % i)
jpayne@69 1358 # Can also use bar.write()
jpayne@69 1359
jpayne@69 1360 By default, this will print to standard output ``sys.stdout``. but you can
jpayne@69 1361 specify any file-like object using the ``file`` argument. For example, this
jpayne@69 1362 can be used to redirect the messages writing to a log file or class.
jpayne@69 1363
jpayne@69 1364 Redirecting writing
jpayne@69 1365 ~~~~~~~~~~~~~~~~~~~
jpayne@69 1366
jpayne@69 1367 If using a library that can print messages to the console, editing the library
jpayne@69 1368 by replacing ``print()`` with ``tqdm.write()`` may not be desirable.
jpayne@69 1369 In that case, redirecting ``sys.stdout`` to ``tqdm.write()`` is an option.
jpayne@69 1370
jpayne@69 1371 To redirect ``sys.stdout``, create a file-like class that will write
jpayne@69 1372 any input string to ``tqdm.write()``, and supply the arguments
jpayne@69 1373 ``file=sys.stdout, dynamic_ncols=True``.
jpayne@69 1374
jpayne@69 1375 A reusable canonical example is given below:
jpayne@69 1376
jpayne@69 1377 .. code:: python
jpayne@69 1378
jpayne@69 1379 from time import sleep
jpayne@69 1380 import contextlib
jpayne@69 1381 import sys
jpayne@69 1382 from tqdm import tqdm
jpayne@69 1383 from tqdm.contrib import DummyTqdmFile
jpayne@69 1384
jpayne@69 1385
jpayne@69 1386 @contextlib.contextmanager
jpayne@69 1387 def std_out_err_redirect_tqdm():
jpayne@69 1388 orig_out_err = sys.stdout, sys.stderr
jpayne@69 1389 try:
jpayne@69 1390 sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err)
jpayne@69 1391 yield orig_out_err[0]
jpayne@69 1392 # Relay exceptions
jpayne@69 1393 except Exception as exc:
jpayne@69 1394 raise exc
jpayne@69 1395 # Always restore sys.stdout/err if necessary
jpayne@69 1396 finally:
jpayne@69 1397 sys.stdout, sys.stderr = orig_out_err
jpayne@69 1398
jpayne@69 1399 def some_fun(i):
jpayne@69 1400 print("Fee, fi, fo,".split()[i])
jpayne@69 1401
jpayne@69 1402 # Redirect stdout to tqdm.write() (don't forget the `as save_stdout`)
jpayne@69 1403 with std_out_err_redirect_tqdm() as orig_stdout:
jpayne@69 1404 # tqdm needs the original stdout
jpayne@69 1405 # and dynamic_ncols=True to autodetect console width
jpayne@69 1406 for i in tqdm(range(3), file=orig_stdout, dynamic_ncols=True):
jpayne@69 1407 sleep(.5)
jpayne@69 1408 some_fun(i)
jpayne@69 1409
jpayne@69 1410 # After the `with`, printing is restored
jpayne@69 1411 print("Done!")
jpayne@69 1412
jpayne@69 1413 Redirecting ``logging``
jpayne@69 1414 ~~~~~~~~~~~~~~~~~~~~~~~
jpayne@69 1415
jpayne@69 1416 Similar to ``sys.stdout``/``sys.stderr`` as detailed above, console ``logging``
jpayne@69 1417 may also be redirected to ``tqdm.write()``.
jpayne@69 1418
jpayne@69 1419 Warning: if also redirecting ``sys.stdout``/``sys.stderr``, make sure to
jpayne@69 1420 redirect ``logging`` first if needed.
jpayne@69 1421
jpayne@69 1422 Helper methods are available in ``tqdm.contrib.logging``. For example:
jpayne@69 1423
jpayne@69 1424 .. code:: python
jpayne@69 1425
jpayne@69 1426 import logging
jpayne@69 1427 from tqdm import trange
jpayne@69 1428 from tqdm.contrib.logging import logging_redirect_tqdm
jpayne@69 1429
jpayne@69 1430 LOG = logging.getLogger(__name__)
jpayne@69 1431
jpayne@69 1432 if __name__ == '__main__':
jpayne@69 1433 logging.basicConfig(level=logging.INFO)
jpayne@69 1434 with logging_redirect_tqdm():
jpayne@69 1435 for i in trange(9):
jpayne@69 1436 if i == 4:
jpayne@69 1437 LOG.info("console logging redirected to `tqdm.write()`")
jpayne@69 1438 # logging restored
jpayne@69 1439
jpayne@69 1440 Monitoring thread, intervals and miniters
jpayne@69 1441 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
jpayne@69 1442
jpayne@69 1443 ``tqdm`` implements a few tricks to increase efficiency and reduce overhead.
jpayne@69 1444
jpayne@69 1445 - Avoid unnecessary frequent bar refreshing: ``mininterval`` defines how long
jpayne@69 1446 to wait between each refresh. ``tqdm`` always gets updated in the background,
jpayne@69 1447 but it will display only every ``mininterval``.
jpayne@69 1448 - Reduce number of calls to check system clock/time.
jpayne@69 1449 - ``mininterval`` is more intuitive to configure than ``miniters``.
jpayne@69 1450 A clever adjustment system ``dynamic_miniters`` will automatically adjust
jpayne@69 1451 ``miniters`` to the amount of iterations that fit into time ``mininterval``.
jpayne@69 1452 Essentially, ``tqdm`` will check if it's time to print without actually
jpayne@69 1453 checking time. This behaviour can be still be bypassed by manually setting
jpayne@69 1454 ``miniters``.
jpayne@69 1455
jpayne@69 1456 However, consider a case with a combination of fast and slow iterations.
jpayne@69 1457 After a few fast iterations, ``dynamic_miniters`` will set ``miniters`` to a
jpayne@69 1458 large number. When iteration rate subsequently slows, ``miniters`` will
jpayne@69 1459 remain large and thus reduce display update frequency. To address this:
jpayne@69 1460
jpayne@69 1461 - ``maxinterval`` defines the maximum time between display refreshes.
jpayne@69 1462 A concurrent monitoring thread checks for overdue updates and forces one
jpayne@69 1463 where necessary.
jpayne@69 1464
jpayne@69 1465 The monitoring thread should not have a noticeable overhead, and guarantees
jpayne@69 1466 updates at least every 10 seconds by default.
jpayne@69 1467 This value can be directly changed by setting the ``monitor_interval`` of
jpayne@69 1468 any ``tqdm`` instance (i.e. ``t = tqdm.tqdm(...); t.monitor_interval = 2``).
jpayne@69 1469 The monitor thread may be disabled application-wide by setting
jpayne@69 1470 ``tqdm.tqdm.monitor_interval = 0`` before instantiation of any ``tqdm`` bar.
jpayne@69 1471
jpayne@69 1472
jpayne@69 1473 Merch
jpayne@69 1474 -----
jpayne@69 1475
jpayne@69 1476 You can buy `tqdm branded merch <https://tqdm.github.io/merch>`__ now!
jpayne@69 1477
jpayne@69 1478 Contributions
jpayne@69 1479 -------------
jpayne@69 1480
jpayne@69 1481 |GitHub-Commits| |GitHub-Issues| |GitHub-PRs| |OpenHub-Status| |GitHub-Contributions| |CII Best Practices|
jpayne@69 1482
jpayne@69 1483 All source code is hosted on `GitHub <https://github.com/tqdm/tqdm>`__.
jpayne@69 1484 Contributions are welcome.
jpayne@69 1485
jpayne@69 1486 See the
jpayne@69 1487 `CONTRIBUTING <https://github.com/tqdm/tqdm/blob/master/CONTRIBUTING.md>`__
jpayne@69 1488 file for more information.
jpayne@69 1489
jpayne@69 1490 Developers who have made significant contributions, ranked by *SLoC*
jpayne@69 1491 (surviving lines of code,
jpayne@69 1492 `git fame <https://github.com/casperdcl/git-fame>`__ ``-wMC --excl '\.(png|gif|jpg)$'``),
jpayne@69 1493 are:
jpayne@69 1494
jpayne@69 1495 ==================== ======================================================== ==== ================================
jpayne@69 1496 Name ID SLoC Notes
jpayne@69 1497 ==================== ======================================================== ==== ================================
jpayne@69 1498 Casper da Costa-Luis `casperdcl <https://github.com/casperdcl>`__ ~80% primary maintainer |Gift-Casper|
jpayne@69 1499 Stephen Larroque `lrq3000 <https://github.com/lrq3000>`__ ~9% team member
jpayne@69 1500 Martin Zugnoni `martinzugnoni <https://github.com/martinzugnoni>`__ ~3%
jpayne@69 1501 Daniel Ecer `de-code <https://github.com/de-code>`__ ~2%
jpayne@69 1502 Richard Sheridan `richardsheridan <https://github.com/richardsheridan>`__ ~1%
jpayne@69 1503 Guangshuo Chen `chengs <https://github.com/chengs>`__ ~1%
jpayne@69 1504 Helio Machado `0x2b3bfa0 <https://github.com/0x2b3bfa0>`__ ~1%
jpayne@69 1505 Kyle Altendorf `altendky <https://github.com/altendky>`__ <1%
jpayne@69 1506 Noam Yorav-Raphael `noamraph <https://github.com/noamraph>`__ <1% original author
jpayne@69 1507 Matthew Stevens `mjstevens777 <https://github.com/mjstevens777>`__ <1%
jpayne@69 1508 Hadrien Mary `hadim <https://github.com/hadim>`__ <1% team member
jpayne@69 1509 Mikhail Korobov `kmike <https://github.com/kmike>`__ <1% team member
jpayne@69 1510 ==================== ======================================================== ==== ================================
jpayne@69 1511
jpayne@69 1512 Ports to Other Languages
jpayne@69 1513 ~~~~~~~~~~~~~~~~~~~~~~~~
jpayne@69 1514
jpayne@69 1515 A list is available on
jpayne@69 1516 `this wiki page <https://github.com/tqdm/tqdm/wiki/tqdm-ports>`__.
jpayne@69 1517
jpayne@69 1518
jpayne@69 1519 LICENCE
jpayne@69 1520 -------
jpayne@69 1521
jpayne@69 1522 Open Source (OSI approved): |LICENCE|
jpayne@69 1523
jpayne@69 1524 Citation information: |DOI|
jpayne@69 1525
jpayne@69 1526 |README-Hits| (Since 19 May 2016)
jpayne@69 1527
jpayne@69 1528 .. |Logo| image:: https://tqdm.github.io/img/logo.gif
jpayne@69 1529 .. |Screenshot| image:: https://tqdm.github.io/img/tqdm.gif
jpayne@69 1530 .. |Video| image:: https://tqdm.github.io/img/video.jpg
jpayne@69 1531 :target: https://tqdm.github.io/video
jpayne@69 1532 .. |Slides| image:: https://tqdm.github.io/img/slides.jpg
jpayne@69 1533 :target: https://tqdm.github.io/PyData2019/slides.html
jpayne@69 1534 .. |Merch| image:: https://tqdm.github.io/img/merch.jpg
jpayne@69 1535 :target: https://tqdm.github.io/merch
jpayne@69 1536 .. |Build-Status| image:: https://img.shields.io/github/actions/workflow/status/tqdm/tqdm/test.yml?branch=master&label=tqdm&logo=GitHub
jpayne@69 1537 :target: https://github.com/tqdm/tqdm/actions/workflows/test.yml
jpayne@69 1538 .. |Coverage-Status| image:: https://img.shields.io/coveralls/github/tqdm/tqdm/master?logo=coveralls
jpayne@69 1539 :target: https://coveralls.io/github/tqdm/tqdm
jpayne@69 1540 .. |Branch-Coverage-Status| image:: https://codecov.io/gh/tqdm/tqdm/branch/master/graph/badge.svg
jpayne@69 1541 :target: https://codecov.io/gh/tqdm/tqdm
jpayne@69 1542 .. |Codacy-Grade| image:: https://app.codacy.com/project/badge/Grade/3f965571598f44549c7818f29cdcf177
jpayne@69 1543 :target: https://www.codacy.com/gh/tqdm/tqdm/dashboard
jpayne@69 1544 .. |CII Best Practices| image:: https://bestpractices.coreinfrastructure.org/projects/3264/badge
jpayne@69 1545 :target: https://bestpractices.coreinfrastructure.org/projects/3264
jpayne@69 1546 .. |GitHub-Status| image:: https://img.shields.io/github/tag/tqdm/tqdm.svg?maxAge=86400&logo=github&logoColor=white
jpayne@69 1547 :target: https://github.com/tqdm/tqdm/releases
jpayne@69 1548 .. |GitHub-Forks| image:: https://img.shields.io/github/forks/tqdm/tqdm.svg?logo=github&logoColor=white
jpayne@69 1549 :target: https://github.com/tqdm/tqdm/network
jpayne@69 1550 .. |GitHub-Stars| image:: https://img.shields.io/github/stars/tqdm/tqdm.svg?logo=github&logoColor=white
jpayne@69 1551 :target: https://github.com/tqdm/tqdm/stargazers
jpayne@69 1552 .. |GitHub-Commits| image:: https://img.shields.io/github/commit-activity/y/tqdm/tqdm.svg?logo=git&logoColor=white
jpayne@69 1553 :target: https://github.com/tqdm/tqdm/graphs/commit-activity
jpayne@69 1554 .. |GitHub-Issues| image:: https://img.shields.io/github/issues-closed/tqdm/tqdm.svg?logo=github&logoColor=white
jpayne@69 1555 :target: https://github.com/tqdm/tqdm/issues?q=
jpayne@69 1556 .. |GitHub-PRs| image:: https://img.shields.io/github/issues-pr-closed/tqdm/tqdm.svg?logo=github&logoColor=white
jpayne@69 1557 :target: https://github.com/tqdm/tqdm/pulls
jpayne@69 1558 .. |GitHub-Contributions| image:: https://img.shields.io/github/contributors/tqdm/tqdm.svg?logo=github&logoColor=white
jpayne@69 1559 :target: https://github.com/tqdm/tqdm/graphs/contributors
jpayne@69 1560 .. |GitHub-Updated| image:: https://img.shields.io/github/last-commit/tqdm/tqdm/master.svg?logo=github&logoColor=white&label=pushed
jpayne@69 1561 :target: https://github.com/tqdm/tqdm/pulse
jpayne@69 1562 .. |Gift-Casper| image:: https://img.shields.io/badge/dynamic/json.svg?color=ff69b4&label=gifts%20received&prefix=%C2%A3&query=%24..sum&url=https%3A%2F%2Fcaspersci.uk.to%2Fgifts.json
jpayne@69 1563 :target: https://cdcl.ml/sponsor
jpayne@69 1564 .. |Versions| image:: https://img.shields.io/pypi/v/tqdm.svg
jpayne@69 1565 :target: https://tqdm.github.io/releases
jpayne@69 1566 .. |PyPI-Downloads| image:: https://img.shields.io/pypi/dm/tqdm.svg?label=pypi%20downloads&logo=PyPI&logoColor=white
jpayne@69 1567 :target: https://pepy.tech/project/tqdm
jpayne@69 1568 .. |Py-Versions| image:: https://img.shields.io/pypi/pyversions/tqdm.svg?logo=python&logoColor=white
jpayne@69 1569 :target: https://pypi.org/project/tqdm
jpayne@69 1570 .. |Conda-Forge-Status| image:: https://img.shields.io/conda/v/conda-forge/tqdm.svg?label=conda-forge&logo=conda-forge
jpayne@69 1571 :target: https://anaconda.org/conda-forge/tqdm
jpayne@69 1572 .. |Snapcraft| image:: https://img.shields.io/badge/snap-install-82BEA0.svg?logo=snapcraft
jpayne@69 1573 :target: https://snapcraft.io/tqdm
jpayne@69 1574 .. |Docker| image:: https://img.shields.io/badge/docker-pull-blue.svg?logo=docker&logoColor=white
jpayne@69 1575 :target: https://hub.docker.com/r/tqdm/tqdm
jpayne@69 1576 .. |Libraries-Rank| image:: https://img.shields.io/librariesio/sourcerank/pypi/tqdm.svg?logo=koding&logoColor=white
jpayne@69 1577 :target: https://libraries.io/pypi/tqdm
jpayne@69 1578 .. |Libraries-Dependents| image:: https://img.shields.io/librariesio/dependent-repos/pypi/tqdm.svg?logo=koding&logoColor=white
jpayne@69 1579 :target: https://github.com/tqdm/tqdm/network/dependents
jpayne@69 1580 .. |OpenHub-Status| image:: https://www.openhub.net/p/tqdm/widgets/project_thin_badge?format=gif
jpayne@69 1581 :target: https://www.openhub.net/p/tqdm?ref=Thin+badge
jpayne@69 1582 .. |awesome-python| image:: https://awesome.re/mentioned-badge.svg
jpayne@69 1583 :target: https://github.com/vinta/awesome-python
jpayne@69 1584 .. |LICENCE| image:: https://img.shields.io/pypi/l/tqdm.svg
jpayne@69 1585 :target: https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE
jpayne@69 1586 .. |DOI| image:: https://img.shields.io/badge/DOI-10.5281/zenodo.595120-blue.svg
jpayne@69 1587 :target: https://doi.org/10.5281/zenodo.595120
jpayne@69 1588 .. |binder-demo| image:: https://mybinder.org/badge_logo.svg
jpayne@69 1589 :target: https://mybinder.org/v2/gh/tqdm/tqdm/master?filepath=DEMO.ipynb
jpayne@69 1590 .. |Screenshot-Jupyter1| image:: https://tqdm.github.io/img/jupyter-1.gif
jpayne@69 1591 .. |Screenshot-Jupyter2| image:: https://tqdm.github.io/img/jupyter-2.gif
jpayne@69 1592 .. |Screenshot-Jupyter3| image:: https://tqdm.github.io/img/jupyter-3.gif
jpayne@69 1593 .. |README-Hits| image:: https://cgi.cdcl.ml/hits?q=tqdm&style=social&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif
jpayne@69 1594 :target: https://cgi.cdcl.ml/hits?q=tqdm&a=plot&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif&style=social