码迷,mamicode.com
首页 > 编程语言 > 详细

python自动化之调试

时间:2017-07-26 23:37:58      阅读:437      评论:0      收藏:0      [点我收藏+]

标签:config   rac   跟踪   做什么   cto   factorial   step   快速   定义   

#####调试

#####查看日志与断言

‘‘‘

抛出异常使用raise语句.在代码中,raise语句包含以下部分:

(1)raise关键字;

(2)对Exception函数的调用;

(3)传递给Exception函数的字符串,包含有用的出错信息

‘‘‘

###########################################抛出异常####################################

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

 

#######################################取得反向跟踪的字符串####################################

‘‘‘

反向跟踪包含了出错信息、导致该错误的代码行号,以及导致该

错误的函数调用的序列.这个序列称为“调用栈”

‘‘‘

‘‘‘

调用traceback.format_exc(),得到抛出异常的字符串形式.

可以将反向跟踪信息写入一个日志文件,并让程序继续运行

‘‘‘     

 

import traceback

try:

         raise Exception(‘This is the error message.‘)

except:

         errorFile=open(‘errorInfo.txt‘,‘w‘)

         errorFile.write(traceback.former_exc())

         errorFile.close()

         print(‘The traceback info was written to errorInfo.txt.‘)

#######################################断言####################################

‘‘‘

"断言"是一个心智正常的检查,确保代码没有做什么明显错误的事.

这些心智正常的检查由assert语句执行.如果检查失败,就会抛出异常

assert语句包含以下部分:

(1)assert关键字;

(2)条件(即求值为);

(3)逗号;

(4)当条件为False时显示的字符串

‘‘‘

podBayDoorStatus=‘open‘

assert podBayDoorStatus==‘open‘,‘The pod bay doors need to be "open".‘

podBayDoorStatus=‘I \‘m sorry,Dave.I \‘m afraid I can\‘t do that.‘

assert podBayDoorStatus==‘open‘,‘The pod bay doors need to be "open".‘

 

#######################################禁用断言#######################################

‘‘‘

在运行Python时传入-O选项,可以禁用断言

‘‘‘

#######################################日志###########################################

‘‘‘

Python的logging模块使得你很容易创建自定义的消息记录.

这些日志消息将描述程序执行何时到达日志函数调用,

并列出你指定的任何变量当时的值.

另一方面,缺失日志信息表明有一部分代码被跳过,从未执行

‘‘‘

#######################################使用日志模块###################################

‘‘‘

要启用logging模块,在程序运行时将日志信息显示在屏幕上,

请将下面的代码复制到程序顶部(但在Python的#!行之下)

‘‘‘

import logging

logging.basicConfig(level=logging.DEBUG,format=‘ %(asctime)s-%(levelname)s-%(message)s‘)

‘‘‘

当Python记录一个事件的日志时,它会创建一个LogRecord对象,保存关于该事件的信息.

logging模块的函数让你指定想看到的这个LogRecord对象的细节,以及希望的细节展示

方式.

‘‘‘

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

 

print(factorial(5))

logging.debug(‘End of program‘)

‘‘‘

logging.debug()调用不仅打印出传递给它的字符串,而且包含一个时间戳和单词DEBUG

‘‘‘

#######################################不要用print()调试###################################

‘‘‘

1、每次清楚print()调用,可能删除了不是用来产生日志消息的

2、日志消息好处:可以随心所欲地在程序中想加多少就加多少,稍后

   只要加入一次logging.disable(logging.CRITICAL)调用,就可以禁止日志

‘‘‘

#######################################日志级别###################################

‘‘‘

Python中的日志级别(从最不重要到最重要)

级别                   日志函数                            描述

DEBUG             logging.debug()                 最低级别.用于小细节,通常只有在诊断问题时,才会关心这些消息

INFO                 logging.info()             用于记录程序中一般事件的消息,或确认一切工作正常

WARNING       logging.warning()   用于表示可能的问题,它不会阻止程序的工作,但将来可能会

ERROR             logging.error()         用来记录错误,它导致程序做某事失败

CRITICAL         logging.critical()       最高级别.用来表示致命的错误,它导致或将要导致程序完全停止工作

‘‘‘

‘‘‘

日志级别的好处是:可以改变想看到的日志消息的优先级

向basicConfig()函数传入logging.DEBUG,将显示所有日志级别的消息

传入logging.error,将只显示ERROR和CRITICAL消息,跳过DEBUG、INFO和WARNING消息

‘‘‘

#######################################禁用日志###################################

‘‘‘

logging.disable()函数禁用日志信息,只要向logging.disable()传入一个日志级别

它就会禁止该级别和更低级别的所有日志消息.如果想要禁用所有日志,只要在程序中

添加logging.disable(logging.CRITICAL)

‘‘‘

import logging

logging.basicConfig(level=logging.INFO,format=‘%(asctime)s-%(levelname)s-%(message)s‘)

logging.critical(‘Critical error!Critical error!‘)

logging.disable(logging.CRITICAL)

logging.critical(‘Critical error!Critical error!‘)

logging.error(‘Error!Error!‘)

 

##################################将日志记录到文件###################################

import logging

logging.basicConfig(filename=‘myProgramLog.txt‘,level=logging.DEBUG,format=‘%(asctime)s-%(levelname)s-%(message)s‘)

##################################调试###################################

‘‘‘

GO、Step、Over、Out、Quit:

Step按钮让调试器进入函数调用

Over按钮将快速执行函数调用,不会单步进入其中

Out按钮将快速执行余下的代码,直到走出当前所处的函数

Go:调试器将在程序末尾或断点处停止

‘‘‘

‘‘‘

写assert语句,如果变量spam是一个小于10的整数,就触发AssertionError

1、assert(spam>=10,‘The spam variable is less than 10.‘)

写assert语句,如果eggs和bacon包含的字符串相同,而且不论大小写,就触发AssertionError

2、assert(eggs.lower()!=bacon.lower(),‘The eggs and bacon variables are the same!‘)

写assert语句,总是触发AssertionError

3、assert(False,‘This assertion always triggers.‘)

‘‘‘

python自动化之调试

标签:config   rac   跟踪   做什么   cto   factorial   step   快速   定义   

原文地址:http://www.cnblogs.com/dudumiaomiao/p/7241986.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!