5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonのexceptで丁寧にtracebackを表示する

Posted at

ちゃお…†
まいおり…†

Pythonで例外をcatchした際にexcept節で例外の詳細を表示したいときってありますよね?そんなときは以下のコードをコピペしてください!

import traceback
import re
import sys

try:
    pass  # ここに何か処理を書く
except Exception as e:
    error_class = type(e)
    error_description = str(e)
    err_msg = '%s: %s' % (error_class, error_description)
    print(err_msg)
    tb = traceback.extract_tb(sys.exc_info()[2])
    trace = traceback.format_list(tb)
    print('---- traceback ----')
    for line in trace:
        if '~^~' in line:
            print(line.rstrip())
        else:
            text = re.sub(r'\n\s*', ' ', line.rstrip())
            print(text)
    print('-------------------')

以下はtry節に a = 1 / 0 と書いて実行した時の標準出力です。

<class 'ZeroDivisionError'>: division by zero
---- traceback ----
  File "/private/tmp/example.py", line 6, in <module>
    a = 1 / 0
        ~~^~~
-------------------

これでゼロ除算が起きてるのがファイルの6行目だとわかりますね。

もちろんprint関数じゃなくてloggerに出力させたりお好みにカスタマイズしてお使いください!

みんな終電大丈夫?

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?