python中异常处理中级题目_老王Python-进阶篇4-异常处理1.3(周末习题)

一 编写with操作类Fileinfo(),定义__enter__和__exit__方法。完成功能:

1.1 在__enter__方法里打开Fileinfo(filename),并且返回filename对应的内容。如果文件不存在等情况,需要捕获异常。

1.2 在__enter__方法里记录文件打开的当前日期和文件名。并且把记录的信息保持为log.txt。内容格式:"2014-4-5 xxx.txt"

1 importlogging,os2

3 classFileinfo(object):4

5 def __init__(self,filename):6 self.filename=filename7

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 exceptIOError:14 return 'error'

15 else:16 self.__exit__()17 returncontent18

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 importlogging,os,urllib2

3 classpage(object):4 globala5 def __init__(self,num):6 self.num=num7

8 defget_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 raiseException14 exceptIndexError:15 return u'\n超出范围'

16 exceptException:17 self.__exit__() #内部方法调用

18 return 'url 404 not found'

19 else:20 returnf.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()

3、

三:定义一个方法get_urlcontent(url)。返回url对应内容。

要求:

1自己定义一个异常类,捕获URL格式不正确的情况,并且用logging模块记录错误信息。

2 用内置的异常对象捕获url 404 not found的情况。并且print 'url is not found'

1 importlogging,os,urllib,re2

3 classpage(object):4 globala5 def __init__(self,num):6 self.num=num7

8 defget_page(self):9 '''

10 1、先判断URL是否合法:11 如果不合法,保存日志,并返回'url is wrong'12 如果合法,判断URL是否可以打开:13 如果不可以打开,抛出异常14 如果打开,返回页面数据15

16 '''

17 try:18 new_url=a[self.num]19

20 modle_url=re.compile('^(http|https)\:(\/\/|\\\\)\w+\.\w+\.(com|cn)')21 m1=modle_url.search(new_url)22

23 if m1==None:24 self.__exit__() #内部方法调用

25 return u'\n url不合法'

26 else:27 f=urllib.urlopen(new_url)28 if urllib.urlopen(new_url).code==404:29 raiseException30 exceptIndexError:31 return u'\n超出范围'

32 exceptException:33 return 'url 404 is not found'

34 else:35 returnf.read()36

37 def __exit__(self):38 logging.basicConfig(level=logging.ERROR)39 logger=logging.getLogger()40 logger.setLevel=(logging.DEBUG)41 hfile=logging.FileHandler(r"C:\Users\Administrator\Desktop\urllog.log")42 hfile.setLevel=(logging.DEBUG)43 formatter=logging.Formatter('[%(asctime)s]''-''%(levelname)s''-''%(message)s')44 hfile.setFormatter(formatter)45 logger.addHandler(hfile)46

47 logging.error(a[self.num])48

49 if __name__=='__main__':50 num=int(raw_input('please input a number:\n'))51 a=['https://wenda.so.com/q/1480716337726538','http:www.cnblogs.com/duyaya/','http://www.cn.com/d/']52 c=page(num)53 printc.get_page()54 #输入0,可正常打印URL信息

55 #输入1,打印 URL不合格

56 #输入2,打印 URL 404 is not find

57 #输入3,打印 超出范围

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值