python进阶宝典8-调试方法

## 几种调试方法 ##
# 1.抛出异常
# 2.取得反向跟踪信息
# 3.断言
# 4.使用日志
# 5.IDE调试器-断点及逐行跟踪等

## 抛出异常  raise Exception 与 try except 的配合使用
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)
        i = i + 1
    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))

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

## 断言 assert
#     断言针对的是程序员的错误,而不是用户的错误。对于业务逻辑层面的错误处理,要抛出异常,而不是用断言语句来检测
market_2nd = {'ns':'green','ew':'red'}          # Market街和第2街的路口,南北向和东西向的交通灯分别为绿色和红色
misson_16th = {'ns':'red','ew':'green'}
def switchLights(stoplight):
    for key in stoplight.keys():
        if stoplight[key] == 'green':
            stoplight[key] = 'yellow'
        if stoplight[key] == 'yellow':
            stoplight[key] = 'red'
        if stoplight[key] == 'red':
            stoplight[key] = 'green'
    assert 'red' in stoplight.values(), 'Neither light is red! '+str(stoplight)    # 都不是红灯通过断言报错
switchLights(market_2nd)
# assert 用来调试程序,调试通过后,可以跳过断言来执行
# 如上面这段代码, python assertlight.py    执行到都不是红灯时,会报错,检测出了会撞车的逻辑异常
#                python -O assertlight.py  取消执行断言代码,不会报错。在排除了程序中的逻辑异常后取消执行断言


## 日志 logging模块
# logging.basicConfig(level=logging.DEBUG)   # 定义开始显示的日志级别 DEBUG|INFO|WARNING|ERROR|CRITICAL
# logging.basicConfig(filename='aaa.txt')    # 定义日志输出到文件 
# logging.disable(logging.CRITICAL)          # 定义禁止日志消息的级别
import logging
logging.basicConfig(level=logging.DEBUG,format=' %(asctime)s - %(levelname)s - %(message)s')
#logging.basicConfig(level=logging.DEBUG,filename='loggingout.txt',format=' %(asctime)s - %(levelname)s - %(message)s')
logging.disable(logging.CRITICAL)
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')




            

你可能感兴趣的:(python)