老王Python-進階篇4-異常處理1.3(周末習題)
阿新 • • 發佈:2018-01-15
調用 page eve sage urn put not name bject
一 編寫with操作類Fileinfo(),定義__enter__和__exit__方法。完成功能:
1.1 在__enter__方法裏打開Fileinfo(filename),並且返回filename對應的內容。如果文件不存在等情況,需要捕獲異常。
1.2 在__enter__方法裏記錄文件打開的當前日期和文件名。並且把記錄的信息保持為log.txt。內容格式:"2014-4-5 xxx.txt"
1 import logging,os 2 3 class Fileinfo(object): 4 5 def __init__(self,filename): 6self.filename=filename 7 8 def __enter__(self): 9 try: 10 with open(self.filename,‘r‘) as new_file: 11 new_file.seek(0) 12 content=new_file.read() 13 except IOError: 14 return ‘error‘ 15 else: 16 self.__exit__() 17 return content 18 19 20 def __exit__(self): 21 logging.basicConfig(level=logging.DEBUG) 22 logger=logging.getLogger() 23 logger.setLevel=(logging.DEBUG) 24 hfile=logging.FileHandler(r"C:\Users\Administrator\Desktop\sendlog.log") 25 hfile.setLevel=(logging.DEBUG)26 formatter=logging.Formatter(‘[%(asctime)s]‘ ‘%(message)s‘) 27 hfile.setFormatter(formatter) 28 logger.addHandler(hfile) 29 30 logging.debug(self.filename) 31 32 if __name__==‘__main__‘: 33 c=Fileinfo(‘C:\\Users\\Administrator\\Desktop\\12.txt‘) 34 print c.__enter__()
二:用異常方法,處理下面需求:
info = [‘http://xxx.com‘,‘http:///xxx.com‘,‘http://xxxx.cm‘....]任意多的網址
2.1 定義一個方法get_page(listindex) listindex為下標的索引,類型為整數。 函數調用:任意輸入一個整數,返回列表下標對應URL的內容,用try except 分別捕獲列表下標越界和url 404 not found 的情況。
2.2 用logging模塊把404的url,記錄到當前目錄下的urlog.txt。urlog.txt的格式為:2013-04-05 15:50:03,625 ERROR http://wwwx.com 404 not foud、
1 import logging,os,urllib 2 3 class page(object): 4 global a 5 def __init__(self,num): 6 self.num=num 7 8 def get_page(self): 9 try: 10 new_url=a[self.num] 11 f=urllib.urlopen(new_url) 12 if urllib.urlopen(new_url).code==404: 13 raise Exception 14 except IndexError: 15 return u‘\n超出範圍‘ 16 except Exception: 17 self.__exit__() #內部方法調用 18 return ‘url 404 not found‘ 19 else: 20 return f.read() 21 22 def __exit__(self): 23 logging.basicConfig(level=logging.ERROR) 24 logger=logging.getLogger() 25 logger.setLevel=(logging.DEBUG) 26 hfile=logging.FileHandler(r"C:\Users\Administrator\Desktop\urllog.log") 27 hfile.setLevel=(logging.DEBUG) 28 formatter=logging.Formatter(‘[%(asctime)s]‘‘-‘‘%(levelname)s‘‘-‘‘%(message)s‘) 29 hfile.setFormatter(formatter) 30 logger.addHandler(hfile) 31 32 logging.error(a[self.num]) 33 34 if __name__==‘__main__‘: 35 num=int(raw_input(‘please input a number:\n‘)) 36 a=[‘https://wenda.so.com/q/1480716337726538‘,‘http://www.cnblogs.com/duyaya/‘,‘http://www.cn.com/d/‘] 37 c=page(num) 38 print c.get_page()
老王Python-進階篇4-異常處理1.3(周末習題)