Merge branch terrible and branch awful
[ipdf/code.git] / tools / progressbar.py
1 # From #http://nbviewer.ipython.org/github/ipython/ipython/blob/3607712653c66d63e0d7f13f073bde8c0f209ba8/docs/examples/notebooks/Animations_and_Progress.ipynb
2
3 import sys, time
4 try:
5     from IPython.display import clear_output
6     have_ipython = True
7 except ImportError:
8     have_ipython = False
9
10 class ProgressBar:
11     def __init__(self, iterations):
12         self.iterations = iterations
13         self.prog_bar = '[]'
14         self.fill_char = '*'
15         self.width = 40
16         self.__update_amount(0)
17         if have_ipython:
18             self.animate = self.animate_ipython
19         else:
20             self.animate = self.animate_noipython
21
22     def animate_ipython(self, iter):
23         print '\r', self,
24         sys.stdout.flush()
25         self.update_iteration(iter + 1)
26
27     def update_iteration(self, elapsed_iter):
28         self.__update_amount((elapsed_iter / float(self.iterations)) * 100.0)
29         self.prog_bar += '  %d of %s complete' % (elapsed_iter, self.iterations)
30
31     def __update_amount(self, new_amount):
32         percent_done = int(round((new_amount / 100.0) * 100.0))
33         all_full = self.width - 2
34         num_hashes = int(round((percent_done / 100.0) * all_full))
35         self.prog_bar = '[' + self.fill_char * num_hashes + ' ' * (all_full - num_hashes) + ']'
36         pct_place = (len(self.prog_bar) // 2) - len(str(percent_done))
37         pct_string = '%d%%' % percent_done
38         self.prog_bar = self.prog_bar[0:pct_place] + \
39             (pct_string + self.prog_bar[pct_place + len(pct_string):])
40
41     def __str__(self):
42         return str(self.prog_bar)

UCC git Repository :: git.ucc.asn.au