Skip to main content
 首页 » 编程设计

python之如何永久设置 pdb 中显示的行数

2025年05月04日9softidea

我可以在运行时使用 l 在 pdb 中显示要执行的当前行之前和之后的更多行,但是我们可以在脚本中或通过命令行选项永久地执行此操作吗?

ywong:tmp ywong$ python tests.py 
> /private/tmp/tests.py(23)<module>() 
-> unittest.main() 
(Pdb) l 
 18             self.assertEqual(1,1) 
 19 
 20     if __name__ == "__main__": 
 21         import pdb 
 22         pdb.set_trace() 
 23  ->     unittest.main() 
 24         #unittest.main(testRunner=MyRunner) 
[EOF] 
(Pdb) 

请您参考如下方法:

您可以设置自己的函数,通过实例化 pdb.Pdb 创建自定义调试器对象并执行 list调用 pdb 之前的命令交互式提示。

您可以按如下方式创建自定义调试器调用函数:

import pdb, sys 
 
def auto_list_debug(): 
    # Create an instance of the Pdb class 
    my_pdb = pdb.Pdb() 
    my_pdb.reset() 
 
    # Execute your list command before invoking the interactive prompt 
    my_pdb.cmdqueue.append('l') 
 
    # Invoke the interactive prompt with the current frame 
    my_pdb.interaction(sys._getframe().f_back, None) 

使用此函数代替 pdb.set_trace()

for i in range(5): 
    auto_list_debug()