본문 바로가기
Python

[Python] Debugging

by llHoYall 2021. 10. 27.

Debugging is an important thing to fix a problem of code.

Debugger

pdb

pdb is a command-line tool to debug Python code.

import pdb
pdb.set_trace()

ipdb

ipdb is the same kind of tool.

In addition, ipdb can debug IPython as well.

But, this is not a built-in module.

$ pip install ipdb
import ipdb
ipdb.set_trace()

pudb

pudb is a more useful debugger than pdb and ipdb.

But, this is not a built-in module like ipdb.

Also, it looks like a GUI, but it's a command-line tool.

$ pip install pudb
import pudb
pudb.set_trace()

Usage of Debugger

pdb

If you use this tool, simply input the command as following:

  • ? / h / help : Help
  • w / where : Print the current stack trace
  • s / step : Run the current line
  • n / next : Continue execution until the next line
  • r / return : Continue execution until the current function returns
  • a / args : Print the argument list of the current function
  • l / list : List source code for the current file
  • j # / jump # : Jump to the line
  • unt # / until # : Continue execution until the line
  • p <expression> : Evaluate the expression and print its value
  • pp <expression> : Like the p, except the value of the expression is pretty-printed using the pprint module
  • q / quit : Quit from the debugger

ipdb

Its command is the same as pdb.

pudb

If you press ? key, you can see the GUI help menu.

You can even use a mouse.

  • ? / F1 : Help
  • n : Step over
  • s : Step into
  • c : Continue
  • r / f : Finish current function
  • t : Run to cursor
  • e : Show traceback
  • b : Set/Clear breakpoint
  • m : Open module
  • L : show (file/line) location / Go to line
  • / : Search
  • q : Quit

Breakpoint

breakpoint() can be used in Python v3.7 or higher.

When this built-in function is called where debugging is desired, the debugger is automatically called at that location.

x = 3
y = 4
breakpoint()
z = x + y

If you don't want to use breakpoint(), set the environment variable PYTHONBREAKPOINT to 0.

# On MAC
$ export PYTHONBREAKPOINT=0

If not, set it as an empty string.

# On MAC
$ export PYTHONBREAKPOINT=

Conclusion

There is a web-based debugger as well.

But, I think the pudb is a good option.

Debugging skill is very important, so try to get used to it.

'Python' 카테고리의 다른 글

[Python] String  (0) 2021.10.31
[Python] Testing  (0) 2021.10.30
[Python] logging  (0) 2021.10.25
[Python] Docstring  (0) 2021.10.18
[Python] Running Python with Docker  (0) 2021.08.28

댓글