should I call close() after urllib.urlopen()?

Viewed 54836

I'm new to Python and reading someone else's code:

should urllib.urlopen() be followed by urllib.close()? Otherwise, one would leak connections, correct?

5 Answers

You basically do need to explicitly close your connection when using IronPython. The automatic closing on going out of scope relies on the garbage collection. I ran into a situation where the garbage collection did not run for so long that Windows ran out of sockets. I was polling a webserver at high frequency (i.e. as high as IronPython and the connection would allow, ~7Hz). I could see the "established connections" (i.e. sockets in use) go up and up on PerfMon. The solution was to call gc.collect() after every call to urlopen.

urllib.request module uses HTTP/1.1 and includes Connection:close header in its HTTP requests.

It's from official docs, you can check it here.

Related