40.md 1.8 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10
# Python 调试

> 原文: [https://pythonspot.com/python-debugging/](https://pythonspot.com/python-debugging/)

我们可以使用调试工具来最小化和发现错误。 在本文中,您将学习最佳的 Python 调试技巧。

## PuDB-基于控制台的 Python 调试器

![python-debugging-pudb](img/be30d3c5aa2158a9864d173116eb6291.jpg)

W
wizardforcel 已提交
11
使用 PuDB 进行 Python 调试
W
init  
wizardforcel 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

使用 PuDB 终端显示了图形界面。

## 安装

,以便与 Python 3 一起安装:

```py

sudo pip3 install pudb

```

对于 Python 2.x 使用:

```py

sudo pip install pudb

```

## 调试

使用以下命令开始调试:

```py

$ pudb3 program.py 

```

(或 sudo(如果您没有正确的权限))

您可以逐步完成该程序。 使用 **n** 键逐步执行该程序。 当前变量内容显示在右上方。

![pudb-debug](img/224bd2a6a881437fdda6c2509430673e.jpg)

W
wizardforcel 已提交
49
python 调试
W
init  
wizardforcel 已提交
50 51 52 53 54

您可以使用 **b** 键设置断点。 要继续执行直到下一个断点,请按 **c** 键。

![python-breakpoint](img/b4dc9a1dbd2f3dbfa9b8223a63b62c12.jpg)

W
wizardforcel 已提交
55
Python 程序中的断点
W
init  
wizardforcel 已提交
56 57 58

## PDB-Python 调试器

W
wizardforcel 已提交
59
`pdb`模块支持设置断点。 断点是程序的有意暂停。 您可以在其中获取有关程序状态的更多信息。
W
init  
wizardforcel 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

要设置断点,请插入行

```py

pdb.set_trace()

```

## 示例

实际示例:

```py

import pdb

x = 3
y = 4
pdb.set_trace()

total = x + y
pdb.set_trace()

```

我们在该程序中插入了一些断点。 程序将在每个断点处暂停( **pdb.set_trace()**)。 要查看变量内容,只需键入变量名称:

```py

$ python3 program.py
(Pdb) x
3
(Pdb) y
4
(Pdb) total
*** NameError: name 'total' is not defined
(Pdb) 

```

**c****继续**继续执行程序,直到下一个断点

```py

(Pdb) c
--Return--
> program.py(7)<module>()->None
-> total = x + y
(Pdb) total
7

```