【Python进阶(二)】——程序调试方法

🍉CSDN小墨&晓末:https://blog.csdn.net/jd1813346972

个人介绍: 研一|统计学|干货分享
         擅长Python、Matlab、R等主流编程软件
         累计十余项国家级比赛奖项,参与研究经费10w、40w级横向

文章目录

  • [1 程序调试基本方法](#1 程序调试基本方法)
    • [1.1 PDB调试](#1.1 PDB调试)
    • [1.2 debug调试](#1.2 debug调试)
  • [2 设置错误信息的显示方式](#2 设置错误信息的显示方式)
    • [2.1 mode Plain](#2.1 mode Plain)
    • [2.2 mode Verbose](#2.2 mode Verbose)
    • [2.3 debug](#2.3 debug)
  • [3 设置断言的方法](#3 设置断言的方法)

【Python进阶(二)】系列------程序调试方法,建议收藏!

该篇文章利用Python演示了程序调试方法,包括程序的基本调试方法里;错误信息显示方式;断言设置方法等内容。

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
相关推荐
倔强青铜三21 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
聚客AI1 天前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
惯导马工1 天前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法