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"
Salem source share