Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 1 | import sys |
| 2 | |
| 3 | |
| 4 | class Progress(object): |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 5 | _strsize = 0 |
| 6 | _note_size = 0 |
| 7 | |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 8 | def __init__(self, max_index, bar_size=21): |
| 9 | self.total = max_index |
| 10 | # bar size in symbols |
| 11 | self.bar_size = bar_size |
| 12 | |
| 13 | def write_progress(self, index, note=''): |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 14 | # calc index and percent values |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 15 | _suffix = '' |
| 16 | new_size = len(note) |
| 17 | if self._note_size > new_size: |
| 18 | _suffix = ' '*(self._note_size - new_size) |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 19 | if index: |
| 20 | _percent = (100 * index) // self.total |
| 21 | _index = (self.bar_size * index) // self.total |
| 22 | else: |
| 23 | _percent = 0 |
| 24 | _index = 0 |
| 25 | |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 26 | # clear the line |
| 27 | sys.stdout.write('\r') |
| 28 | # print new progress |
| 29 | _format = "[{:"+str(self.bar_size-1)+"}] {}/{} ({}%) {}" |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 30 | _progress_string = _format.format( |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 31 | '='*_index, |
| 32 | index, |
| 33 | self.total, |
| 34 | _percent, |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 35 | note + _suffix |
| 36 | ) |
| 37 | sys.stdout.write(_progress_string) |
| 38 | # Save new note size and whole string size |
| 39 | self._strsize = len(_progress_string) |
| 40 | self._note_size = new_size |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 41 | sys.stdout.flush() |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 42 | |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 43 | def clearline(self): |
| 44 | sys.stdout.write('\r') |
| 45 | sys.stdout.write(' '*self._strsize) |
| 46 | sys.stdout.write('\r') |
Alex | d0391d4 | 2019-05-21 18:48:55 -0500 | [diff] [blame] | 47 | sys.stdout.flush() |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 48 | |
| 49 | def end(self): |
| 50 | self._note_size = 0 |
| 51 | self._strsize = 0 |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 52 | sys.stdout.write('\n') |