如何在Python PDB中继续下一个循环迭代?

2024-03-29 05:52:43 发布

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

给定此示例代码:

import pdb

for i in range(10):
  pdb.set_trace()
  print(str(i))

当我从PDB得到提示时,如果PDB也使用continue循环控制语句,我如何跳过循环的迭代来继续代码执行?


Tags: 代码inimport示例fortracerange语句
2条回答

不能使用continue,因为调试器中的新语句需要完整并且在没有任何其他上下文的情况下有效;在编译时,continue必须在循环构造中给定。因此,即使调试器正在处理循环构造,也不能使用!continue(使用!来防止pdb解释命令)。

您可以使用j[ump]命令,只要您稍后有一个语句跳转到。如果要跳过的语句之后循环为空,则只能“倒带”:

$ bin/python test.py
> /.../test.py(5)<module>()
-> print(str(i))
(Pdb) l
  1     import pdb
  2     
  3     for i in range(10):
  4         pdb.set_trace()
  5  ->     print(str(i))
  6     
[EOF]
(Pdb) j 3
> /.../test.py(3)<module>()
-> for i in range(10):

j 3跳到第3行,不跳过任何内容;将重新执行第3行,包括设置range()。您可以跳到第4行,但是for循环不会前进。

您需要在循环的末尾添加另一个语句,以便Python继续。该语句可以是print()pass或任何不必改变状态的语句。您甚至可以使用continue作为最后一个语句。我用了i

for i in range(10):
    pdb.set_trace()
    print(str(i))
    i  # only here to jump to.

演示:

$ bin/python test.py
> /.../test.py(5)<module>()
-> print(str(i))
(Pdb) l
  1     import pdb
  2     
  3     for i in range(10):
  4         pdb.set_trace()
  5  ->     print(str(i))
  6         i  # only here to jump to.
  7     
[EOF]
(Pdb) j 6
> /.../test.py(6)<module>()
-> i  # only here to jump to.
(Pdb) c
> /.../test.py(4)<module>()
-> pdb.set_trace()
(Pdb) s
> /.../test.py(5)<module>()
-> print(str(i))
(Pdb) j 6
> /.../test.py(6)<module>()
-> i  # only here to jump to.
(Pdb) i
1
(Pdb) c
> /.../test.py(4)<module>()
-> pdb.set_trace()
(Pdb) s
> /.../test.py(5)<module>()
-> print(str(i))
(Pdb) j 6
> /.../test.py(6)<module>()
-> i  # only here to jump to.
(Pdb) i
2

来自Debugger Commands

j(ump) lineno
Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don’t want to run.

It should be noted that not all jumps are allowed — for instance it is not possible to jump into the middle of a for loop or out of a finally clause.

听起来很奇怪。不过,您应该能够使用jump command。您可能需要在for循环的末尾添加一个pass语句,以便可以跳到循环的末尾。如果您不确定代码的行号,那么可以使用^{}找出循环的行号。

> c:\run.py(5)<module>()
-> print(i)
(Pdb) ll
  1     import pdb
  2     
  3     for i in range(10):
  4         pdb.set_trace()
  5  ->     print(i)
  6         pass
(Pdb) j 6
> c:\run.py(6)<module>()
-> pass
(Pdb) c
> c:\python\run.py(4)<module>()
-> pdb.set_trace()
(Pdb) c
1
> c:\python\run.py(5)<module>()
-> print(i)

值得注意的是,跳到for行将重新启动循环。

相关问题 更多 >