Python urllib2 设置超时时间并处理超时异常
2013-08-01 21:20 江湖么名 阅读(30111) 评论(1) 收藏 举报可以使用 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
浙公网安备 33010602011771号