gpt4 book ai didi

python - 捕获套接字超时异常

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

我想捕获套接字超时(最好是在异常中)... except urllib.error.URLError: 可以捕获它,但我需要区分死链接和超时。 ... 如果我取出 except urllib.error.URLError: 套接字超时不会捕获并且脚本会因 socket.timeout 错误而终止

import urllib.request,urllib.parse,urllib.error
import socket
import http
socket.setdefaulttimeout(0.1)


try:
file2 = urllib.request.Request('http://uk.geforce.com/html://')
file2.add_header("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.29 Safari/525.13")
file3 = urllib.request.urlopen(file2).read().decode("utf8", 'ignore')
except urllib.error.URLError: print('fail')
except socket.error: print('fail')
except socket.timeout: print('fail')
except UnicodeEncodeError: print('fail')
except http.client.BadStatusLine: print('fail')
except http.client.IncompleteRead: print('fail')
except urllib.error.HTTPError: print('fail')

print('done')

最佳答案

...
except urllib.error.URLError, e:
print type(e.reason)

你会看到 <class 'socket.timeout'>每当有套接字超时时。这是你想要的吗?

例如:

try:
data = urllib2.urlopen("http://www.abcnonexistingurlxyz.com")
except Exception,e:
print type(e.reason)
...
<class 'socket.timeout'>

关于python - 捕获套接字超时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7167107/

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