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.
问问题
193184 次
1 回答
243
只需调用list
生成器即可。
lst = list(gen)
lst
请注意,这会影响不会返回任何其他项目的生成器。
您也不能直接list
在 IPython 中调用,因为它与列出代码行的命令冲突。
对此文件进行了测试:
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.
转义函数/变量/调试器名称冲突的通用方法
有调试器命令p
,pp
它会print
和prettyprint
它们后面的任何表达式。
所以你可以按如下方式使用它:
$ 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 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']
于 2014-06-09T23:44:25.553 回答