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
40
"""Return estimated terminal width.
42
TODO: Do something smart on Windows?
44
TODO: Is there anything that gets a better update when the window
45
is resized while the program is running?
49
return int(os.environ['COLUMNS'])
50
except (IndexError, KeyError, ValueError):
54
def _supports_progress(f):
55
return hasattr(f, 'isatty') and f.isatty()
59
class Progress(object):
60
def __init__(self, units, current, total=None):
62
self.current = current
65
def _get_percent(self):
66
if self.total is not None and self.current is not None:
67
return 100.0 * self.current / self.total
69
percent = property(_get_percent)
72
if self.total is not None:
73
return "%i of %i %s %.1f%%" % (self.current, self.total, self.units,
76
return "%i %s" (self.current, self.units)
80
class ProgressBar(object):
81
def __init__(self, to_file=sys.stderr):
84
self.to_file = to_file
85
self.suppressed = not _supports_progress(self.to_file)
88
def __call__(self, progress):
89
if self.start is None:
90
self.start = datetime.datetime.now()
91
if not self.suppressed:
92
draw_progress_bar(progress, start_time=self.start,
96
if not self.suppressed:
97
clear_progress_bar(self.to_file)
101
def divide_timedelta(delt, divisor):
102
"""Divides a timedelta object"""
103
return datetime.timedelta(float(delt.days)/divisor,
104
float(delt.seconds)/divisor,
105
float(delt.microseconds)/divisor)
107
def str_tdelta(delt):
110
return str(datetime.timedelta(delt.days, delt.seconds))
113
def get_eta(start_time, progress, enough_samples=20):
114
if start_time is None or progress.current == 0:
116
elif progress.current < enough_samples:
118
elapsed = datetime.datetime.now() - start_time
119
total_duration = divide_timedelta((elapsed) * long(progress.total),
121
if elapsed < total_duration:
122
eta = total_duration - elapsed
124
eta = total_duration - total_duration
128
def draw_progress_bar(progress, start_time=None, to_file=sys.stderr):
129
eta = get_eta(start_time, progress)
130
if start_time is not None:
131
eta_str = " "+str_tdelta(eta)
135
fmt = " %i of %i %s (%.1f%%)"
136
f = fmt % (progress.total, progress.total, progress.units, 100.0)
137
cols = _width() - 3 - len(f)
138
if start_time is not None:
140
markers = int (float(cols) * progress.current / progress.total)
141
txt = fmt % (progress.current, progress.total, progress.units,
143
to_file.write("\r[%s%s]%s%s" % ('='*markers, ' '*(cols-markers), txt,
146
def clear_progress_bar(to_file=sys.stderr):
147
to_file.write('\r%s\r' % (' '*79))
150
def spinner_str(progress, show_text=False):
152
Produces the string for a textual "spinner" progress indicator
153
:param progress: an object represinting current progress
154
:param show_text: If true, show progress text as well
155
:return: The spinner string
157
>>> spinner_str(Progress("baloons", 0))
159
>>> spinner_str(Progress("baloons", 5))
161
>>> spinner_str(Progress("baloons", 6), show_text=True)
164
positions = ('|', '/', '-', '\\')
165
text = positions[progress.current % 4]
167
text+=" %i %s" % (progress.current, progress.units)
171
def spinner(progress, show_text=False, output=sys.stderr):
173
Update a spinner progress indicator on an output
174
:param progress: The progress to display
175
:param show_text: If true, show text as well as spinner
176
:param output: The output to write to
178
>>> spinner(Progress("baloons", 6), show_text=True, output=sys.stdout)
181
output.write('\r%s' % spinner_str(progress, show_text))
186
result = doctest.testmod()
189
print "All tests passed"
191
print "No tests to run"
195
from time import sleep
198
pb(Progress('Elephanten', i, 100))
202
if __name__ == "__main__":