您的位置:首页 > 编程语言 > Python开发

[Python进阶-6]错误异常处理,断言assert,日志logging,单元测试,文档测试

2015-10-06 11:38 1091 查看
(1)try……except……else……finally处理错误异常。

def xxx(x):
try:
n=10/x
print n
except ZeroDivisionError,err:
print err
except TypeError,err:
print err
else:
print 'success'
finally:
print 'finally'
xxx(1)
#10
#success
#finally
xxx(0)
#integer division or modulo by zero
#finally
xxx('s')
#unsupported operand type(s) for /: 'int' and 'str'
#finally


(2)可以定义自己的错误类(继承python自带的错误类),利用raise抛出异常。

class myError(StandardError):
pass

def xxx(x):
try:
n=10/x
print n
except ZeroDivisionError:
raise myError('hello,error')

xxx(0)
#Traceback (most recent call last):
# File "test.py", line 11, in <module>
#    xxx(0)
#  File "test.py", line 9, in xxx
#    raise myError('hello,error')
#__main__.myError: hello,error


(3)用print打印信息来调试错误,或者用断言assert。断言的好处就是可以用-O(大写的O)选项忽略错误信息。

def test(x):
print 'before'
assert x!=0,'the value of x is 0'
print 'after'

test(0)


用python test.py执行时,结果:

before
Traceback (most recent call last):
File "test.py", line 6, in <module>
test(0)
File "test.py", line 3, in test
assert x!=0,'the value of x is 0'
AssertionError: the value of x is 0


用python -O test.py执行时,结果:

before
after


(4)还有种调试就是logging,需要设置logging纪录级别,默认好像时warning。一共有debug,info,warn,error和crtical5个等级。比如下面,我们设置了info等级,那么低于这个等级的debug信息就无法纪录了。

import os
import logging

logging.basicConfig(filename=os.path.join(os.getcwd(),'log.txt'),level=logging.INFO)
logging.debug('DEBUG HERE')
logging.info('INFO HERE')
logging.warn('WARN HERE')
logging.error('ERROR HERE')
logging.critical('CRITICAL HERE')


打开同目录下的log.txt文件,结果:

INFO:root:INFO HERE
WARNING:root:WARN HERE
ERROR:root:ERROR HERE
CRITICAL:root:CRITICAL HERE


再进一步,一般都会设置自己纪录日志的格式,参考

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s:%(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename = os.path.join(FILE,'log.txt'),
filemode='w')
logging.info('msg')
logging.debug('msg2')


结果一般如下:

Sun, 22 Sep 2013 15:23:13:log1.py[line:41] INFO msg
Sun, 22 Sep 2013 15:23:13:log1.py[line:42] DEBUG msg2


(5)pdb和pdb_settrace()类似于Xcode的断点的感觉。当然用PyCharm这类IDE可以方便的设置断点。

(6)单元测试unittest。单元测试相当于一组测试的集合。这样不管程序如何被修改,修改后跑一下这个测试即可,而不需要一个个的测试。单位测试需要写一个脚本,详见廖雪峰的网站

(7)还有doctest文档测试,当文档编写要求比较严格,按照输入输出匹配。doctest的好处就是即可以当作指导文档,也可以用作测试。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息