Python学习笔记(七)——调试

本文介绍了Python中异常处理的基本方法,包括如何使用try-except语句捕获和处理异常,以及如何通过raise语句主动抛出异常。此外,还详细讲解了日志模块的使用,包括不同级别的日志输出、日志格式设置、日志禁用及日志文件的保存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

抛出异常

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

如果没有tryException 用来抛出异常,程序就会崩溃

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 Exception happend:'+ str(err))

这里写图片描述

try:
    pass
except Exception as e:
    raise
else:
    pass
finally:
    pass


try:
    pass
except Exception as e:
    raise e
else:
    pass

try:
    pass
except Exception as e:
    raise e
finally:
    pass

try:
    pass
except Exception as e:
    raise e

取得反向跟踪的字符串

#! python3
#errorExample.py
def spam():
    func()
def func():
    raise Exception('This is the error message')
spam()

“调用栈”,反向跟踪

===================== RESTART: D:/python/errorExample.py =====================
Traceback (most recent call last):
  File "D:/python/errorExample.py", line 5, in <module>
    spam()
  File "D:/python/errorExample.py", line 2, in spam
    func()
  File "D:/python/errorExample.py", line 4, in func
    raise Exception('This is the error message')
Exception: This is the error message

traceback 模块

>>> 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.')


116
The traceback info was written to errorInfo.txt.
#errorInfo.txt
Traceback (most recent call last):
  File "<pyshell#72>", line 2, in <module>
Exception: This is the error message.

断言

日志

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(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: D:\python\factorialLog.py =====================
 2018-02-07 16:54:56,376- DEBUG-  Start of program
 2018-02-07 16:54:56,527- DEBUG- Start of factorial(5%)
 2018-02-07 16:54:56,547- DEBUG-  i is0,total is0
 2018-02-07 16:54:56,565- DEBUG-  i is1,total is0
 2018-02-07 16:54:56,580- DEBUG-  i is2,total is0
 2018-02-07 16:54:56,593- DEBUG-  i is3,total is0
 2018-02-07 16:54:56,613- DEBUG-  i is4,total is0
 2018-02-07 16:54:56,632- DEBUG-  i is5,total is0
 2018-02-07 16:54:56,651- DEBUG- End of factorial(5%)
0
 2018-02-07 16:54:56,694- DEBUG- End of program

不要用print() 调试

日志级别

描述日志函数级别
DEBUGlogging.debug()最低级别。用于小细节。通常只有在诊断问题时,你才会关心这些消息
INFOlogging.info()用于记录程序中一般事件的信息,或确认一切工作正常
WARNINGlogging.warning()它不会阻止程序的工作,但将来可能会用于表示可能的问题
ERRORlogging.error()用于记录错误,它导致程序做某事失败
CRITICALlogging.critical()最高级别。用于表示致命的错误,它导致或将要导致程字完全停止工作
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s\n" "%(levelname)s- %(message)s')
>>> logging.debug (' Some debugging details.' )
 2018-02-07 17:27:36,672- DEBUG-  Some debugging details.
>>> logging.info('The logging module is working.' )
 2018-02-07 17:28:09,721- INFO- The logging module is working.
>>> logging.warning('An error message is about to be logged.' )
 2018-02-07 17:28:23,338- WARNING- An error message is about to be logged.
>>> logging.error('Anhas occurred.')
 2018-02-07 17:28:59,818- ERROR- Anhas occurred.
>>> logging.critical( 'The program is unable to recover! ')
 2018-02-07 17:29:38,894- CRITICAL- The program is unable to recover! 

禁用日志功能

logging.disable(logging.CRITICAL)

>>> import logging
>>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s\n" "%(levelname)s- %(message)s')
>>> logging.debug (' Some debugging details.' )
 2018-02-07 17:37:48,995- DEBUG-  Some debugging details.
>>> logging.disable(logging.CRITICAL)
>>> logging.info('The logging module is working.' )
>>> logging.warning('An error message is about to be logged.' )
>>> logging.error('Anhas occurred.')
>>> logging.critical( 'The program is unable to recover! ')

将日志记录到文件中

>>> import logging
>>> logging.basicConfig(filename='mylogging.txt',level=logging.DEBUG, format=' %(asctime)s\n" "%(levelname)s- %(message)s')

IDLE的调试器

Debug——>Debugger
调试窗口

Go

程序正常执行到终点,或者到达一个断点

Step

调试器执行下一行的代码,并更新窗口显示的局部变量和全局变量

Over

与Step类似,只是如果下一步的遇到一个函数调用,则全速执行函数后,停下

Out

调试器全速执行代码,知道将前的函数执行完毕

Quit

终止调试

调试一个数字相加的程序

print('First Num:')
First = input()
print('Second Num')
Second = input()
print('Third Num')
Third = input()
print('The sum is' + First + Second + Third)
================== RESTART: D:\python\buggyAddingProgram.py ==================
First Num:
20
Second Num
30
Third Num
40
The sum is203040
[DEBUG ON]

这里写图片描述

断点

代码鼠标右键,set Breakpoint

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值