python 调试之assert and logging

断言 assert

assert后面跟的表达式应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错。

如果断言失败,会抛出AssertionError

def foo(s):
n = int(s)
assert n != 0, 'n is zero'
return 10/n

foo('0')

输入结果:

Traceback (most recent call last):
File "。。。/errorPrac.py", line 35, in <module>
foo('0')
File "。。。errorPrac.py", line 32, in foo
assert n != 0, 'n is zero'
AssertionError: n is zero

logging

logging不但能抛出错误,还可以输出到文档

输出到文档的内容需要在import logging的时候定义,允许定义输出信息的级别:debug, info, warning, error,

当制定level = INFO后,logging.debug就不起作用了。同样的,如果指定 level = ERROR, 前面的debug,info和warning都不起作用了

logging还有一个好处,通过简单的配置,一条语句可以同时输出到不同的地方,比如console和文件

如:

import logging
logging.basicConfig(level=logging.INFO)
def test(s):
n = int(s)
logging.info('n = %d' % n)
print(10 / n)

test('0')

输出:

NFO:root:n = 0
Traceback (most recent call last):
File errorPrac.py, line 44, in <module>
test('0')
File errorPrac.py, line 42, in test
print(10 / n)
ZeroDivisionError: division by zero




 

posted on 2018-03-08 16:36  永恒自由森林  阅读(968)  评论(0编辑  收藏  举报

导航