chris.tian
chris.tian

Reputation: 770

Interrupting urllib.read

I have written a server application which monitors interrupted downloads. Now I want to create a test case with python. So far I have figured out how to download the whole page. But how do I tell the program to stop the download before completion or after a specific amount of downloaded bytes? Here is my code for a complete download...

opener = urllib2.build_opener()
response = opener.open(TARGET_URL)
data = response.read() // how to interrupt before completion?

Upvotes: 2

Views: 114

Answers (1)

NPE
NPE

Reputation: 500357

Call read() with a numeric argument smaller than the size of the content, and then drop the connection:

>>> import urllib2
>>> opener = urllib2.build_opener()
>>> response = opener.open('http://downloads.raspberrypi.org/NOOBS_latest')
>>> response.read(4)
'PK\x03\x04'
>>> response.close()

This does not guarantee that it will read exactly four bytes from the server, but it won't fetch the entire URL if its contents is large enough (for some definition of "large enough").

Upvotes: 1

Related Questions