20
10

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 5 years have passed since last update.

tracebackを文字列で取得する時はTracebackExceptionを使おう

Last updated at Posted at 2019-07-08

TL;DR

''.join(traceback.TracebackException.from_exception(exc).format())

従来の方法

tracebackを文字列で取得する方法として traceback.format_exception() がよく紹介されています。

import traceback

try:
    1/0
except Exception as e:
    t = traceback.format_exception(type(e), e, e.__traceback__)
    print(t)

# ['Traceback (most recent call last):\n',
#  '  File "/path/to/script.py", line 4, in <module>\n    1/0\n',
#  'ZeroDivisionError: division by zero\n']

この書き方は冗長です。エラーひとつに対して etype, value, tb の3つの引数を与えなくてはなりません。
(引数 e_type は Python3.5 からは無視される仕様となったため、 None で代用できます)

より単純な書き方

Python3.5 から TracebackException が導入され、より単純に同じことを実現できるようになりました。

import traceback

try:
    1/0
except Exception as e:
    t = list(traceback.TracebackException.from_exception(e).format())
    print(t)

# ['Traceback (most recent call last):\n',
#  '  File "/path/to/script.py", line 4, in <module>\n    1/0\n',
#  'ZeroDivisionError: division by zero\n']

TracebackException.format() は文字列のジェネレータを返す点に注意してください。

謝辞

TracebackException について教えてくださった python.jp の atsuoishimoto さんに感謝申し上げます。

20
10
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
20
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?