# httpleak.py """ Demonstrate circular references in http http://bugs.python.org/issue7464 """ from __future__ import print_function try: from urllib2 import urlopen print("python 2") except ImportError: from urllib.request import urlopen print("python 3") import gc gc.disable() import weakref import traceback response = urlopen("http://www.google.com") try: w = weakref.ref(response.fp._sock) except AttributeError: w = weakref.ref(response.fp.raw._sock) # python 3 if not w(): raise RuntimeError print("socket is", repr(w())) if "HTTPResponse" in repr(w()): print("response socket fileobject is ", w().fp) print("got", repr(response.read()[:10])) response.close() del response if w(): print("socket still lives after close") if "HTTPResponse" in repr(w()): print("response socket fileobject is ", w().fp) gc.collect() if w(): print("Unexpected: socket still lives after gc") else: print("socket finally died after gc") else: print("socket died by itself")