Pygments
を使ってスタックトレースをちょっと美しくします。
sample_code.py
def funcA():
funcB()
def funcB():
funcC()
def fucnC():
1/0 # error!
funcA()
↓生だとこんな感じ
Traceback (most recent call last):
File "test.py", line 10, in <module>
funcA()
File "test.py", line 2, in funcA
funcB()
File "test.py", line 5, in funcB
funcC()
NameError: name 'funcC' is not defined
↓これぐらい綺麗にしたい
Traceback (most recent call last):
File "test.py", line 10, in <module>
funcA()
File "test.py", line 2, in funcA
funcB()
File "test.py", line 5, in funcB
funcC()
NameError: name 'funcC' is not defined
1. Pygmentsのインストール
pip
でもeasy_install
でもport
でも。
pip install Pygments
2. Pythonコードの最初に以下を追加
sys.excepthook
を利用します。
coloring.py
import sys
def myexcepthook(type, value, tb):
import traceback
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
tbtext = ''.join(traceback.format_exception(type, value, tb))
lexer = get_lexer_by_name("pytb", stripall=True)
formatter = TerminalFormatter()
sys.stderr.write(highlight(tbtext, lexer, formatter))
sys.excepthook = myexcepthook
参考: Coloring exceptions from Python on a terminal
とりあえずこれで出力されたスタックトレースの文字列や数値が色付けされます。
(発展) 3. Pythonコード実行時に自動で上記のコードを実行する
全てのコードに上を追加するのは面倒なので、勝手に実行してくれるようにします。
(意味不明なバグに繋がりかねないので、何をしているか理解してから試すのをおすすめします。)
usercustomize
を利用します。
参考: 16.1.4. カスタマイズ用モジュール
python -c "import site; print(site.getusersitepackages())"
で出力されるディレクトリにusercustomize.py
を作成して、上述のコードcoloring.py
を書けば完了です。
感想
やってみた感じ、分かりやすさはあまり変わらないですね!!