Python错误与调试

Python错误与调试

错误

try-catch语法:

try:
    pass
except SomeError as e:
    pass
except SomeError as e:
    pass
finally:
    pass

logging模块

日志级别:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET

import logging

logging.debug('debug')
logging.info('info')
logging.warning('warning')

# 默认打印到标准输出,日志级别WARNING

logging.basicConfig

通过该函数配置日志的输出格式及方式,日志可同时输出到多个位置

import logging

logging.basicConfig(level = logging.ERROR,
    format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    datefmt = '%a, %d %b %Y %H:%M:%S',
    filename = 'amsimple.log',
    filemode = 'a')

console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

格式说明:

%(levelno)s
%(levelname)s
%(pathname)s
%(filename)s
%(funcName)s
%(lineno)d
%(asctime)s
%(thread)d
%(threadName)s
%(process)d
%(message)s

logging.config

可通过配置文件定义logging行为,然后在代码中加载配置以及获取日志。

import logging
import logging.config

logging.config.fileConfig('logger.conf')
logger = logging.getLogger('A') # 获取配置文件中对应的logger A

pdb调试

通过python -m pdb xxx.py可进入pdb调试状态,或者在代码中import pdb,通过pdb.set_trace()触发调试。

常用命令:

break 或 b
continue 或 c
list 或 l
step 或 s
return 或 r
exit 或 q
next 或 n
pp
help

博客原文

猜你喜欢

转载自blog.csdn.net/shasharoman/article/details/79651890