Source code for pycaps.util.progress
import sys
from datetime import datetime, timedelta
def _format_timedelta(td):
seconds = td.total_seconds()
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
return "%d:%02d:%02d" % (hours, minutes, round(seconds))
[docs]class ProgressBar(object):
def __init__(self, descr, n_steps, width=20):
"""
Create a progress bar object. Doesn't actually start timing or print anything; call initialize() to do that.
Args:
descr (str): Description of the task to be performed (e.g. "Loading data: ")
n_steps (int): Number of steps involved in the task.
width (int): Width of the progress bar on screen in characters.
"""
self._descr = descr
self._progress = 0
self._n_steps = n_steps
self._width = width
[docs] def initialize(self):
"""
Starts timing the task and prints the initial progress bar to the screen.
"""
self._start_time = datetime.now()
self._print_bar()
[docs] def is_complete(self):
"""
Is the task complete?
Returns:
A boolean specifying whether or not the task is complete.
"""
return self._progress == self._n_steps
[docs] def complete_step(self, print_bar=True):
"""
Tell a progress bar that one of the tasks is complete.
Args:
print_bar (bool): Whether or not to print the bar after this step (defaults to True).
"""
self.set_step(self._progress + 1, print_bar=print_bar)
[docs] def set_step(self, step, print_bar=True):
"""
Tell the progress bar that we have completed a certain number of tasks.
Args:
step (int): The number of tasks we have completed.
print_bar (bool): Whether or not to print the bar after this step (defaults to True).
"""
if step > self._n_steps:
# print "Warning: Step number %d out of bounds for current progress bar (%d steps max)." % (step, self._n_steps)
step = self._n_steps
self._progress = step
if print_bar:
self._print_bar()
def _print_bar(self):
"""
Print the bar to the screen.
"""
n_hashes = self._progress * self._width / self._n_steps
n_spaces = self._width - n_hashes
completed = "%.1f%%" % (100 * float(self._progress) / self._n_steps)
completed_pad = " " * (6 - len(completed))
elapsed = _format_timedelta(datetime.now() - self._start_time)
sys.stdout.write("\r%s[%s%s] %s%s (%s elapsed)" % (self._descr, "#" * n_hashes, " " * n_spaces, completed, completed_pad, elapsed))
sys.stdout.flush()
if self.is_complete():
print
if __name__ == "__main__":
import time
n_steps = 130
pb = ProgressBar("Loading stuff: ", n_steps, width=40)
pb.initialize()
for idx in xrange(n_steps):
time.sleep(0.1)
pb.complete_step()