3

Possible Duplicate:
should I call close() after urllib.urlopen()?
Do objects created by urllib2.urlopen() represent a constant connection?

I haven't seen any code samples in the Python documentation that indicate it's necessary to close connections to remote servers.

import urllib2
handle = urllib2.urlopen('http://download.thinkbroadband.com/5MB.zip')
# ... do whatever

In the code above It feels wrong to not call close() on handle when I'm done. What's happening here? Is it necessary to close the connection manually or is it closed for me?

Community
  • 1
  • 1
Matty
  • 33,203
  • 13
  • 65
  • 93
  • 2
    Sorry, deleted my answer. This has been answered well here - http://stackoverflow.com/questions/1522636/should-i-call-close-after-urllib-urlopen – timc Apr 25 '12 at 01:17
  • @timc Does this also apply to urllib2? – Matty Apr 25 '12 at 01:18
  • @timc I was going to respond to your answer ("It is not actually a 'connection' that you're creating. urlopen returns a file-like object so it's not really necessary to close it until you no longer want to read or write from it.") with the following: It doesn't maintain an open connection to the remote server? What happens when `read(x)` is called multiple times? Is a new connection created for each read? Is there any advantage to calling `close()` or can I just leave it until the GC picks it up? – Matty Apr 25 '12 at 01:21
  • @Matty as Charles pointed out it applies across both urllib and urllib2 as they both return a file-like object. As far as I'm aware there is no open connection to the server and the response is written to a buffer. If you try it in your example handle.read() you will get the content of the url, if you try it again you will get nothing as you have reached the end of the buffer in the same way you would with a file object. – timc Apr 25 '12 at 01:26
  • @timc `x` could be less than the size indicated in the Content-Length header and `read()` could be called multiple times, retrieving small chunks, the sum of all the chunks being less than the total file size. Running some test code I see that `read()` does do a network communication every time it's called and the remote file isn't buffered locally in its entirety. – Matty Apr 25 '12 at 01:31
  • @Matty then I apologize for my misunderstanding. Unfortunately I'm unable to test at this minute. I wonder whether a new connection is created for each read() request or if the object represents a constant connection. – timc Apr 25 '12 at 01:36
  • 1
    @timc I might break that into a new question! – Matty Apr 25 '12 at 01:37

0 Answers0