Skip to content

Instantly share code, notes, and snippets.

@imShakil
Last active August 27, 2021 11:30
Show Gist options
  • Save imShakil/574ee08b45a67c7f0a1dc5a5c346381a to your computer and use it in GitHub Desktop.
Save imShakil/574ee08b45a67c7f0a1dc5a5c346381a to your computer and use it in GitHub Desktop.
Python Progress-bar while downloading files using linux terminal
#!/usr/bin/python3
import os
import sys
import time
import urllib.request
def show_progress(block_number, block_size, total_size):
global start_time
if total_size < 0 or None:
return
if block_number == 0:
start_time = time.time()
return
duration = time.time() - start_time
progress_size = min(block_number * block_size, total_size)
speed = int(progress_size / (1024 * duration))
percent = min(int(block_number * block_size * 100 / total_size), 100)
sys.stdout.write("\r[{}{}] {}%, {} KB/s, Downloaded {:.3f}/{:.3f} MB in {:.3f} seconds ".format(
'#' * (percent // 5), '.' * (20 - percent // 5), percent, speed, progress_size / (1024*1024),
total_size / (1024 * 1024), duration))
sys.stdout.flush()
if __name__ == '__main__':
try:
url = sys.argv[1]
except IndexError as e:
print(e, "#usage: python3 progress-bar.py url")
file_extension = list(url.split('/'))[-1]
file_path = os.path.join(os.getcwd(), file_extension)
print("Downloading {} to {}".format(url, file_path))
urllib.request.urlretrieve(url, file_path, show_progress)
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment