LoginSignup
44

More than 5 years have passed since last update.

Pythonでpdbを使ったデバッグ

Posted at

pdbを使ったPythonコードのデバッグ

import pdbとか使えますが,ここではソースコードに変更を加えずにデバッグする方法を紹介します.
よく使うコマンドだけを取り上げます.

始め方

$ python -m pdb XXXXX.py

または

$ python3 -m pdb XXXXX.py

実行例

実行するプログラムの例

hello.py
msg = "Hello world"

def hello(txt):
    print(txt)

hello(msg)
print("Done.")
  • pdbの実行例
$ python3 -m pdb hello.py
> /path/to/current/directory/hello.py(1)<module>()
-> msg = "Hello world"
(Pdb)

pdbの使い方

(Pdb)に続いてコマンドを入力することで,デバッグ作業を進めることができます.

  • よく使うコマンド
コマンド 機能
b(reak) [行数または関数名] 行または関数にブレークポイントをうつ
c(ont(inue)) 次のブレークポイントに当たるまで実行
s(tep) 現在の行を実行(関数呼び出しで止まる)
n(ext) 現在の行を実行(関数呼び出しであれば関数を実行)
q(uit) デバッガを終了

コマンドで,かっこ内の文字は省略できます.

実行例

$ python3 -m pdb hello.py
> /path/to/current/directory/hello.py(1)<module>()
-> msg = "Hello world"
(Pdb) b 6
Breakpoint 1 at /path/to/current/directory/hello.py:6
(Pdb) c
> /path/to/current/directory/hello.py(6)<module>()
-> hello(msg)
(Pdb) s
--Call--
> /path/to/current/directory/hello.py(3)hello()
-> def hello(txt):
(Pdb) s
> /path/to/current/directory/hello.py(4)hello()
-> print(txt)
(Pdb) n
Hello world
--Return--
> /path/to/current/directory/hello.py(4)hello()->None
-> print(txt)
(Pdb) c
Done.
The program finished and will be restarted
> /path/to/current/directory/hello.py(1)<module>()
-> msg = "Hello world"
(Pdb) q
$ 

参考

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
44