调试

发布时间:2019-05-22 22:13:30编辑:auto阅读(1976)

    来源:python编程快速上手——Al Sweigart

     

    1 抛出异常

    抛出异常相当于是说:“停止运行这个函数中的代码,将程序执行转到 except 语句”。

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

    • raise 关键字
    • 对 Exception 函数的调用
    • 传递给 Exception 函数的字符串,包含有用的出错信息

    Ex:   

    1 try:
    2     raise Exception('This is the error message.')
    3 except Exception as err:
    4     print('An exception happened: ' + str(err))

    out: An exception happened: This is the error message.

     

    2 取得反向跟踪的字符串

    只要抛出的异常没有被处理,Python 就会显示反向跟踪。也可以调用 traceback.format_exc(),得到它的字符串形式。

    如果希望得到异常的反向跟踪的信息,同时希望except 语句优雅地处理该异常,这个函数就很有用。在调用之前需要先导入 traceback 模块。

    Ex:

     1 import traceback
     2 try:
     3     raise Exception('This is the error message.')
     4 except:
     5     errorfile = open('errorInfo.txt', 'w')
     6     errorfile.write(traceback.format_exc())
     7     errorfile.close()
     8     print('The traceback info was written to errorInfo.txt.')
     9 
    10 out: The traceback info was written to errorInfo.txt.
    11 
    12 errorInfo.txt:
    13 
    14 Traceback (most recent call last):
    15   File "d:\Code\Python\test.py", line 3, in <module>
    16     raise Exception('This is the error message.')
    17 Exception: This is the error message.

     

    3 断言

    “断言” 是一个心智正常的检查,确保代码没有做什么明显错误的事情。这些心智正常的检查由 assert 语句执行。如果检查失败,就会抛出异常。

    在代码中,assert 语句包含以下部分:

    • assert 关键字
    • 条件(即求值为 True 或 False 的表达式)
    • 逗号
    • 当条件为 False 时显示的字符串

    Ex:

     1 test = 'open'
     2 assert test == 'open', 'The test need to be "open"'  #条件为True, 语句正常执行
     3 test = 'close'
     4 assert test == 'open', 'The test need to be "open"'
     5 
     6 out:
     7 Traceback (most recent call last):
     8   File "d:\Code\Python\test.py", line 4, in <module>
     9     assert test == 'open', 'The test need to be "open"'
    10 AssertionError: The test need to be "open"

    禁用断言:

    如果已完成程序的编写和测试,不希望执行心智正常检测,从而减慢程序的速度,可以禁用断言。

    禁用方法:在python或python3之后和.py文件之前加上-O开关。这将运行程序的优化版本,跳过断言检查。

     

    4 日志

    简单使用

     1 import logging
     2 
     3 logging.debug('debug message')
     4 logging.info('info message')
     5 logging.warn('warn message')
     6 logging.error('error message')
     7 logging.critical('critical message') 
     8 
     9 out:  WARNING:root:warn message
    10       ERROR:root:error message
    11       CRITICAL:root:critical message
    12 
    13 #默认情况下,logging模块将日志打印到屏幕上(stdout)
    14 #日志级别为WARNING(即只有日志级别高于WARNING的日志信息才会输出)
    15 #日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET

    简单配置

     1 import logging
    2 logging.basicConfig: logging.basicConfig(level=logging.DEBUG, 3 format='%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s %(message)s', 4 datefmt='%a, %d %b %Y %H:%M:%S', 5 filename='myapp.log', 6 filemode='w') 7 ''' 8 logging.basicConfig函数各参数: 9 filename: 指定日志文件名 10 filemode: 和file函数意义相同,指定日志文件的打开模式,'w''a' 11 format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示: 12   %(levelno)s: 打印日志级别的数值 13   %(levelname)s: 打印日志级别名称 14   %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0] 15   %(filename)s: 打印当前执行程序名 16   %(funcName)s: 打印日志的当前函数 17   %(lineno)d: 打印日志的当前行号 18   %(asctime)s: 打印日志的时间 19   %(thread)d: 打印线程ID 20   %(threadName)s: 打印线程名称 21   %(process)d: 打印进程ID 22   %(message)s: 打印日志信息 23 datefmt: 指定时间格式,同time.strftime() 24 level: 设置日志级别,默认为logging.WARNING 25 stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略 26 '''

    几个重要的概念:

    •     Logger 记录器,暴露了应用程序代码能直接使用的接口。
    •     Handler 处理器,将(记录器产生的)日志记录发送至合适的目的地。
    •     Filter 过滤器,提供了更好的粒度控制,它可以决定输出哪些日志记录。
    •     Formatter 格式化器,指明了最终输出中日志记录的布局。

    禁用日志

    在程序中添加logging.disable(logging.CRITICAL)

     

    5 IDLE 的调试器

    要启用IDLE 的调试器,就在交互式环境窗口点击 Debug > Debugger。

     


    2019-03-2812:46:59

关键字