异常习题:

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

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

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

class Fileinfo(object):
import time
newTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) def __init__(self, filename):
self.filename = filename def __enter__(self):
try:
fn = open(self.filename, 'r')
content = fn.read()
except Exception as err:
print(str(err) + "The file doesn't exist.")
else:
fn.close()
return content def __exit__(self, type, value, traceback): with open('log.txt', 'a+')as log_fn:
# 调用类成员,加上类名,eg,Fileinfo.newTime
log_fn.write('%s %s\n' % (Fileinfo.newTime, self.filename)) with Fileinfo('comment1.txt') as fn: # __enter__中的返回值给予给fn
print(fn)

二:用异常方法,处理下面需求:

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

import logging
import os
import time
from urllib import request info = ['http://www.baidu.com', 'http:///xxx.com', 'http://xxxx.cm'] # 第一步 创建logger对象
logger = logging.getLogger()
logger.setLevel(logging.INFO) # 设置log等级
# 创建handler,用于写入文件
rq = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
log_name = 'log.txt'
fh = logging.FileHandler(log_name, mode='a')
fh.setLevel(logging.DEBUG) # 输出到file的log等级的开关
# 第三步,定义handler的输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
# 第四步,将logger添加到handler里面
logger.addHandler(fh) def get_page(listindex):
try:
openurl = request.urlopen(info[listindex])
content = openurl.read()
return content
except IOError:
logger.error('%s %s\n' %(info[listindex],'404 not found'))
print('404')
except IndexError:
print('数组下标越界') get_page(1)

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

要求:

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

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

 import logging
import os
import time
from urllib import request # 第一步 创建logger对象
logger = logging.getLogger()
logger.setLevel(logging.INFO) # 设置log等级
# 创建handler,用于写入文件
rq = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
log_name = 'log.txt'
fh = logging.FileHandler(log_name, mode='a')
fh.setLevel(logging.DEBUG) # 输出到file的log等级的开关
# 第三步,定义handler的输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
# 第四步,将logger添加到handler里面
logger.addHandler(fh) def get_urlcontent(url):
try:
openurl = request.urlopen(url)
content = openurl.read()
except IOError:
logger.error('%s %s\n' %(url,'404 not found'))
print('404')
else:
return content print(get_urlcontent('http://asdwww.baidu.com'))

python练习:异常的更多相关文章

  1. Python标准异常topic

    Python标准异常topic AssertionError                            断言语句 (assert)                              ...

  2. Python 6 —— 异常

    Python 6 —— 异常 异常分类 AttributeError:调用不存在的方法 EOFError:遇到文件末尾引发异常 ImportError:导入模块引发异常 IndexError:列表越界 ...

  3. python 的异常及其处理

    Python 异常处理 python提供了两个非常重要的功能来处理python程序在运行中出现的异常和错误.你可以使用该功能来调试python程序. 异常处理: 本站Python教程会具体介绍. 断言 ...

  4. Python中异常(Exception)的总结

    Python中的异常处理 异常处理的语句结构 try: <statements> #运行try语句块,并试图捕获异常 except <name1>: <statement ...

  5. Python标准异常总结

    Python标准异常总结 AssertionError 断言语句(assert)失败 AttributeError 尝试访问未知的对象属性  EOFError 用户输入文件末尾标志EOF(Ctrl+d ...

  6. 19 Python标准异常总结 (转)

    Python标准异常总结 AssertionError 断言语句(assert)失败 AttributeError 尝试访问未知的对象属性 EOFError 用户输入文件末尾标志EOF(Ctrl+d) ...

  7. Python标准异常和异常处理详解

    python提供了两个非常重要的功能来处理python程序在运行中出现的异常和错误.你可以使用该功能来调试python程序. 1.异常处理: 本站Python教程会具体介绍. 2.断言(Asserti ...

  8. python基础-异常(exception)处理

    python基础-异常(exception)处理 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 程序中难免出现错误,而错误分成两种,即语法错误和逻辑错误.语法错误根本过不了pyth ...

  9. python——标准异常总结

    请参考此网站: Python 标准异常总结 https://fishc.com.cn/forum.php?mod=viewthread&tid=45814&extra=page%3D1 ...

  10. python之-- 异常

    异常处理: 语法:try: codeexcept (KeyError..可以写多个) as e: error为抓取的多个错误提示,e为错误信息 print(e) # 打印错误信息except (Ind ...

随机推荐

  1. StringBuffer & StringBuilder的区别

    StringBuffer是线程安全的,内部有锁.所以比StringBuilder慢一点. 在单线程生成字符串的情况下,优先使用StringBuilder. 这就是为啥有时候IntelliJ Idea会 ...

  2. ISO/IEC 9899:2011 条款5——5.1 概念模型

    5.1 概念模型 5.1.1 翻译环境 5.1.2 执行环境

  3. 测试一下windowsLiveWriter

    一个是看看这个东西能不能发布出博客,还有一个就是准备开始写博客了,所以随便写个作为开始吧,我不想多说什么目标啊,什么的,所以就这一句简单的一句话就够了.

  4. properties配置文件参数获取

    package com.opslab.util; import org.apache.log4j.Logger; import java.io.File;import java.io.IOExcept ...

  5. ABAP函数篇1 日期函数

    1. 日期格式字段检查 data:l_date type ekko-bedat. l_date = '20080901'. CALL FUNCTION 'DATE_CHECK_PLAUSIBILITY ...

  6. Golang中的Map(集合)

    Map 是一种无序的键值对的集合.Map 最重要的一点是通过 key 来快速检索数据,key 类似于索引,指向数据的值. Map 是一种集合,所以我们可以像迭代数组和切片那样迭代它.不过,Map 是无 ...

  7. http post 自动变成了options 怎么设置

  8. Nodejs Client for FastDFS

    FastDFS 是分布式文件存储系统.这个项目是FastDFS的NodeJS客户端,用来与FastDFS Server进行交互,进行文件的相关操作.我测试过的server版本是4.0.6. githu ...

  9. Selenium(二十):expected_conditions判断页面元素

    1. 判断元素(expected_conditons) 作为一个刚刚转到python开发的小朋友,在开发前只将前辈们封装的方法看了一遍,学了一边selenium基础.看到封装的方法有什么判断元素是否存 ...

  10. MangoDB

    <MongoDB权威指南> 一.简介 MongoDB是一款强大.灵活.且易于扩展的通用型数据库 1.易用性 MongoDB是一个面向文档(document-oriented)的数据库,而不 ...