Readable progress

This commit is contained in:
CorpNewt 2018-10-07 14:05:02 -05:00 committed by GitHub
parent b2999bb734
commit e50e41cec8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -10,13 +10,39 @@ class Downloader:
def __init__(self):
return
def get_size(self, size, suff=None):
if size == -1:
return "Unknown"
ext = ["B","KB","MB","GB","PB"]
s = float(size)
s_dict = {}
# Iterate the ext list, and divide by 1000 each time
for e in ext:
s_dict[e] = s
s /= 1000
if suff and suff.upper() in s_dict:
# We supplied the suffix - use it \o/
bval = round(s_dict[suff.upper()], 2)
biggest = suff.upper()
else:
# Get the maximum >= 1 type
biggest = next((x for x in ext[::-1] if s_dict[x] >= 1), "B")
# Round to 2 decimal places
bval = round(s_dict[biggest], 2)
return "{:,.2f} {}".format(bval, biggest)
def _progress_hook(self, response, bytes_so_far, total_size):
if total_size > 0:
percent = float(bytes_so_far) / total_size
percent = round(percent*100, 2)
sys.stdout.write("Downloaded {:,} of {:,} bytes ({:.2f}%)\r".format(bytes_so_far, total_size, percent))
t_s = self.get_size(total_size)
try:
b_s = self.get_size(bytes_so_far, t_s.split(" ")[1])
except:
b_s = self.get_size(bytes_so_far)
sys.stdout.write("Downloaded {} of {} ({:.2f}%)\r".format(b_s, t_s, percent))
else:
sys.stdout.write("Downloaded {:,} bytes\r".format(bytes_so_far))
sys.stdout.write("Downloaded {}\r".format(b_s))
def get_string(self, url, progress = True):
response = urlopen(url)
@ -76,4 +102,4 @@ class Downloader:
if os.path.exists(file):
return file
else:
return None
return None