将生成器对象转换为列表以进行调试

2024-04-25 04:54:09 发布

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

当我使用I Python在Python中调试时,有时会遇到一个断点,我想检查一个当前是生成器的变量。我能想到的最简单的方法是将它转换成一个列表,但是我不清楚在ipdb中的一行中,什么是简单的方法,因为我对Python还很陌生。


Tags: 方法列表断点ipdb陌生
1条回答
网友
1楼 · 发布于 2024-04-25 04:54:09

只需在生成器上调用list

lst = list(gen)
lst

请注意,这会影响生成器,它不会返回任何其他项。

也不能直接调用IPython中的list,因为它与列出代码行的命令冲突。

在此文件上测试:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

运行时:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

转义函数/变量/调试器名称冲突的通用方法

调试器命令pppprintprettyprint跟随它们的任何表达式。

所以你可以使用它如下:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

还有一个exec命令,通过在表达式前面加上!来调用,它强制调试器将表达式作为Python表达式。

ipdb> !list(g1)
[]

有关更多详细信息,请参见调试器中的help phelp pphelp exec

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

相关问题 更多 >