LoginSignup
1
2

More than 5 years have passed since last update.

Pythonのエラー(スタックトレース)を色付けして分かりやすくする

Posted at

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を書けば完了です。

感想

やってみた感じ、分かりやすさはあまり変わらないですね!!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2