gpt4 book ai didi

python - Python中如何区分超时错误和其他 `URLError`?

转载 作者:太空狗 更新时间:2023-10-30 01:10:17 27 4
gpt4 key购买 nike

如何区分超时错误和Python中的其他URLError

编辑

当我捕获到 URLError 时,它可能是Temporary failure in name resolutiontimeout,或其他一些错误?我如何区分彼此?

最佳答案

我使用类似下面选项 2 的代码...但要获得全面的答案,请查看 Michael Foord's urllib2 page

如果您使用下面的选项 1 或选项 2,您可以通过查看 e.codee.reason< 在 except 子句中添加尽可能多的智能和分支

选项 1:

from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(someurl)
try:
response = urlopen(req)
except HTTPError, e:
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
except URLError, e:
print 'We failed to reach a server.'
print 'Reason: ', e.reason
else:
# everything is fine

选项 2:

from urllib import urlencode
from urllib2 import Request
# insert other code here...
error = False
error_code = ""
try:
if method.upper()=="GET":
response = urlopen(req)
elif method.upper()=="POST":
response = urlopen(req,data)
except IOError, e:
if hasattr(e, 'reason'):
#print 'We failed to reach a server.'
#print 'Reason: ', e.reason
error = True
error_code = e.reason
elif hasattr(e, 'code'):
#print 'The server couldn\'t fulfill the request.'
#print 'Error code: ', e.code
error = True
error_code = e.code
else:
# info is dictionary of server parameters, such as 'content-type', etc...
info = response.info().dict
page = response.read()

关于python - Python中如何区分超时错误和其他 `URLError`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5467260/

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