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

《Python 编程快速上手 — 让繁琐工作自动化》读书笔记之【第10章 调试】

2018-03-09 12:00 936 查看

1.  抛出异常

抛出异常使用raise语句,raise语句的结构如下:
• raise 关键字;
• 对 Exception 函数的调用;
• 传递给 Exception 函数的字符串,包含有用的出错信息。
然后用try…except…语句去接受这个异常,如果没有 try 和 except 语句覆盖抛出异常的 raise 语句,该程序就会崩溃,并显示异常的出错信息。示例:#打印矩形
def boxPrint(symbol, width, height):
if len(symbol) != 1:#只传一个字符
raise Exception('Symbol must be a single character string.')
if width<= 2:
raise Exception('Width must be greater than 2.')
if height<= 2:
raise Exception('Height must be greater than 2.')
#打印矩形第一行
print(symbol* width)

#打印矩形高度
for i in range(height- 2):
print(symbol+ (' ' * (width - 2)) + symbol)

#打印矩形最后一行
print(symbol* width)
for sym, w, h in (('*',4,4),('0',20,5),('x',1,3),('ZZ',3,3)):
try:
boxPrint(sym, w, h)
except Exceptionas err:
print('An exception happened: ' + str(err))

2.  取得反向跟踪的字符串

如果python遇到错误,就会生成一些错误信息,称为“反向跟踪”。反向跟踪包含了出错消息、导致该错误的代码行号,以及导致该错误的函数调用的序列。这个序列称为“调用栈”。示例: def spam():
bacon()
def bacon():
raise Exception('Thisis the error message.')
spam()运行代码的到的结果:Traceback (mostrecent call last):
File "D:/Tool/PycharmProjects/chapter10/errorExample.py", line 7, in <module>
spam()
File "D:/Tool/PycharmProjects/chapter10/errorExample.py", line 2, in spam
bacon()
File "D:/Tool/PycharmProjects/chapter10/errorExample.py", line 4, in bacon
raise Exception('Thisis the error message.')
Exception: This is the error message.只要抛出的异常没有被处理,Python 就会显示反向跟踪。但你也可以调用traceback.format_exc(),得到它的字符串形式。示例:import traceback
try:
raise Exception('This is the error message.')
except:
errorFile = open('errorInfo.txt', 'w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written toerrorInfo.txt.')

3.  断言(assert)

assert语句检查代码有没有明显的错误,如果检查失败,就会抛出异常。assert语句结构如下:
• assert 关键字;
• 条件(即求值为 True 或False 的表达式)
• 逗号
• 当条件为 False 时显示的字符串
示例:podBayDoorStatus = 'open'
assert podBayDoorStatus == 'open', "The pod bay doors need to be'open'."
podBayDoorStatus = 'I\'m sorry, Dave. I\'m afraid I can\'t do that.'
assert podBayDoorStatus == 'open',"The pod bay doors need to be'open'."在运行 Python 时传入-O 选项,可以禁用断言。

4.  日志

1)  使用日志模块

要启用 logging 模块,请将下面的代码复制到程序顶部(但在 Python 的#!行之下):import logging

logging.basicConfig(level=logging.DEBUG,format=' %(asctime)s - %(levelname)s

- %(message)s')当 Python 记录一个事件的日志时,它会创建一个 LogRecord 对象,保存关于该事件的信息。logging 模块的函数让你指定想看到的这个 LogRecord 对象的细节,以及希望的细节展示方式。示例:import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')
logging.debug('Start of program')

def factorial(n):
logging.debug('Start of factorial (%d)' % n)
total = 1
for i in range(n +1):
total *= i
logging.debug('i is ' + str(i) + ', total is ' + str(total))
logging.debug('End of factorial (%d)' % n)
return total

print(factorial(5))
logging.debug('End of program')

2)  不要用 print()调试

日志是给程序员看的,而print()则是给用户看的。日志调试不要用print()。只要加入一次 logging.disable(logging.CRITICAL)调用,就可以禁止日志。

3)  日志级别


4)  禁用日志
使用logging.disable()实现日志都禁用以及控制显示的级别。示例:>>> import logging

>>> logging.basicConfig(level =logging.INFO, format = '%(asctime)s - %(levelname)s - %(message)s')

>>> logging.critical('Criticalerror!Critical error!')

2018-03-09 11:46:36,403 - CRITICAL -Critical error!Critical error!

>>>logging.disable(logging.CRITICAL)

>>> logging.critical('Criticalerror!Critical error!')

>>> logging.error('Error!Error!')

5)  将日志记录到文件

logging.basicConfig() 函数接受 filename 关键字参数,作为写入日子的路径。示例:

import logging

logging.basicConfig(filename='myProgramLog.txt',level=logging.DEBUG, format='

%(asctime)s - %(levelname)s - %(message)s')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python debug 调试
相关文章推荐