Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,9 @@ Parameters
Exponential moving average smoothing factor for speed estimates
(ignored in GUI mode). Ranges from 0 (average speed) to 1
(current/instantaneous speed) [default: 0.3].
* bar_format : str, optional
* bar_format : str or callable, optional
Specify a custom bar string formatting. May impact performance.
Can be a callable that will handle bar display.
If unspecified, will use '{l_bar}{bar}{r_bar}', where l_bar is
'{desc}{percentage:3.0f}%|' and r_bar is
'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}]'
Expand Down Expand Up @@ -484,6 +485,34 @@ It is recommend to use ``miniters=1`` whenever there is potentially
large differences in iteration speed (e.g. downloading a file over
a patchy connection).

Integration in a GUI
~~~~~~~~~~~~~~~~~~~~
``tqdm`` can easily be integrated in your own GUI by providing ``bar_format`` with
a callback function that will update your GUI bar display:

.. code:: python

from tqdm import tqdm
from time import sleep
from awesome import GUI

class my_gui_bar(object):
'''Toy GUI bar'''
def __init__(self):
self.gui_bar = GUI()
self.gui_bar.init()
# etc.

def update(self, bar_args={}):
'''Callback for tqdm to update the bar display'''
self.gui_bar.set_text = "{n_fmt}/{n_total} [{elapsed}>{remaining}]".format(bar_args)
self.gui_bar.set_progress = bar_args['n']

gbar = my_gui_bar()
for i in tqdm(range(100), bar_format=gbar.update):
sleep(0.1)


Pandas Integration
~~~~~~~~~~~~~~~~~~

Expand Down
8 changes: 7 additions & 1 deletion tqdm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@
from ._tqdm import trange
from ._tqdm_gui import tqdm_gui
from ._tqdm_gui import tgrange
from ._tqdm_custom import tqdm_custom
from ._tqdm_custom import tcrange
from ._tqdm_custommulti import tqdm_custommulti
from ._tqdm_custommulti import tcmrange
from ._tqdm_pandas import tqdm_pandas
from ._main import main
from ._version import __version__ # NOQA
from ._tqdm import TqdmTypeError, TqdmKeyError, TqdmDeprecationWarning

__all__ = ['tqdm', 'tqdm_gui', 'trange', 'tgrange', 'tqdm_pandas',
'tqdm_notebook', 'tnrange', 'main',
'tqdm_notebook', 'tnrange',
'tqdm_custom', 'tcrange', 'tqdm_custommulti', 'tcmrange',
'main',
'TqdmTypeError', 'TqdmKeyError', 'TqdmDeprecationWarning',
'__version__']

