import inspect
import contextlib
import sys
@contextlib.contextmanager ※「@」でコンテキストマネージャを定義する
def myContextLib(): ※ジェネレータと同じ要領
try:
print('enter...') ※前処理を担当するブロック
yield ※yield 以降が後処理を担当する
except: ※例外処理は except に記述する
ex, ms,
exc_tb = sys.exc_info() ※sys.exc_info() メソッドでトレースバックオブジェクトを取得できる
print('error...')
exc_tb =
inspect.getinnerframes(
exc_tb ) ※前述の処理と同じ
for
frame_object,filename,lineno,function,code_context,index in
exc_tb:
print( '------------' )
print(
frame_object)
print(
filename)
print(
lineno)
print(
function)
print(
code_context)
print(
index)
print( '------------' )
finally:
print('exit...')
with myContextLib():
myList = [ 1, 2, 3 ]
showPrint(myList) ※前述の関数を利用する
【実行結果】
enter... ※前処理
error... ※例外発生
------------
/home/guest/python15h/chapter01/myContext.py
39
myContextLib
[' yield\n']
0
------------
------------
/home/guest/python15h/chapter01/myContext.py
58
[' showPrint(myList)\n']
0
------------
------------
/home/guest/python15h/chapter01/myContext.py
6
showPrint
[' print(l[3])\n']
0
------------
exit... ※後処理