处理urllib2的超时? – Python

我正在使用urllib2的urlopen中的超时参数。

urllib2.urlopen('http://www.example.org', timeout=1) 

我如何告诉Python,如果超时到期,应该提高自定义错误?


有任何想法吗?

除了以下几种情况外,你还可以使用。 这样做会捕获任何exception,这些exception很难debugging,并且捕获包括SystemExitKeyboardInterupt在内的exception,这可能会让程序很烦人。

在最简单的情况下,你会发现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) 

在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)