Progress Class Class for calculating and displaying download progress
| 122 | |
| 123 | |
| 124 | class ProgressPercentage(object): |
| 125 | ''' Progress Class |
| 126 | Class for calculating and displaying download progress |
| 127 | ''' |
| 128 | def __init__(self, client, bucket, filename): |
| 129 | ''' Initialize |
| 130 | initialize with: file name, file size and lock. |
| 131 | Set seen_so_far to 0. Set progress bar length |
| 132 | ''' |
| 133 | self._filename = filename |
| 134 | self._size = client.head_object(Bucket=bucket, Key=filename)['ContentLength'] |
| 135 | self._seen_so_far = 0 |
| 136 | self._lock = threading.Lock() |
| 137 | self.prog_bar_len = 80 |
| 138 | |
| 139 | def __call__(self, bytes_amount): |
| 140 | ''' Call |
| 141 | When called, increments seen_so_far by bytes_amount, |
| 142 | calculates percentage of seen_so_far/total file size |
| 143 | and prints progress bar. |
| 144 | ''' |
| 145 | # To simplify we'll assume this is hooked up to a single filename. |
| 146 | with self._lock: |
| 147 | self._seen_so_far += bytes_amount |
| 148 | ratio = round((float(self._seen_so_far) / float(self._size)) * (self.prog_bar_len - 6), 1) |
| 149 | current_length = int(round(ratio)) |
| 150 | |
| 151 | percentage = round(100 * ratio / (self.prog_bar_len - 6), 1) |
| 152 | |
| 153 | bars = '+' * current_length |
| 154 | output = bars + ' ' * (self.prog_bar_len - current_length - len(str(percentage)) - 1) + str(percentage) + '% ' + self.convert_bytes(self._seen_so_far) + ' / ' + self.convert_bytes(self._size) + ' ' * 5 |
| 155 | |
| 156 | if self._seen_so_far != self._size: |
| 157 | sys.stdout.write(output + '\r') |
| 158 | else: |
| 159 | sys.stdout.write(output + '\n') |
| 160 | sys.stdout.flush() |
| 161 | |
| 162 | def convert_bytes(self, num): |
| 163 | ''' Convert Bytes |
| 164 | Converts bytes to scaled format (e.g KB, MB, etc.) |
| 165 | ''' |
| 166 | step_unit = 1000.0 |
| 167 | for x in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB']: |
| 168 | if num < step_unit: |
| 169 | return "%3.1f %s" % (num, x) |
| 170 | num /= step_unit |
| 171 |