11.调试
1)抛出异常
try …… except 捕捉异常
raise 抛出异常。
测试程序:test_1101.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 exception happened: ' + str(err))
2)取得回溯字符串
抛出的异常未处理,则会显示回溯信息,最终定位到出错的语句行。
traceback模块
traceback.format_exc() 得到回溯字符串
测试程序:test_1102.py
def spam():
bacon()
def bacon():
raise Exception('This is the error message.')
spam()
3)断言
健全性检查
assert condition
交通灯模拟 test_1103.py
market_2nd = {'ns':'green','ew':'red'}
mission_16th = {'ns':'red','ew':'green'}
def switchLights(stoplight):
for key in stoplight.keys():
if stoplight[key] == 'green':
stoplight[key] = 'yellow'
elif stoplight[key] == 'yellow':
stoplight[key] = 'red'
elif stoplight[key] == 'red':
stoplight[key] = 'green'
assert 'red' in stoplight.values(),'Neither light is red!' + str(stoplight)
switchLights(market_2nd)
4)日志
logging模块
logging.basicConfig()
logging.debug()
logging模块可以在显示和隐藏日志间进行切换。
测试程序:test_1104.py
import logging
logging.basicConfig(filename='myProgramLog.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')
日志级别:
DEBUG:logging.debug()
INFO:logging.info()
WARNING:logging.warning()
ERROR:logging.error()
CRITICAL:logging.critical()
CRITICAL>ERROR>WARNING>INFO>DEBUG
禁用日志
logging.disable()
禁用CRITICAL最高级别,所有日志均不显示
5)调试器
vscode调试模式实现。