Python urllib2 设置超时时间并处理超时异常

可以使用 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:  
    if isinstance(e.reason, socket.timeout):  
        raise MyException("There was an error: %r" % e)  
    else:  
        # reraise the original error  
        raise
原文地址:https://www.cnblogs.com/mmix2009/p/3231265.html