当我使用IPython在Python中调试时,有时会遇到一个断点,我想检查一个当前是生成器的变量。我能想到的最简单的方法就是将它转换成一个列表,但是我不清楚在ipdb
中用一行就能做到这一点的简单方法是什么,因为我对Python太陌生了。
发布于 2014-06-10 07:44:26
只需在生成器上调用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.
转义函数/变量/调试器名称冲突的一般方法
有调试器命令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']
https://stackoverflow.com/questions/24130745
复制相似问题