How to kill/stop a Thread?

Fredrik Lundh fredrik at pythonware.com
Wed Mar 22 03:57:58 EST 2006


Dirk Zimmermann wrote:

> I like to do the following: Via http I get a stream of data and I like
> to store this data with a python program. So what I need is to start the
> downloading and to stop it after a given time. My aproach was to use:
>     urllib.urlretrieve("ULR","FILENAME")
>
> It is fine! But how to stop the retrieving? Because it is a constant
> stream of data there is no natural end. So I thought I use
> treading.Thread to do it:
>
>     def retr():
>         urllib.urlretrieve("URL","FILENAME")
>
>     t=threading.Thread(target=retr)
>     t.start()
>
> It's fine! The data is downloaded and I'm back in my program to do some
> other stuff. BUT: I cannot stop the download. How can I achieve this?
> (Another way of solution (w/o threading) would also helpful, of course!)

why not just use urlopen instead, and stop reading from it when you have
enough data ?

    stream = urllib.urlopen("URL")

    while not enough data:
        data = stream.read(BUFSIZE)
        if not data:
            break
        output.write(data)

another alternative is to use asynchronous sockets; see e.g.

    http://effbot.org/zone/effnews-1.htm#asynchronous-http
    http://effbot.org/zone/effnews-3.htm#managing-downloads

</F>






More information about the Python-list mailing list