pdb,如gdb,或trepan3k 有中断命令:
(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.
但是当你这样做时,你应该注意一些事情。
如果您通过文件名和行号指定断点,则可能会收到错误消息。例如:
(Pdb) break foo.py
*** The specified object 'foo.py' is not a function
or was not found along sys.path.
让我们试着理解消息的内容。 foo.py 显然不是函数。它是一个文件。是在sys.path吗?
(Pdb) import sys
(Pdb) sys.path
['', '/usr/lib/python3.6', ...]
没有。好的。那么如果我将文件名作为绝对路径呢?
(Pdb) break /tmp/bug.py:2
Breakpoint 1 at /tmp/bug.py:2
好的。这样可行。但同样有一个警告:可能在该文件中的那一行停止吗?观看:
(Pdb) break /etc/hosts:1
Breakpoint 2 at /etc/hosts:1
/etc/hosts 是一个文件,但它不是 Python 程序。正如我们之前看到的,pdb 会在文件丢失时发出警告,但它不会检查文件是否为 Python 文件。
如果你改为使用trepan3k 运行它,它会打印出令人讨厌的回溯(我会在某个时候修复它),但至少它给出了一些错误的暗示。
pdb 也不太聪明,知道第 2 行是否有可以停止的代码; pdb 将警告空行或空行或行注释行,但任何比这更复杂的东西,比如一些随机文本,并且没有骰子。
再一次,trepan3k 在这方面要好一点:
(trepan3k) break /tmp/bug.py:2
** File /tmp/bug.py is not stoppable at line 2.
使用断点时的最后一个警告是,断点可能不会被命中,因为代码永远不会到达那里。但是sys.set_trace() 也有这种情况,所以我想这种行为并不令人意外。
trepan3k 和 pdb 的断点之间还有一个值得注意的区别。在pdb 中,当您在函数上设置断点时,您实际上是在为该函数记录的第一行设置断点。也就是说,你已经进入了函数。
在 trepan3k 中,您将其设置在函数 call 上,该函数与它所在的位置无关。此外,在对象的上下文中给出的方法名称是一种方法也是可能的,我经常使用它。这是一个例子:
trepan3k /tmp/pathtest.py
(/tmp/pathtest.py:1): <module>
-> 1 from pathlib import Path
(trepan3k) n
(/tmp/pathtest.py:2 @12): <module>
-- 2 mypath = Path(__file__)
(trepan3k) n
(/tmp/pathtest.py:3 @20): <module>
-- 3 print(mypath.match("p.*"))
(trepan3k) break mypath.match()
Breakpoint 1 set at line 972 of file /home/test/.pyenv/versions/3.8.10/lib/python3.8/pathlib.py
(trepan3k) c
(/home/test/.pyenv/versions/3.8.10/lib/python3.8/pathlib.py:972): match
xx 972 def match(self, path_pattern):
(trepan3k) path_pattern
'p.*'
(trepan3k) info pc
PC offset is -1.