Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to distinguish between socket error and timeout?

I'm having the following code:

try:
    while 1:
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.settimeout(5);
        s.connect((HOST,PORT))
        print("before send")
        #time.sleep(10);
        #s.sendall('GET / HTTP/1.1\r\nConnection: Keep-Alive\r\nHost: www.google.lt\r\n\r\n')
        data=s.recv(52)
        print("after send");
        s.close()
        if string.find(data,"HTTP/1.1 200 OK") == -1:
            print("Lost Connection")
        print(data)
        time.sleep(2)
except KeyboardInterrupt:
    print("CTRL C occured")
except socket.error:
    print("socket error occured: ")
except socket.timeout:
    print("timeout error")

I have commented the sendall function to test how recv generates timeout exception. But the problem is that i get socket.error exception. If i change the last lines of code to:

except socket.timeout:
    print("timeout error")
except socket.error:
     print("socket error occured: ")

Then i get socket.timeout exception. So what exception is really generated?

like image 687
zulunation Avatar asked Feb 16 '13 18:02

zulunation


1 Answers

socket.timeout is a subclass of socket.error. Really it's socket.timeout. When you catch a socket.error first, you catch a more general case.

>>> issubclass(socket.timeout, socket.error)
True

This code is correct:

except socket.timeout:
 print("timeout error")
except socket.error:
 print("socket error occured: ")

Try to catch specifically socket.timeout, then other socket.errors.

like image 145
Pavel Anossov Avatar answered Oct 20 '22 00:10

Pavel Anossov