Python 101 by Michael Driscoll

Python 101 by Michael Driscoll

Author:Michael Driscoll
Language: eng
Format: epub, pdf
Publisher: leanpub.com
Published: 2016-04-12T16:00:00+00:00


This is basically a complete rewrite of the first script. In this one we import the os and urllib2 modules as well as the threading module. We will be using urllib2 to do the actual downloading inside the thread class. The os module is used to extract the name of the file we’re downloading so we can use it to create a file with the same name on our machine. In the DownloadThread class, we set up the __init__ to accept a url and a name for the thread. In the run method, we open up the url, extract the filename and then use that filename for naming / creating the file on disk. Then we use a while loop to download the file a kilobyte at a time and write it to disk. Once the file is finished saving, we print out the name of the thread and which url has finished downloading.

The Python 3 version of the code is slightly different. You have to import urllib instead of urllib2 and use urllib.request.urlopen instead of urllib2.urlopen. Here’s the code so you can see the difference:

1 # Python 3 version 2 3 import os 4 import urllib.request 5 6 from threading import Thread 7 8 class DownloadThread(Thread): 9 """ 10 A threading example that can download a file 11 """ 12 13 def __init__(self, url, name): 14 """Initialize the thread""" 15 Thread.__init__(self) 16 self.name = name 17 self.url = url 18 19 def run(self): 20 """Run the thread""" 21 handle = urllib.request.urlopen(self.url) 22 fname = os.path.basename(self.url) 23 with open(fname, "wb") as f_handler: 24 while True: 25 chunk = handle.read(1024) 26 if not chunk: 27 break 28 f_handler.write(chunk) 29 msg = "%s has finished downloading %s!" % (self.name, 30 self.url) 31 print(msg) 32 33 def main(urls): 34 """ 35 Run the program 36 """ 37 for item, url in enumerate(urls): 38 name = "Thread %s" % (item+1) 39 thread = DownloadThread(url, name) 40 thread.start() 41 42 if __name__ == "__main__": 43 urls = ["http://www.irs.gov/pub/irs-pdf/f1040.pdf", 44 "http://www.irs.gov/pub/irs-pdf/f1040a.pdf", 45 "http://www.irs.gov/pub/irs-pdf/f1040ez.pdf", 46 "http://www.irs.gov/pub/irs-pdf/f1040es.pdf", 47 "http://www.irs.gov/pub/irs-pdf/f1040sb.pdf"] 48 main(urls)



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.