さて、ここまででフロー、文字列、型、ファイル等を扱い、基礎プログラミングとしては一段落できた。
今日からは後半戦にはいり、開発をするうえで実践で必要になる技術を学んでいく。
まずはデバッグからである。デバッグ方法の一つ目としては本来発生するべきでない現象が起きた時には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), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
boxPrint(sym, w, h)
except Exception as err:
print('An exception happened: ' + str(err))
次にtracebackをファイルに書き込む処理
try:
raise Exception('This is error')
except:
errorfile = open('.\\errorInfo.txt', 'w')
errorfile.write(traceback.format_exc())
errorfile.close()
ログを取得する際にはloggingパッケージを利用する。
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('start')
2018-02-26 10:56:23,764 - DEBUG - start
