程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

python散装笔记——103: 调试

hfteth 2025-03-05 16:20:27 技术文章 10 ℃

1: 通过 IPython 和 ipdb

如果安装了 IPython(或 Jupyter),调试器可以使用

import ipdb
ipdb.set_trace()

当达到该值时,代码将退出并打印:

/home/usr/ook.py(3)()
1 import ipdb
2 ipdb.set_trace()
----> 3 print("Hello world!")
ipdb>

显然,这意味着必须编辑代码。还有一种更简单的方法:

from IPython.core import ultratb
sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=1)

如果出现未捕获异常,将调用调试器。

2: Python 调试器: 使用 _pdb_逐步调试

Python 标准库包含一个名为 pdb 的交互式调试库。pdb 具有广泛的功能,其中最常用的是 “逐步通过 ”程序的能力。

要立即进入逐步调试,请使用

python -m pdb 

这将在程序的第一行启动调试器。

通常情况下,你会希望调试代码的特定部分。为此,我们需要导入 pdb 库,并使用 set_trace() 中断这个麻烦的示例代码流。

import pdb

def divide(a, b):
  pdb.set_trace()
  return a/b
  # What's wrong with this? Hint: 2 != 3

print divide(1, 2)

运行该程序将启动交互式调试器。

python foo.py
> ~/scratch/foo.py(5)divide()
-> return a/b
(Pdb)

该命令通常在一行中使用,因此可以用一个 # 字符将其注释掉

import pdf; pdb.set_trace()

在 (Pdb) 提示符下可以输入命令。这些命令可以是调试器命令,也可以是 python 命令。要打印变量,我们可以使用调试器中的 p 或 python 的 print

(Pdb) p a
1
(Pdb) print a
1

要查看所有本地变量的列表,请使用

locals

内置函数

这些都是需要了解的调试器命令:

b | : set breakpoint at line *n* or function named *f*.
# b 3
# b divide
b: show all breakpoints.
c: continue until the next breakpoint.
s: step through this line (will enter a function).
n: step over this line (jumps over a function).
r: continue until the current function returns.
l: list a window of code around this line.
p : print variable named *var*.
# p x
q: quit debugger.
bt: print the traceback of the current execution call stack
up: move your scope up the function call stack to the caller of the current function
down: Move your scope back down the function call stack one level
step: Run the program until the next line of execution in the program, then return control back to the debugger
next: run the program until the next line of execution in the current function, then return control back to the debugger
return: run the program until the current function returns, then return control back to the debugger
continue: continue running the program until the next breakpoint (or set_trace si called again)

调试器还可以对 python 进行交互式评估:

-> return a/b
(Pdb) p a+b
3
(Pdb) [ str(m) for m in [a,b]]
['1', '2']
(Pdb) [ d for d in xrange(5)]
[0, 1, 2, 3, 4]

注意

如果变量名与调试器命令重合,请在变量名前使用感叹号“!”,以明确指代变量而非调试器命令。例如,您可能经常使用变量名 “c ”来表示计数器,您可能希望在调试器中打印它。相反,使用“!c ”命令可以打印变量的值,如下所示:

(Pdb) !c
4

3: 远程调试器

有时你需要调试由其他进程执行的 python 代码,这时 rpdb 就派上用场了。

rpdbpdb 的一个封装器,能将 stdinstdout 重新路由到一个套接字处理程序。默认情况下,它会在 4444 端口打开调试器。

使用方法

# In the Python file you want to debug.
import rpdb
rpdb.set_trace()

然后,你需要在终端运行这个程序来连接这个进程。

# Call in a terminal to see the output
$ nc 127.0.0.1 4444

您将获得 pdb promt

> /home/usr/ook.py(3)()
-> print("Hello world!")
(Pdb)
最近发表
标签列表