blob: fa770a307cf1b1756216d5eb941d2c919b04e964 [file] [log] [blame]
Alex0989ecf2022-03-29 13:43:21 -05001# Author: Alex Savatieiev (osavatieiev@mirantis.com; a.savex@gmail.com)
2# Copyright 2019-2022 Mirantis, Inc.
Alex41485522019-04-12 17:26:18 -05003import sys
4
5
6class Progress(object):
Alexd9fd85e2019-05-16 16:58:24 -05007 _strsize = 0
8 _note_size = 0
9
Alex41485522019-04-12 17:26:18 -050010 def __init__(self, max_index, bar_size=21):
11 self.total = max_index
12 # bar size in symbols
13 self.bar_size = bar_size
14
15 def write_progress(self, index, note=''):
Alex3ebc5632019-04-18 16:47:18 -050016 # calc index and percent values
Alexd9fd85e2019-05-16 16:58:24 -050017 _suffix = ''
18 new_size = len(note)
19 if self._note_size > new_size:
20 _suffix = ' '*(self._note_size - new_size)
Alex1f90e7b2021-09-03 15:31:28 -050021 if index:
22 _percent = (100 * index) // self.total
23 _index = (self.bar_size * index) // self.total
24 else:
25 _percent = 0
26 _index = 0
27
Alex41485522019-04-12 17:26:18 -050028 # clear the line
29 sys.stdout.write('\r')
30 # print new progress
31 _format = "[{:"+str(self.bar_size-1)+"}] {}/{} ({}%) {}"
Alexd9fd85e2019-05-16 16:58:24 -050032 _progress_string = _format.format(
Alex41485522019-04-12 17:26:18 -050033 '='*_index,
34 index,
35 self.total,
36 _percent,
Alexd9fd85e2019-05-16 16:58:24 -050037 note + _suffix
38 )
39 sys.stdout.write(_progress_string)
40 # Save new note size and whole string size
41 self._strsize = len(_progress_string)
42 self._note_size = new_size
Alex41485522019-04-12 17:26:18 -050043 sys.stdout.flush()
Alex3ebc5632019-04-18 16:47:18 -050044
Alexd9fd85e2019-05-16 16:58:24 -050045 def clearline(self):
46 sys.stdout.write('\r')
47 sys.stdout.write(' '*self._strsize)
48 sys.stdout.write('\r')
Alexd0391d42019-05-21 18:48:55 -050049 sys.stdout.flush()
Alexd9fd85e2019-05-16 16:58:24 -050050
51 def end(self):
52 self._note_size = 0
53 self._strsize = 0
Alex41485522019-04-12 17:26:18 -050054 sys.stdout.write('\n')