如何忽略下一个类似 pdb 的断点,包括 set_trace() 调用?

How to ignore the next pdb-like breakpoints, including set_trace() calls?

我遇到了以下问题:

我有非常像下面的代码

def my_function():
    import pdb; pdb.set_trace()
    ....

在运行时,我的函数被调用了很多次。我有兴趣在第一次调用此函数时检查代码执行情况。

如果我完成了检查,我想点击 c,让程序恢复正常执行,而不会在下次调用此函数时在此断点处停止。

有办法吗?或者我必须做一些完全不同的事情,比如把 set_trace() 调用一些只调用一次的地方,然后一旦命中断点,使用像 tbreak my_function 这样的命令来设置一次性断点在那里?

您可以尝试在函数第一次执行时设置一个属性。类似于:

def my_function():
    if not hasattr(my_function,'first_time'):
        my_function.first_time = 1 # Dummy value
        import pdb; pdb.set_trace()
    ...

属性 first_time 将在函数调用之间持续存在,并且在第一次调用函数时将创建它。下次调用该函数时,它已经存在,不会执行if语句中的代码。此解决方案依赖于您的函数不是 class 中的方法,因为 class 方法不能具有属性,因为它们已经是 class 的属性。

请注意,我不确定您的实际代码中是否有导入,但最佳编码实践规定您应该只将导入放在代码的开头,而不是在您拥有的函数内部。

当我遇到这个问题时,我 import pdb; pdb.set_trace() 在文件的开头(导入时间)或在 __main__ (运行 时间)然后使用调试器 list(或只是 l)命令来查找你的行号和 break(或只是 b)来设置断点。

您也可以从一开始就以PDB模式启动程序并到达相同的点。

(Pdb) help break
b(reak) ([file:]lineno | function) [, condition]
With a line number argument, set a break there in the current
file.  With a function name, set a break at first executable line
of that function.  Without argument, list all breaks.  If a second
argument is present, it is a string specifying an expression
which must evaluate to true before the breakpoint is honored.

The line number may be prefixed with a filename and a colon,
to specify a breakpoint in another file (probably one that
hasn't been loaded yet).  The file is searched for on sys.path;
the .py suffix may be omitted.

我会在第5行设置一个断点,例如

(Pdb) b 5
Breakpoint 1 at /home/flipmcf/program.py:5

现在,继续

(Pdb) c

到达断点会进入pdb

既然只想看第一个运行,直接去掉断点

(Pdb) help clear
cl(ear) filename:lineno
cl(ear) [bpnumber [bpnumber...]]
With a space separated list of breakpoint numbers, clear
those breakpoints.  Without argument, clear all breaks (but
first ask confirmation).  With a filename:lineno argument,
clear all breaks at that line in that file.

Note that the argument is different from previous versions of
the debugger (in python distributions 1.5.1 and before) where
a linenumber was used instead of either filename:lineno or
breakpoint numbers.

(Pdb) clear 1
Deleted breakpoint 1
(Pdb) c