【发布时间】:2014-07-30 14:40:07
【问题描述】:
当我使用 IPython 在 Python 中进行调试时,有时会遇到断点,我想检查当前是生成器的变量。我能想到的最简单的方法是将其转换为列表,但我不清楚在 ipdb 的一行中执行此操作的简单方法是什么,因为我对 Python 还很陌生。
【问题讨论】:
当我使用 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.
调试器命令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']
【讨论】:
list(gen) 会耗尽生成器,之后将无法使用