Python学习8-10.1-10.7 调试


本文为学习python编程时所记录的笔记,仅供学习交流使用。

10.1 抛出异常

>>> raise Exception('This is the error message.')
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    raise Exception('This is the error message.')
Exception: This is the error message.

boxPrint.py

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 Exception as err:
        print('An excepiton happened:'+str(err))
        
    

10.2 取得反向跟踪的字符串

def spam():
    bacon()
def bacon():
    raise Exception('This is the error message.')

spam()
>>> 
 RESTART: C:/Users/VECTOR/AppData/Local/Programs/Python/Python37/errorExample.py 
Traceback (most recent call last):
  File "C:/Users/VECTOR/AppData/Local/Programs/Python/Python37/errorExample.py", line 6, in <module>
    spam()
  File "C:/Users/VECTOR/AppData/Local/Programs/Python/Python37/errorExample.py", line 2, in spam
    bacon()
  File "C:/Users/VECTOR/AppData/Local/Programs/Python/Python37/errorExample.py", line 4, in bacon
    raise Exception('This is the error message.')
Exception: This is the error message.
>>> 

>>> 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 to errorInfo.txt')

	
115
The traceback info was written to errorInfo.txt

10.3 断言

>>> podBayDoorStatus='open'
>>> assert podBayDoorStatus=='open','The pod bay doors need to be "open".'
>>> podBayDoorStatus='I\'m sorry,Dave.I\'m afraid I cant'
>>> assert podBayDoorStatus=='open','The pod bay doors need to be "open".'
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    assert podBayDoorStatus=='open','The pod bay doors need to be "open".'
AssertionError: The pod bay doors need to be "open".

10.3.1 在交通灯模拟中使用断言

10.4 日志

10.4.1 使用日志模块

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(%s%%)'%(n))
    total=1
    for i in range(1,n+1):
        total*=i
        logging.debug('i is '+str(i)+', total is '+str(total))
    logging.debug('End of factorial(%s%%)'%(n))
    return total

print(factorial(5))
logging.debug('End of program')
>>> 
 RESTART: C:/Users/VECTOR/AppData/Local/Programs/Python/Python37/factorialLog.py 
2020-02-18 13:33:29,550-DEBUG-Start of program
2020-02-18 13:33:29,571-DEBUG-Start of factorial(5%)
2020-02-18 13:33:29,576-DEBUG-i is 1, total is 1
2020-02-18 13:33:29,579-DEBUG-i is 2, total is 2
2020-02-18 13:33:29,581-DEBUG-i is 3, total is 6
2020-02-18 13:33:29,595-DEBUG-i is 4, total is 24
2020-02-18 13:33:29,609-DEBUG-i is 5, total is 120
2020-02-18 13:33:29,620-DEBUG-End of factorial(5%)
120
2020-02-18 13:33:29,646-DEBUG-End of program

10.4.2 不要用print()调试

logging.disable(logging.CRITICAL)

10.4.3 日志级别

级别日志函数描述
DEBUGlogging.debug()最低级别,用于小细节,通常只有在诊断问题时,你才关心这些消息
INFOlogging.info()用于记录程序中一般事件的信息,或确认一切工作正常
WARNINGlogging.warning()用于表示可能的问题,它不会阻止程序的工作,但将来可能会
ERRORlogging.error()用于记录错误,它将导致程序做某事失败
CRITICALlogging.critical()最高级别,用于表示致命的错误,它导致或将要导致程序完全停止工作

10.4.4 禁用日志

10.4.5 将日志记录到文件

import logging
#logging.basicConfig(level=logging.DEBUG,format='%(asctime)s-%(levelname)s-%(message)s')
logging.basicConfig(filename='factoriallLog.txt',level=logging.DEBUG,format='%(asctime)s-%(levelname)s-%(message)s')
logging.debug('Start of program')

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

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

10.5 IDLE的调试器

GO 程序正常执行至终止,或到达一个断点
Step 将导致调试器执行下一行代码,然后再次暂停
Over 执行下一行代码,与step类似,但是跨过函数
Out 全速执行代码行,直至它从当前函数返回
Quit 完全停止调试

print('Enter the first number to add:')
first=input()
print('Enter the sencond number to add:')
second=input()
print('Enter the third number to add:')
third=input()
print('The sum is '+first+second+third)

10.5.7 断点

断点可以设置在特定代码行上,当程序执行到达该行时,它迫使调试器暂停。

内容来源

[1] [美]斯维加特(Al Sweigart).Python编程快速上手——让繁琐工作自动化[M]. 王海鹏译.北京:人民邮电出版社,2016.7.p174-188

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值