文章目录
1 程序调试基本方法
1.1 PDB调试
运行程序:
#当python抛出异常或错误信息时,可以用PDB(The Python Debugger,Python调试器)进行程序调试
x=1
x1
运行结果:
Traceback (most recent call last):
File "<ipython-input-45-ff55524dcc80>", line 2, in <module>
x1
NameError: name 'x1' is not defined
1.2 debug调试
运行程序:
%debug #打开PDB方法,退出PDB方法是输入q或quit
#除了PDB,常用的python调试器还有Pylint,Pycheaker
运行结果:
<ipython-input-45-ff55524dcc80>(2)<module>()
1 x=1
----> 2 x1
ipdb> x
1
ipdb> q
2 设置错误信息的显示方式
2.1 mode Plain
运行程序:
%xmode Plain
y=1
Y
运行结果:
Exception reporting mode: Plain
Traceback (most recent call last):
File "<ipython-input-48-e9d491258c9c>", line 3, in <module>
Y
NameError: name 'Y' is not defined
2.2 mode Verbose
运行程序:
%xmode Verbose
y=1
Y
运行结果:
Exception reporting mode: Verbose
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-49-4e5fe2f91061> in <module>
1 get_ipython().run_line_magic('xmode', 'Verbose')
2 y=1
----> 3 Y
global Y = undefined
NameError: name 'Y' is not defined
2.3 debug
运行程序:
%debug
运行结果:
<ipython-input-49-4e5fe2f91061>(3)<module>()
1 get_ipython().run_line_magic('xmode', 'Verbose')
2 y=1
----> 3 Y
ipdb> x
1
ipdb> y
1
ipdb> q
3 设置断言的方法
运行程序:
a=1
b=0
assert b!=0,"分母不能等于0"
运行结果:
AssertionError Traceback (most recent call last)
<ipython-input-51-2b94eee22f18> in <module>
1 a=1
2 b=0
----> 3 assert b!=0,"分母不能等于0"
global b = 0
AssertionError: 分母不能等于0
运行程序:
%debug
运行结果:
<ipython-input-51-2b94eee22f18>(3)<module>()
1 a=1
2 b=0
----> 3 assert b!=0,"分母不能等于0"
ipdb> a
ipdb> b
ipdb> a
ipdb> quuit
*** NameError: name 'quuit' is not defined
ipdb> quit