gpt4 book ai didi

Python:如何区分套接字错误和超时?

转载 作者:太空狗 更新时间:2023-10-29 21:17:33 34 4
gpt4 key购买 nike

我有以下代码:

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 异常。那么真正产生了什么异常呢?

最佳答案

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

try catch 特定的socket.timeout,然后是其他socket.error

关于Python:如何区分套接字错误和超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14913880/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com