1
# Copyright (C) 2005 Aaron Bentley <aaron.bentley@utoronto.ca>
2
# Copyright (C) 2005 Canonical <canonical.com>
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
"""Simple text-mode progress indicator.
21
To display an indicator, create a ProgressBar object. Call it,
22
passing Progress objects indicating the current state. When done,
25
Progress is suppressed when output is not sent to a terminal, so as
26
not to clutter log files.
29
# TODO: remove functions in favour of keeping everything in one class
31
# TODO: should be a global option e.g. --silent that disables progress
32
# indicators, preferably without needing to adjust all code that
33
# potentially calls them.
35
# TODO: Perhaps don't write updates faster than a certain rate, say
44
"""Return estimated terminal width.
46
TODO: Do something smart on Windows?
48
TODO: Is there anything that gets a better update when the window
49
is resized while the program is running?
53
return int(os.environ['COLUMNS'])
54
except (IndexError, KeyError, ValueError):
58
def _supports_progress(f):
59
if not hasattr(f, 'isatty'):
64
if os.environ.get('TERM') == 'dumb':
65
# e.g. emacs compile window
71
class ProgressBar(object):
72
"""Progress bar display object.
74
Several options are available to control the display. These can
75
be passed as parameters to the constructor or assigned at any time:
78
Show percentage complete.
80
Show rotating baton. This ticks over on every update even
81
if the values don't change.
83
Show predicted time-to-completion.
87
Show numerical counts.
89
The output file should be in line-buffered or unbuffered mode.
92
MIN_PAUSE = 0.1 # seconds
104
object.__init__(self)
105
self.to_file = to_file
106
self.suppressed = not _supports_progress(self.to_file)
111
self.last_total = None
112
self.show_pct = show_pct
113
self.show_spinner = show_spinner
114
self.show_eta = show_eta
115
self.show_bar = show_bar
116
self.show_count = show_count
120
self.update(self.last_msg, self.last_cnt, self.last_total)
124
def update(self, msg, current_cnt=None, total_cnt=None):
125
"""Update and redraw progress bar."""
129
# save these for the tick() function
131
self.last_cnt = current_cnt
132
self.last_total = total_cnt
135
if self.start_time is None:
136
self.start_time = now
138
interval = now - self.last_update
139
if interval > 0 and interval < self.MIN_PAUSE:
142
self.last_update = now
147
assert current_cnt <= total_cnt
149
assert current_cnt >= 0
151
if self.show_eta and self.start_time and total_cnt:
152
eta = get_eta(self.start_time, current_cnt, total_cnt)
153
eta_str = " " + str_tdelta(eta)
157
if self.show_spinner:
158
spin_str = self.SPIN_CHARS[self.spin_pos % 4] + ' '
162
# always update this; it's also used for the bar
165
if self.show_pct and total_cnt and current_cnt:
166
pct = 100.0 * current_cnt / total_cnt
167
pct_str = ' (%5.1f%%)' % pct
171
if not self.show_count:
173
elif current_cnt is None:
175
elif total_cnt is None:
176
count_str = ' %i' % (current_cnt)
178
# make both fields the same size
179
t = '%i' % (total_cnt)
180
c = '%*i' % (len(t), current_cnt)
181
count_str = ' ' + c + '/' + t
184
# progress bar, if present, soaks up all remaining space
185
cols = width - 1 - len(msg) - len(spin_str) - len(pct_str) \
186
- len(eta_str) - len(count_str) - 3
189
# number of markers highlighted in bar
190
markers = int(round(float(cols) * current_cnt / total_cnt))
191
bar_str = '[' + ('=' * markers).ljust(cols) + '] '
193
# don't know total, so can't show completion.
194
# so just show an expanded spinning thingy
195
m = self.spin_pos % cols
196
ms = (' ' * m + '*').ljust(cols)
198
bar_str = '[' + ms + '] '
204
m = spin_str + bar_str + msg + count_str + pct_str + eta_str
206
assert len(m) < width
207
self.to_file.write('\r' + m.ljust(width - 1))
208
#self.to_file.flush()
215
self.to_file.write('\r%s\r' % (' ' * (_width() - 1)))
216
#self.to_file.flush()
220
def str_tdelta(delt):
223
delt = int(round(delt))
224
return '%d:%02d:%02d' % (delt/3600,
229
def get_eta(start_time, current, total, enough_samples=3):
230
if start_time is None:
236
if current < enough_samples:
242
elapsed = time.time() - start_time
244
if elapsed < 2.0: # not enough time to estimate
247
total_duration = float(elapsed) * float(total) / float(current)
249
assert total_duration >= elapsed
251
return total_duration - elapsed
256
result = doctest.testmod()
259
print "All tests passed"
261
print "No tests to run"
265
from time import sleep
266
pb = ProgressBar(show_pct=True, show_bar=True, show_spinner=False)
268
pb.update('Elephanten', i, 99)
275
if __name__ == "__main__":