Handling urllib2's timeout? - Python
我在urllib2的urlopen中使用了timeout参数。
1 | urllib2.urlopen('http://www.example.org', timeout=1) |
如何告诉Python如果超时到期,应该引发自定义错误?
有任何想法吗?
很少有您想要使用
在最简单的情况下,您将捕获
1 2 3 4 | try: urllib2.urlopen("http://example.com", timeout = 1) except urllib2.URLError, e: raise MyException("There was an error: %r" % e) |
以下应捕获连接超时时引发的特定错误:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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) |
在Python 2.7.3中:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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) |