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

博客原文

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章