プログラムを停止/終了せずに、完全なPython例外トレースバックをキャッチして印刷する 質問する

プログラムを停止/終了せずに、完全なPython例外トレースバックをキャッチして印刷する 質問する

終了せずに例外をキャッチしてログに記録したい、例:

try:
    do_stuff()
except Exception as err:
    print(Exception, err)
    # I want to print the entire traceback here,
    # not just the exception name and details

try/except が例外をインターセプトせずに例外が発生したときに出力されるのとまったく同じ出力を出力したいのですが、プログラムを終了させたくありません。

ベストアンサー1

traceback.format_exc()必要な場合は、さらに詳しい情報が得られます。

import traceback

def do_stuff():
    raise Exception("test exception")

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())

出力は次のようになります:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    do_stuff()
  File "main.py", line 5, in do_stuff
    raise Exception("test exception")
Exception: test exception

おすすめ記事