2
votes

I'd better use the following sample codes to explain my problem:

while True:
    NewThread = threading.Thread(target = CheckSite, args = ("http://example.com", "http://demo.com"))
    NewThread.start()

    time.sleep(300)

def CheckSite(Url1, Url2):
    try:
        Response1 = urllib2.urlopen(Url1)
        Response2 = urllib2.urlopen(Url2)
        del Response1
        del Response2
    except Exception, reason:
        print "How should I delete Response1 and Response2 when exception occurs?"
        del Response1
        del Response2 #### You can't simply write this as Reponse2 might not even exist if exception shows up running Response1

I've wrote a really looong script, and it's used to check different sites running status(response time or similar stuff), just like what I did in the previous codes, I use couple of threads to check different site separately. As you can see in each thread there would be several server requests and of course you will get 403 or similar every now and then. I always think those wasted connections(ones with exceptions) would be collected by some kind of garbage collector in python, so I just leave them alone.

But when I check my network monitor, I found those wasted connections still there wasting resources. The longer the script running, the more wasted connections appears. I really don't want to do try-except clause each time sending server request so that del responsecan be used in each except part to destroy the wasted connection. There gotta be a better way to do this, anybody can help me out?

4
Why the grudge against exception handling? Second, and more important, how do you "check your network monitor" to see that there are still "wasted connections"? What tool are you using, and what is it's output? - Jim Brissom
@Jim: Simply read from my kaspersky network monitor, as there's lots of connections running there under this script(some are even hours long), so I guess these would be wasted connections, right? - Shane

4 Answers

3
votes

What exactly do you expect "delete" to mean in this context, anyway, and what are you hoping to accomplish?

Python has automatic garbage collection. These objects are defined, further, in such a way that the connection will be closed whenever the garbage collector gets around to collecting the corresponding objects.

If you want to ensure that connections are closed as soon as you no longer need the object, you can use the with construct. For example:

def CheckSite(Url1, Url2):
    with urllib2.urlopen(Url1) as Response1:
        with urllib2.urlopen(Url2) as Response2:
            # do stuff
1
votes

I'd also suggest to use the with statement in conjunction with the contextlib.closing function.

It should close the connection when it finishes the job or when it gets an exception.

Something like:

with contextlib.closing(urllib2.open(url)) as reponse:
    pass
#del response    #to assure the connection does not have references...
0
votes

You shoud use Response1.close(). with doesn't work with urllib2.urlopen directly, but see the contextlib.closing example in the Python documentation.

Connections can stay open for hours if not properly closed, even if the process creating them exits, due the reliable packet delivery features of TCP.

0
votes

You should not check for Exception rather you should catch URLError as noted in the Documentation.

If an exception isn't thrown, does the connection persist? Maybe what you're looking for is

try:
    Response1 = urllib2.urlopen(Url1)
    Response2 = urllib2.urlopen(Url2)
    Response1.close()
    Response2.close()
except URLError, reason:
    print "How should I delete Response1 and Response2 when exception occurs?"
    if Response2 is not None:
        Response2.close()
    elif Response1 is not None:
        Response1.close()

But I don't understand why you're encapsulating both in a single try. I would do the following personally.

def CheckSites(Url1, Url2):
    try:
        Response1 = urllib2.urlopen(Url1)
    except URLError, reason:
        print "Response 1 failed"
        return

    try:
        Response2 = urllib2.urlopen(Url2)
    except URLError, reason:
        print "Response 2 failed"
        ## close Response1
        Response1.close()
        ## do something or don't based on 1 passing and 2 failing
        return

    print "Both responded"
    ## party time.  rm -rf /

Note that this accomplishes the same thing because in your code, if Url1 fails, you'll never even try to open the Url2 connection.

** Side Note ** Threading is really not helping you here at all. You might as well just try them sequentially because only one thread is going to be running at a time.

http://dabeaz.blogspot.com/2009/08/inside-inside-python-gil-presentation.html
http://wiki.python.org/moin/GlobalInterpreterLock