sajeeb_chandan

Multi-Threaded Downloader

Feb 14th, 2019
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.50 KB | None | 0 0
  1. import os
  2. import csv
  3. import sys
  4. import urllib.request
  5. import urllib.response
  6. import re
  7. import queue
  8. import threading
  9. import time
  10.  
  11. '''
  12. Step 001:
  13. # Read the CSV file
  14. # For each row in csv file extract the links
  15. Step 002:
  16. # Write the link into a text file with '\n' (New line) concat
  17. Step 003:
  18. # Read that text file
  19. # Create a queue
  20. # And insert all the link into queue which contains .MP3 Extension
  21. Step 004:
  22. # Create a function which will download file.
  23. # This function will take queue and saving directory as parameter
  24. '''
  25.  
  26. start = time.time()
  27. q = queue.Queue()
  28. threads = []
  29. txt_file = open('C:\\Users\\Engineers\\Downloads\\172.27.102.252_14th_Feb_2019.txt', 'w')
  30. save_directory = 'C:\\Users\\Engineers\\Downloads\\MP3\\'
  31. thread_lock = threading.Lock()
  32.  
  33. # Step 001
  34. with open('C:\\Users\\Engineers\\Downloads\\172.27.102.252_14th_Feb_2019.csv', 'r') as csv_file:
  35.     for row in csv.reader(csv_file, delimiter=','):
  36.         if re.match(r'https?:\/{2}(?:[\/-\\w.]|(?:%[\da-fA-F]{2}))+', str(list(row)[0])):
  37.             # Step 002
  38.             txt_file.write(str(list(row)[0]) + '\n')
  39.  
  40. # Step 003
  41. with open('C:\\Users\\Engineers\\Downloads\\172.27.102.252_14th_Feb_2019.txt', 'r') as f:
  42.     for line in csv.reader(f, delimiter='\n'):
  43.         if str(line[0]).__contains__('.MP3'):
  44.             q.put(str(line[0]))
  45.  
  46. print(q.qsize())
  47.  
  48.  
  49. # Step 004
  50. def multi_threaded_downloader(q, save_dir):
  51.     try:
  52.         while q.empty() is not True:
  53.  
  54.             base_url = q.get(block=False)
  55.             request_body = urllib.request.Request(base_url)
  56.             request_body.add_header('User-Agent',
  57.                                     r'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0')
  58.             response_body = urllib.request.urlopen(request_body)
  59.             # response_data = response_body.read()
  60.  
  61.             if not os.path.exists(save_dir[0:len(save_dir) - len(os.path.basename(save_dir))]):
  62.                 os.mkdir(save_dir[0:len(save_dir) - len(os.path.basename(save_dir))])
  63.             with open(save_dir[0:len(save_dir) - len(os.path.basename(save_dir))] + urllib.parse.unquote(
  64.                     os.path.basename(base_url)),
  65.                       'wb') as f:
  66.                 with thread_lock:
  67.                     total = response_body.length
  68.                     downloaded = 0
  69.                     while total > downloaded:
  70.                         chunk_size = int(max(1024, 1024*1024))
  71.                         x = response_body.read(chunk_size)
  72.                         f.write(x)
  73.                         downloaded = downloaded + len(x)
  74.                         done = int((100 * downloaded) / total)
  75.                         # print(str(done) + '\n')
  76.                         sys.stdout.write('\r[{}{}]'.format('█' * done, str(done)))
  77.                         sys.stdout.flush()
  78.                         if total == downloaded:
  79.                             print("Successfully Downloaded {0}\n".format(
  80.                                 urllib.parse.unquote(os.path.basename(base_url))))
  81.                             q.task_done()
  82.  
  83.     except Exception as ex:
  84.         print(ex)
  85.         q.task_done()
  86.  
  87.  
  88. for i in range(5):
  89.     t = threading.Thread(name='thread {0}'.format(i), target=multi_threaded_downloader, args=(q, save_directory))
  90.     threads.append(t)
  91.     t.setDaemon(True)
  92.     t.start()
  93. q.join()
  94.  
  95. # for t in threads:
  96. #     t.join()
  97. #     print('{0} Has joined'.format(t.getName()))
  98.  
  99. end = time.time()
  100.  
  101. print("Total elapsed time {0}".format(end - start))
Add Comment
Please, Sign In to add comment