Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

downloading a file in python and cancel

I am trying to make a simple function to download file in python The code is something like

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

My issue is that if I want to cancel the download process in the middle of downloading how do I approach???

This function runs in the background of app and is triggered by a button. Now I am trying to trigger it off with another button.

The platform is XBMC.

like image 757
Abul Hasnat Avatar asked Oct 21 '22 16:10

Abul Hasnat


1 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 have to call the cancel() method.

Please note that this will not remove the partially downloaded file if you cancel it, but that should not be hard to achieve using os.unlink(), for example.

The following example script shows how to use it, starting the download of a ~20Mb file and cancelling 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"
like image 51
Salem Avatar answered Oct 30 '22 20:10

Salem