mdgaziur001

Downloader by MD Gaziur Rahman Noor

Mar 25th, 2020
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. import requests
  2. import sys
  3. import time
  4. import shutil
  5.  
  6. chunk_size = 1024
  7.  
  8. def autoconvert(length):
  9.     length=float(length)
  10.     s=round(length/1048576,2)
  11.     if s<1024:
  12.         return str(s)+" MB"
  13.     elif s>=1024:
  14.         return str(round(s/1024,2))+" GB"
  15.     elif s>=1024*1024:
  16.         return str(round(s/(1024*1024),2))+" TB"
  17.    
  18.  
  19. def Download():
  20.     console_columns,console_rows=shutil.get_terminal_size()
  21.     scls=(25*console_columns)//120
  22.     url=input("Enter the url for downloading file: ")
  23.     filename=url.split('/')[-1]
  24.     if "?" in filename:
  25.         filename=filename.split('?')
  26.         filename=filename[0]
  27.     try:
  28.         response=requests.get(url,stream=True)
  29.     except ConnectionError:
  30.         print("Cannot connect to the destination url!")
  31.         sys.exit(1)
  32.     except ConnectionAbortedError:
  33.         print("The server actively refused to connect!")
  34.         sys.exit(1)
  35.     except:
  36.         print("Cannot connect to the server!")
  37.         sys.exit(1)
  38.     dest=input("Enter the destination(with \ at the end): ")
  39.     file_length=response.headers['content-length']
  40.     curdown=0
  41.     try:
  42.         with open(dest+filename,"wb") as f:
  43.             if file_length==0:
  44.                 f.write(response.content)
  45.             else:
  46.                 for data in response.iter_content(chunk_size=chunk_size):
  47.                     console_columns,console_rows=shutil.get_terminal_size()
  48.                     scls=(25*console_columns)//120
  49.                     curdown+=len(data)
  50.                     percent=(curdown*50)/(float(file_length))
  51.                     f.write(data)
  52.                     barcount=int((percent*scls)//50)
  53.                     spacecount=scls-barcount
  54.                     ac=autoconvert(curdown)
  55.                     af=autoconvert(file_length)
  56.                     print("\rDownloading",filename,"[","█"*barcount," "*spacecount+"]",ac,"/",af,round((100*percent)/50,2),"%",file=sys.stdout,end='')
  57.                     sys.stdout.flush()
  58.     except PermissionError:
  59.         print("Cannot create file in %s! Do you have the permission to do this?"%(dest))
  60.     print()
  61.     print("Download Completed!")
  62. def main():
  63.     Download()
  64. if __name__=="__main__":
  65.     main()
Add Comment
Please, Sign In to add comment