download - downloading a file in python and cancel -
i trying make simple function download file in python code like
def download(url , dest): urllib.urlretrieve(url, dest) my issue if want cancel download process in middle of downloading how approach???
this function runs in background of app , triggered button. trying trigger off button.
the platform xbmc.
a simple class same 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 , _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 clicks "cancel" button have call cancel() method.
please note not remove partially downloaded file if cancel it, should not hard achieve using os.unlink(), example.
the following example script shows how use it, starting download of ~20mb file , cancelling 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"
Comments
Post a Comment