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.
38
# TODO: Perhaps don't write updates faster than a certain rate, say
47
"""Return estimated terminal width.
49
TODO: Do something smart on Windows?
51
TODO: Is there anything that gets a better update when the window
52
is resized while the program is running?
56
return int(os.environ['COLUMNS'])
57
except (IndexError, KeyError, ValueError):
61
def _supports_progress(f):
62
return hasattr(f, 'isatty') and f.isatty()
66
class Progress(object):
67
"""Description of progress through a task.
69
Basically just a fancy tuple holding:
72
noun string describing what is being traversed, e.g.
76
how many objects have been processed so far
79
total number of objects to process, if known.
82
def __init__(self, units, current, total=None):
84
self.current = current
87
def _get_percent(self):
88
if self.total is not None and self.current is not None:
89
return 100.0 * self.current / self.total
91
percent = property(_get_percent)
94
if self.total is not None:
95
return "%i of %i %s %.1f%%" % (self.current, self.total, self.units,
98
return "%i %s" (self.current, self.units)
102
class ProgressBar(object):
103
def __init__(self, to_file=sys.stderr):
104
object.__init__(self)
106
self.to_file = to_file
107
self.suppressed = not _supports_progress(self.to_file)
110
def __call__(self, progress):
111
if self.start is None:
112
self.start = datetime.datetime.now()
113
if not self.suppressed:
114
draw_progress_bar(progress, start_time=self.start,
115
to_file=self.to_file)
118
if not self.suppressed:
119
clear_progress_bar(self.to_file)
123
def divide_timedelta(delt, divisor):
124
"""Divides a timedelta object"""
125
return datetime.timedelta(float(delt.days)/divisor,
126
float(delt.seconds)/divisor,
127
float(delt.microseconds)/divisor)
129
def str_tdelta(delt):
132
return str(datetime.timedelta(delt.days, delt.seconds))
135
def get_eta(start_time, progress, enough_samples=20):
136
if start_time is None or progress.current == 0:
138
elif progress.current < enough_samples:
140
elapsed = datetime.datetime.now() - start_time
141
total_duration = divide_timedelta((elapsed) * long(progress.total),
143
if elapsed < total_duration:
144
eta = total_duration - elapsed
146
eta = total_duration - total_duration
150
def draw_progress_bar(progress, start_time=None, to_file=sys.stderr):
151
eta = get_eta(start_time, progress)
152
if start_time is not None:
153
eta_str = " "+str_tdelta(eta)
157
fmt = " %i of %i %s (%.1f%%)"
158
f = fmt % (progress.total, progress.total, progress.units, 100.0)
159
cols = _width() - 3 - len(f)
160
if start_time is not None:
162
markers = int(round(float(cols) * progress.current / progress.total))
163
txt = fmt % (progress.current, progress.total, progress.units,
165
to_file.write("\r[%s%s]%s%s" % ('='*markers, ' '*(cols-markers), txt,
168
def clear_progress_bar(to_file=sys.stderr):
169
to_file.write('\r%s\r' % (' '*79))
172
def spinner_str(progress, show_text=False):
174
Produces the string for a textual "spinner" progress indicator
175
:param progress: an object represinting current progress
176
:param show_text: If true, show progress text as well
177
:return: The spinner string
179
>>> spinner_str(Progress("baloons", 0))
181
>>> spinner_str(Progress("baloons", 5))
183
>>> spinner_str(Progress("baloons", 6), show_text=True)
186
positions = ('|', '/', '-', '\\')
187
text = positions[progress.current % 4]
189
text+=" %i %s" % (progress.current, progress.units)
193
def spinner(progress, show_text=False, output=sys.stderr):
195
Update a spinner progress indicator on an output
196
:param progress: The progress to display
197
:param show_text: If true, show text as well as spinner
198
:param output: The output to write to
200
>>> spinner(Progress("baloons", 6), show_text=True, output=sys.stdout)
203
output.write('\r%s' % spinner_str(progress, show_text))
208
result = doctest.testmod()
211
print "All tests passed"
213
print "No tests to run"
217
from time import sleep
220
pb(Progress('Elephanten', i, 100))
224
if __name__ == "__main__":