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

Python 将生成器对象转换为列表以进行调试,python,generator,ipdb,Python,Generator,Ipdb,当我使用IPython在Python中调试时,有时会遇到一个断点,我想检查一个当前是生成器的变量。我能想到的最简单的方法是将它转换为一个列表,但我不清楚在ipdb中的一行中实现这一点的简单方法是什么,因为我对Python非常陌生。只需在生成器上调用list lst = list(gen) lst 请注意,这会影响发电机,发电机不会返回任何其他项目 您也不能在IPython中直接调用list,因为它与列出代码行的命令冲突 在此文件上测试: def gen(): yield 1 y

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

只需在生成器上调用
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.
还有一个
exec
命令,通过在表达式前面加
前缀来调用它,它强制调试器将您的表达式作为Python表达式

ipdb> !list(g1)
[]
有关更多详细信息,请参见调试器中的
help p
help pp
help 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']

您好@Jan Vlcinsky,首先感谢您的回答,这种方法对小样本非常有效。我正在处理生成器中的1000000000000000数据。是否有其他方法将其转换为fast,因为这种方法可能需要几天时间才能提供我所需的数据,再次感谢。@WalidBousseta如果您有一个具有如此多潜在项的生成器,任何将其完全转换为列表的尝试都将消耗所有RAM。同意Jan的观点。据我所知,生成器的用途是提供一种非常方便的方式来访问数据,即a)本质上是顺序的,b)长度不确定。如果可能的话,我想看看供应商是否可以提供批量传输选项/数据转储。但是,如果计算一个取决于以前的项目和它的原始马力,考虑一个编译语言。通过这种方式,您可以获得1000+x的速度(例如,Swift中的内部循环在矩阵乘法方面比Python快90000倍)。请记住,
list(gen)
将耗尽生成器,之后它将无法使用
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']