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 | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 19 | _percent = (100 * index) / self.total |
| 20 | _index = (self.bar_size * index) / self.total |
| 21 | # clear the line |
| 22 | sys.stdout.write('\r') |
| 23 | # print new progress |
| 24 | _format = "[{:"+str(self.bar_size-1)+"}] {}/{} ({}%) {}" |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 25 | _progress_string = _format.format( |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 26 | '='*_index, |
| 27 | index, |
| 28 | self.total, |
| 29 | _percent, |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 30 | note + _suffix |
| 31 | ) |
| 32 | sys.stdout.write(_progress_string) |
| 33 | # Save new note size and whole string size |
| 34 | self._strsize = len(_progress_string) |
| 35 | self._note_size = new_size |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 36 | sys.stdout.flush() |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 37 | |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 38 | def clearline(self): |
| 39 | sys.stdout.write('\r') |
| 40 | sys.stdout.write(' '*self._strsize) |
| 41 | sys.stdout.write('\r') |
Alex | d0391d4 | 2019-05-21 18:48:55 -0500 | [diff] [blame^] | 42 | sys.stdout.flush() |
Alex | d9fd85e | 2019-05-16 16:58:24 -0500 | [diff] [blame] | 43 | |
| 44 | def end(self): |
| 45 | self._note_size = 0 |
| 46 | self._strsize = 0 |
Alex | 4148552 | 2019-04-12 17:26:18 -0500 | [diff] [blame] | 47 | sys.stdout.write('\n') |