python程序的调试,用书中的话来说就是“非常优雅”。
try,except和assert的调试方法是我第一次接触,使用起来有些不太习惯,但是看起来很好用的样子。
**
try,except,raise
**
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), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
boxPrint(sym, w, h)
except Exception as err:
print('An exception happened: ' + str(err))
**
断言
**
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.' '
没有试验成功,明天继续。
**
记录日志
**
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of program') #打印日志信息
logging.disable(logging.CRITICAL)
**
将日志记录到文件
**
import logging
logging.basicConfig(filename='myProgramLog.txt',level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
**
利用调试器进行调试
**
IDLE→Debug→Debugger
**
设置断点
**
右键代码→Set Breakpoint