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
20
Simple text-mode progress indicator.
22
Everyone loves ascii art!
24
To display an indicator, create a ProgressBar object. Call it,
25
passing Progress objects indicating the current state. When done,
28
Progress is suppressed when output is not sent to a terminal, so as
29
not to clutter log files.
32
# TODO: remove functions in favour of keeping everything in one class
34
# TODO: should be a global option e.g. --silent that disables progress
35
# indicators, preferably without needing to adjust all code that
36
# potentially calls them.
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
return hasattr(f, 'isatty') and f.isatty()
63
class Progress(object):
64
def __init__(self, units, current, total=None):
66
self.current = current
69
def _get_percent(self):
70
if self.total is not None and self.current is not None:
71
return 100.0 * self.current / self.total
73
percent = property(_get_percent)
76
if self.total is not None:
77
return "%i of %i %s %.1f%%" % (self.current, self.total, self.units,
80
return "%i %s" (self.current, self.units)
84
class ProgressBar(object):
85
def __init__(self, to_file=sys.stderr):
88
self.to_file = to_file
89
self.suppressed = not _supports_progress(self.to_file)
92
def __call__(self, progress):
93
if self.start is None:
94
self.start = datetime.datetime.now()
95
if not self.suppressed:
96
draw_progress_bar(progress, start_time=self.start,
100
if not self.suppressed:
101
clear_progress_bar(self.to_file)
105
def divide_timedelta(delt, divisor):
106
"""Divides a timedelta object"""
107
return datetime.timedelta(float(delt.days)/divisor,
108
float(delt.seconds)/divisor,
109
float(delt.microseconds)/divisor)
111
def str_tdelta(delt):
114
return str(datetime.timedelta(delt.days, delt.seconds))
117
def get_eta(start_time, progress, enough_samples=20):
118
if start_time is None or progress.current == 0:
120
elif progress.current < enough_samples:
122
elapsed = datetime.datetime.now() - start_time
123
total_duration = divide_timedelta((elapsed) * long(progress.total),
125
if elapsed < total_duration:
126
eta = total_duration - elapsed
128
eta = total_duration - total_duration
132
def draw_progress_bar(progress, start_time=None, to_file=sys.stderr):
133
eta = get_eta(start_time, progress)
134
if start_time is not None:
135
eta_str = " "+str_tdelta(eta)
139
fmt = " %i of %i %s (%.1f%%)"
140
f = fmt % (progress.total, progress.total, progress.units, 100.0)
141
cols = _width() - 3 - len(f)
142
if start_time is not None:
144
markers = int (float(cols) * progress.current / progress.total)
145
txt = fmt % (progress.current, progress.total, progress.units,
147
to_file.write("\r[%s%s]%s%s" % ('='*markers, ' '*(cols-markers), txt,
150
def clear_progress_bar(to_file=sys.stderr):
151
to_file.write('\r%s\r' % (' '*79))
154
def spinner_str(progress, show_text=False):
156
Produces the string for a textual "spinner" progress indicator
157
:param progress: an object represinting current progress
158
:param show_text: If true, show progress text as well
159
:return: The spinner string
161
>>> spinner_str(Progress("baloons", 0))
163
>>> spinner_str(Progress("baloons", 5))
165
>>> spinner_str(Progress("baloons", 6), show_text=True)
168
positions = ('|', '/', '-', '\\')
169
text = positions[progress.current % 4]
171
text+=" %i %s" % (progress.current, progress.units)
175
def spinner(progress, show_text=False, output=sys.stderr):
177
Update a spinner progress indicator on an output
178
:param progress: The progress to display
179
:param show_text: If true, show text as well as spinner
180
:param output: The output to write to
182
>>> spinner(Progress("baloons", 6), show_text=True, output=sys.stdout)
185
output.write('\r%s' % spinner_str(progress, show_text))
190
result = doctest.testmod()
193
print "All tests passed"
195
print "No tests to run"
199
from time import sleep
202
pb(Progress('Elephanten', i, 100))
206
if __name__ == "__main__":