Last active
February 20, 2020 02:48
-
-
Save mostafa1972/007ebcc357f28bc8471e33ef31c51de8 to your computer and use it in GitHub Desktop.
File Download from WebSite using Threading Module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import urllib.request | |
import os | |
from queue import Queue | |
class Downloader(threading.Thread): | |
"""Threaded File Downloader""" | |
def __init__(self, queue): | |
"""Initialize the thread""" | |
threading.Thread.__init__(self) | |
self.queue = queue | |
def run(self): | |
"""Run the thread""" | |
while True: | |
# gets the url from the queue | |
url = self.queue.get() | |
# download the file | |
self.download_file(url) | |
# send a signal to the queue that the job is done | |
self.queue.task_done() | |
def download_file(self, url): | |
"""Download the file""" | |
handle = urllib.request.urlopen(url) | |
fname = os.path.basename(url) | |
with open(fname, "wb") as f: | |
while True: | |
chunk = handle.read(1024) | |
if not chunk: break | |
f.write(chunk) | |
def main(urls): | |
""" | |
Run the program | |
""" | |
queue = Queue() | |
print('Download Started') | |
# create a thread pool and give them a queue | |
for i in range(5): | |
t = Downloader(queue) | |
t.setDaemon(True) | |
t.start() | |
# give the queue some data | |
for url in urls: | |
queue.put(url) | |
# wait for the queue to finish | |
queue.join() | |
print('Download Completed') | |
if __name__ == "__main__": | |
urls = ["https://www.etaxnbr.gov.bd/tpos/documents/Guideline/Bangla/Manual_Individual_Return_11GA_BL_v1.0.pdf", | |
"https://www.etaxnbr.gov.bd/tpos/documents/Guideline/Bangla/Manual_Register_Online_Account_BL_v1.0.pdf"] | |
main(urls) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank You :)