I will summarize debugging using ipdb, including organizing what the web development beginners have learned.
It provides an extension of pdb, which is a ** debugger ** that comes standard with Python.
Enter the following code at the position where you want to start the debugger and execute the program.
import ipdb; ipdb.set_trace()
When executed, it waits for ** standard input **, so you can operate the debugger by entering a command. The following is a summary of frequently used (likely) commands.
command | motion |
---|---|
n | Run to next line |
s | Execute until the next function |
p variable name | Show variable value |
a | Show the arguments of the function being executed |
h | help |
q | End |
Let's actually use ipdb using the program of Aggressive Cows of POJ No.3468.
Aggressive.py
import ipdb
n = 5
m = 3
x = [1, 2, 8, 4, 9]
def C(d):
last = 0
for _ in range(1, m):
crt = last + 1
while crt<n and x[crt]-x[last]<d:
crt += 1
if crt == n:
return False
last = crt
return True
x.sort()
lb, ub = 0, max(x)
while ub-lb > 1:
ipdb.set_trace()
mid = int( (lb+ub)/2 )
if C(mid):
lb = mid
else:
ub = mid
print(lb)
Execute.
$ python Aggressive.py
>c:/users/~/aggressive.py(21)<module>()
20 import ipdb; ipdb.set_trace()
---> 21 mid = int( (lb+ub)/2 )
22 if C(mid):
The set breakpoint is output as an arrow.
ipdb> h
Documented commands (type help <topic>):
========================================
EOF cl disable interact next psource rv unt
a clear display j p q s until
alias commands down jump pdef quit source up
args condition enable l pdoc r step w
b cont exit list pfile restart tbreak whatis
break continue h ll pinfo return u where
bt d help longlist pinfo2 retval unalias
c debug ignore n pp run undisplay
Miscellaneous help topics:
==========================
exec pdb
A list of usable commands is output.
ipdb> p mid
*** NameError: name 'mid' is not defined
The variable mid
is not defined because line 21 has not been executed yet.
ipdb> n
> c:/users/~/aggressive.py(22)<module>()
21 mid = int( (lb+ub)/2 )
---> 22 if C(mid):
23 lb = mid
The arrow indicating the breakpoint shifts down by one.
ipdb> p mid
4
Since the 21st line is executed, the value of the variable mid
is displayed.
ipdb> s
--Call--
> c:/users/~/aggressive.py(6)C()
5
----> 6 def C(d):
7 last = 0
It seems that the call to the next function was executed.
ipdb> a
d = 4
Since the call to the next function was just below, the value of the variable mid
confirmed earlier is displayed as an argument.
ipdb> q
Exiting Debugger.
Exit the debugger.
I used all the commands that are often used in ipdb. It was my first time to use the debugger, but I ran the program ** halfway ** and checked the contents of the variables each time, or ran it to the desired position without rewriting the program. I found it very convenient to go. It's hard to write a program because it's debugging, so I want to make good use of the debugger to write an efficient and error-free program.
Recommended Posts