老王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 import logging,os
 2 
 3 class Fileinfo(object):
 4     
 5     def __init__(self,filename):
 6         self.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()

 3、

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

要求:

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

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

 1 import logging,os,urllib,re
 2 
 3 class page(object):
 4     global a
 5     def __init__(self,num):
 6         self.num=num
 7     
 8     def get_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                     raise Exception
30         except IndexError:
31             return u'\n超出范围'
32         except Exception:
33             return 'url 404 is not found'
34         else:
35             return f.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     print c.get_page()
54 #输入0,可正常打印URL信息
55 #输入1,打印 URL不合格
56 #输入2,打印 URL 404 is not find
57 #输入3,打印 超出范围

 

posted @ 2018-01-14 21:18  秋刀鱼Q  阅读(346)  评论(0编辑  收藏  举报