分享

python异常处理

 java_laq小馆 2014-05-05

处理Python中urllib2/mechanize库进行socket通信超时的问题

分类: Python Linux 269人阅读 评论(0) 收藏 举报
最近实验室的网络状况不太稳定,信息采集程序经常阻塞在通信时的recv()处,Python的urllib2/mechanize库在做HTTP访问时,是用socket方式进行通信,那么我们可以设置一个timeout值,来检测是否超时,并作出相应的异常处理。


异常处理的几个片段代码如下:

  1. import socket  
  2. import urllib2  
  3. try:  
  4.     resp = urllib2.urlopen(req, timeout=32)  
  5. except urllib2.URLError, e:  
  6.     print "Bad URL or timeout"  
  7.     #处理异常  
  8. except socket.timeout, e:  
  9.     print "socket timeout"  
  10.     #处理异常  

  1. import urllib2  
  2. import socket  
  3. #In Python 2.7.3  
  4. class MyException(Exception):  
  5.     pass  
  6.   
  7. try:  
  8.     urllib2.urlopen("http://", timeout = 32)  
  9. except urllib2.URLError as e:  
  10.     print type(e)    #not catch  
  11. except socket.timeout as e:  
  12.     print type(e)    #catched  
  13.     raise MyException("There was an error: %r" % e)  

下面这部分代码是的dbr所写,感谢他的帮助!
  1. import urllib2  
  2. import socket  
  3.   
  4. class MyException(Exception):  
  5.     pass  
  6.   
  7. try:  
  8.     urllib2.urlopen("http://", timeout = 1)  
  9. except urllib2.URLError, e:  
  10.     # For Python 2.6  
  11.     if isinstance(e.reason, socket.timeout):  
  12.         raise MyException("There was an error: %r" % e)  
  13.     else:  
  14.         # reraise the original error  
  15.         raise  
  16. except socket.timeout, e:  
  17.     # For Python 2.7  
  18.     raise MyException("There was an error: %r" %   

下面是关于使用mechanize库的open方法(函数)时,捕获超时异常的代码,感谢中RoadieRich的帮助

(If you're using Python 2.6 or better, and a correspondingly updated version of mechanize, mechanize.urlopen should accept a timeout=... optional argument which seems to be what you're looking for... 具体地址: http:///questions/3552928/how-do-i-set-a- timeout-value-for-pythons-mechanize)

片段代码如下:

  1. tried=0  
  2. connected = False  
  3. while not Connected:  
  4.     try:  
  5.         r = b.open('http://www.google.com/foobar', timeout=32)  
  6.         connected = true # if line above fails, this is never executed  
  7.     except mechanize.HTTPError as e:  
  8.         print e.code              
  9.         tried += 1          
  10.         if tried > 4:  
  11.             exit()   
  12.         sleep(30)  
  13.   
  14.     except mechanize.URLError as e:  
  15.         print e.reason.args              
  16.         tried += 1  
  17.         if tried > 4:  
  18.             exit()          
  19.         sleep(30

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多