Python新手学习(九):调试

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调试模式实现。
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值