当我使用IPython在Python中进行调试时,我有时遇到了一个断点,我想检查一个当前是生成器的变量。我能想到的最简单的方法是将其转换为列表,但我不清楚ipdb
在一行中执行此操作的简单方法,因为我&#39 ;我是Python的新手。
答案 0 :(得分:141)
只需在生成器上调用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']