python urllib2 超時處理實例

gd7g 9年前發布 | 1K 次閱讀 C/C++

python的urllib2包的timeout異常需要通過socket.timeout異常來捕獲,如下實例:

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)</pre> 


 本文由用戶 gd7g 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!