【发布时间】:2011-02-12 08:11:20
【问题描述】:
我在 urllib2 的 urlopen 中使用 timeout 参数。
urllib2.urlopen('http://www.example.org', timeout=1)
我如何告诉 Python 如果超时到期,应该引发自定义错误?
有什么想法吗?
【问题讨论】:
标签: python timeout urllib2 urllib
我在 urllib2 的 urlopen 中使用 timeout 参数。
urllib2.urlopen('http://www.example.org', timeout=1)
我如何告诉 Python 如果超时到期,应该引发自定义错误?
有什么想法吗?
【问题讨论】:
标签: python timeout urllib2 urllib
在极少数情况下您想使用except:。这样做会捕获任何异常,这可能很难调试,它会捕获包括SystemExit 和KeyboardInterupt 在内的异常,这会使您的程序使用起来很烦......
在最简单的情况下,你会捕捉到urllib2.URLError:
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)
以下应捕获连接超时时引发的特定错误:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
# For Python 2.6
if isinstance(e.reason, socket.timeout):
raise MyException("There was an error: %r" % e)
else:
# reraise the original error
raise
except socket.timeout, e:
# For Python 2.7
raise MyException("There was an error: %r" % e)
【讨论】:
socket.timeout添加了一个额外的捕获
hasattr(e,'reason') and isinstance(e.reason, socket.timeout),因为HttpError至少在Python 2.6中没有reason属性。
urllib2.URLError。从慢速服务器读取响应时超时似乎导致socket.timeout。所以总的来说,捕捉两者可以让你区分这些情况。
在 Python 2.7.3 中:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
print type(e) #not catch
except socket.timeout as e:
print type(e) #catched
raise MyException("There was an error: %r" % e)
【讨论】: