Alex | 0989ecf | 2022-03-29 13:43:21 -0500 | [diff] [blame^] | 1 | # Author: Alex Savatieiev (osavatieiev@mirantis.com; a.savex@gmail.com) |
| 2 | # Copyright 2019-2022 Mirantis, Inc. |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 3 | import sys |
| 4 | |
| 5 | |
| 6 | class Progress(object): |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 7 | _strsize = 0 |
| 8 | _note_size = 0 |
| 9 | |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 10 | 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=''): |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 16 | # calc index and percent values |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 17 | _suffix = '' |
| 18 | new_size = len(note) |
| 19 | if self._note_size > new_size: |
| 20 | _suffix = ' '*(self._note_size - new_size) |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 21 | 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 | |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 28 | # clear the line |
| 29 | sys.stdout.write('\r') |
| 30 | # print new progress |
| 31 | _format = "[{:"+str(self.bar_size-1)+"}] {}/{} ({}%) {}" |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 32 | _progress_string = _format.format( |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 33 | '='*_index, |
| 34 | index, |
| 35 | self.total, |
| 36 | _percent, |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 37 | 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 |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 43 | sys.stdout.flush() |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 44 | |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 45 | def clearline(self): |
| 46 | sys.stdout.write('\r') |
| 47 | sys.stdout.write(' '*self._strsize) |
| 48 | sys.stdout.write('\r') |
Alex | d0391d4 | 2019-05-21 18:48:55 -0500 | [diff] [blame] | 49 | sys.stdout.flush() |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 50 | |
| 51 | def end(self): |
| 52 | self._note_size = 0 |
| 53 | self._strsize = 0 |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 54 | sys.stdout.write('\n') |