如何忽略下一个pdblike断点,包括set\u trace()调用?

2024-10-05 22:02:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下问题:

我有如下代码

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

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

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

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


Tags: 函数代码importmydeftrace情况function
2条回答

当我遇到这个问题时,我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行设置一个断点

^{pr2}$

现在,继续

(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

您可以尝试在第一次执行函数时设置它的属性。比如:

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语句中的代码将不会执行。这个解决方案依赖于你的函数不是类内部的方法,因为类方法不能有属性,因为它们已经是类的属性。在

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

相关问题 更多 >