LoginSignup
7
7

More than 5 years have passed since last update.

Python | Jupyter > 事後解析デバッギング | pdb.post_mortem()

Last updated at Posted at 2017-09-07

関連: [Python]超便利なデバッグ

Jupyterでの事後解析デバッギング

@ 科学技術計算のためのPython入門 -開発基礎、必須ライブラリ、高速化- by 中久喜 健司さん
p80

IPython (もしくはJupyter Notebook)を使えば「事後解析デバッギング」が可能とのこと。
「事後解析デバッギング」ではエラーが出てからdebugを走らせるという流れになる。

In [26]: run myscript.py
...
NameError: name 'z' is not defined
In [27]: debug
でデバッグ開始

プログラムを走らせてエラーに気づいた後でデバッグをする、という流れで作業ができそう。

Pythonの事後解析デバッギング

事後解析デバッギングもサポートし、プログラムの制御下で呼び出すことができます。

Python自体で事後解析デバッギング可能ということだろうか?

pdb.post_mortem()

pdb.post_mortem(traceback=None)
与えられた traceback オブジェクトの事後解析デバッギングに入ります。

以下を見つけた。
https://stackoverflow.com/questions/242485/starting-python-debugger-automatically-on-error

試してみた。

動作環境
CentOS 6.8 (64bit)
httpd.x86_64 0:2.2.15-54.el6.centos
Python 2.6.6
postdebug_170907.py
import pdb, traceback, sys

def addxy(x, y):
    return z

try:
    x, y = 3.141, 2.718
    z = addxy(x, y)
except:
    type, value, tb = sys.exc_info()
    traceback.print_exc()
    pdb.post_mortem(tb)
$ python postdebug_170907.py 
Traceback (most recent call last):
  File "postdebug_170907.py", line 8, in <module>
    z = addxy(x, y)
  File "postdebug_170907.py", line 4, in addxy
    return z
NameError: global name 'z' is not defined
> /home/wrf/WORK/PYTHON/postdebug_170907.py(4)addxy()
-> return z
(Pdb) p x
3.141

エラーが出た時点でpdbが起動し、p xなどのデバッグができるようだ。

-m pdbとの使い分けは未消化。

7
7
3

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