Download file in python and cancel

I am trying to make a simple function to upload a file in python. The code is similar to

def download(url , dest): urllib.urlretrieve(url, dest) 

My problem is that if I want to cancel the download process in the middle of the download, how do I fit ???

This function is launched in the background of the application and launched by the button. Now I am trying to start it using another button.

Platform - XBMC.

+4
source share
2 answers

A simple class to do the same as your download function:

 import urllib import threading class Downloader: def __init__(self): self.stop_down = False self.thread = None def download(self, url, destination): self.thread = threading.Thread(target=self.__down, args=(url, destination)) self.thread.start() def __down(self, url, dest): _continue = True handler = urllib.urlopen(url) self.fp = open(dest, "w") while not self.stop_down and _continue: data = handler.read(4096) self.fp.write(data) _continue = data handler.close() self.fp.close() def cancel(self): self.stop_down = True 

So, when someone clicks the Cancel button, you must call the cancel() method.

Please note that this will not delete the partially downloaded file if you cancel it, but this is not difficult to do, for example, using os.unlink() .

The following script example shows how to use it by starting to download the ~ 20 MB file and canceling it after 5 seconds:

 import time if __name__ == "__main__": url = "http://ftp.postgresql.org/pub/source/v9.2.3/postgresql-9.2.3.tar.gz" down = Downloader() down.download(url, "file") print "Download started..." time.sleep(5) down.cancel() print "Download canceled" 
+2
source

If you cancel by pressing CTRL + C, you can use this constructed exception and continue with what you think should be the best.

In this case, if I cancel the middle of the download, I just want this partial file to be deleted:

 def download(url , dest): try: urllib.urlretrieve(url, dest) except KeyboardInterrupt: if os.path.exists(dest): os.remove(dest) except Exception, e: raise 
0
source

All Articles