Python 将生成器对象转换为列表以进行调试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24130745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert generator object to list for debugging
提问by Seanny123
When I'm debugging in Python using IPython, I sometimes hit a break-point and I want to examine a variable that is currently a generator. The simplest way I can think of doing this is converting it to a list, but I'm not clear on what's an easy way of doing this in one line in ipdb
, since I'm so new to Python.
当我使用 IPython 在 Python 中进行调试时,有时会遇到一个断点,我想检查当前是生成器的变量。我能想到的最简单的方法是将其转换为列表,但我不清楚在ipdb
.
采纳答案by Jan Vlcinsky
Simply call list
on the generator.
只需调用list
发电机。
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
请注意,这会影响不会返回任何其他项目的生成器。
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
您也不能直接调用list
IPython,因为它与列出代码行的命令冲突。
Tested on this file:
在这个文件上测试:
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)
which when run:
运行时:
$ 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.
General method for escaping function/variable/debugger name conflicts
转义函数/变量/调试器名称冲突的通用方法
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
有调试器命令p
和pp
这种意愿print
,并prettyprint
跟随他们任何表情。
So you could use it as follows:
因此,您可以按如下方式使用它:
$ 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
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
还有一个exec
命令,通过在表达式前加上 来调用!
,它强制调试器将您的表达式作为 Python 表达式。
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
欲了解更多详情,请参阅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']