Expand Down
89 changes: 77 additions & 12 deletions tqdm/_tqdm.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,9 @@ def format_meter(n, total, elapsed, ncols=None, prefix='',
rate : float, optional
Manual override for iteration rate.
If [default: None], uses n/elapsed.
bar_format : str, optional
bar_format : str or callable, optional
Specify a custom bar string formatting. May impact performance.
Can be a callable that will handle bar display.
[default: '{l_bar}{bar}{r_bar}'], where l_bar is
'{desc}{percentage:3.0f}%|' and r_bar is
'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}]'
Expand Down Expand Up @@ -209,8 +210,10 @@ def format_meter(n, total, elapsed, ncols=None, prefix='',
r_bar = '| {0}/{1} [{2}<{3}, {4}]'.format(
n_fmt, total_fmt, elapsed_str, remaining_str, rate_fmt)

if ncols == 0:
return l_bar[:-1] + r_bar[1:]
# Formatting progress bar
# space available for bar's display
N_BARS = max(1, ncols - len(l_bar) - len(r_bar)) if ncols \
else 10

if bar_format:
# Custom bar formatting
Expand All @@ -231,25 +234,36 @@ def format_meter(n, total, elapsed, ncols=None, prefix='',
'remaining': remaining_str,
'l_bar': l_bar,
'r_bar': r_bar,
'n_bars': N_BARS,
'desc': prefix if prefix else '',
'ncols': ncols,
'frac': frac,
# 'bar': full_bar # replaced by procedure below
}

# Interpolate supplied bar format with the dict
if '{bar}' in bar_format:
if hasattr(bar_format, '__call__'):
# Callback user provided function/method to handle display
bar_format(bar_args)
elif bar_format is True:
# Just return the parameters dict
return bar_args
elif '{bar}' in bar_format:
# Format left/right sides of the bar, and format the bar
# later in the remaining space (avoid breaking display)
l_bar_user, r_bar_user = bar_format.split('{bar}')
l_bar = l_bar_user.format(**bar_args)
r_bar = r_bar_user.format(**bar_args)
# recompute bar's length
N_BARS = max(1, ncols - len(l_bar) - len(r_bar)) if ncols \
else 10
else:
# Else no progress bar, we can just format and return
return bar_format.format(**bar_args)

# Formatting progress bar
# space available for bar's display
N_BARS = max(1, ncols - len(l_bar) - len(r_bar)) if ncols \
else 10
# No space? Don't display a bar
if ncols == 0:
return l_bar + r_bar

# format bar depending on availability of unicode/ascii chars
if ascii:
Expand Down Expand Up @@ -278,10 +292,60 @@ def format_meter(n, total, elapsed, ncols=None, prefix='',
# Piece together the bar parts
return l_bar + full_bar + r_bar

# no total: no progressbar, ETA, just progress stats
# No total: no progressbar nor ETA, just progress stats
else:
return (prefix if prefix else '') + '{0}{1} [{2}, {3}]'.format(
n_fmt, unit, elapsed_str, rate_fmt)
# Custom formatting?
if bar_format:
l_bar = (prefix if prefix else '') + \
'{0}{1}'.format(n_fmt, unit)
r_bar = '[{0}, {1}]'.format(elapsed_str, rate_fmt)
N_BARS = max(1, ncols - len(l_bar) - len(r_bar)) if ncols \
else 10
# Populate dict with nototal appropriate values
# (must contain same set of params as with-total dict above)
bar_args = {'n': n,
'n_fmt': n_fmt,
'total': total,
'total_fmt': '?',
'percentage': '?',
'rate': rate if inv_rate is None else inv_rate,
'rate_noinv': rate,
'rate_noinv_fmt': ((format_sizeof(rate)
if unit_scale else
'{0:5.2f}'.format(rate))
if rate else '?') + unit + '/s',
'rate_fmt': rate_fmt,
'elapsed': elapsed_str,
'remaining': '?',
'l_bar': l_bar,
'r_bar': r_bar,
'n_bars': N_BARS,
'desc': prefix if prefix else '',
'ncols': ncols,
'frac': None,
}

# Interpolate supplied bar format with the dict
if hasattr(bar_format, '__call__'):
# Callback user provided function/method to handle display
bar_format(bar_args)
elif bar_format is True:
# Just return the parameters dict
return bar_args
elif '{bar}' in bar_format:
# Format left/right sides of the bar, and format the bar
# later in the remaining space (avoid breaking display)
l_bar_user, r_bar_user = bar_format.split('{bar}')
l_bar = l_bar_user.format(**bar_args)
r_bar = r_bar_user.format(**bar_args)
return l_bar + ' ' + r_bar
else:
# Else no progress bar, we can just format and return
return bar_format.format(**bar_args)
# No bar_format, just return a simple "no ETA" progress status
else:
return (prefix if prefix else '') + '{0}{1} [{2}, {3}]'.format(
n_fmt, unit, elapsed_str, rate_fmt)

def __new__(cls, *args, **kwargs):
# Create a new instance
Expand Down Expand Up @@ -508,8 +572,9 @@ def __init__(self, iterable=None, desc=None, total=None, leave=True,
Exponential moving average smoothing factor for speed estimates
(ignored in GUI mode). Ranges from 0 (average speed) to 1
(current/instantaneous speed) [default: 0.3].
bar_format : str, optional
bar_format : str or callable, optional
Specify a custom bar string formatting. May impact performance.
Can be a callable that will handle bar display.
If unspecified, will use '{l_bar}{bar}{r_bar}', where l_bar is
'{desc}{percentage:3.0f}%|' and r_bar is
'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}]'
Expand Down
Loading