2013-02-16 51 views
7

我有下面的代码:Python:如何区分套接字错误和超时?

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") 

我评论了sendall功能测试的recv如何产生超时异常。 但问题是,我得到socket.error异常。 如果我的代码的最后几行更改为:

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

然后我得到socket.timeout例外。 那真的产生了什么异常?

回答

17

socket.timeoutsocket.error的子类。真的是socket.timeout。当你首先遇到socket.error时,你会发现一个更一般的情况。

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

此代码是正确的:

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

试图抓住专门socket.timeout,那么其他socket.error秒。