将生成器对象转换为列表以进行调试 [英] Convert generator object to list for debugging

查看:182
本文介绍了将生成器对象转换为列表以进行调试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用IPython在Python中进行调试时,有时会遇到断点,并且我想检查当前是生成器的变量.我可以想到的最简单的方法是将其转换为列表,但是由于在Python中还很陌生,因此我不清楚在ipdb的一行中执行此操作的简单方法.

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.

推荐答案

只需在生成器上调用list.

lst = list(gen)
lst

请注意,这会影响生成器,生成器将不会再返回任何其他项.

Be aware that this affects the generator which will not return any further items.

您也不能直接在IPython中调用list,因为它与列出代码行的命令冲突.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

对此文件进行了测试:

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.

转义函数/变量/调试器名称冲突的常规方法

有调试器命令ppp将在它们之后的printprettyprint任何表达式.

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.

因此您可以按以下方式使用它:

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

还有一个exec命令,通过在表达式的前面加上!来调用该命令,这会强制调试器将您的表达式作为Python.

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

有关更多详细信息,请参见在调试器中的help phelp pphelp exec.

For more details see help p, help pp and help exec when in debugger.

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']

这篇关于将生成器对象转换为列表以进行调试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆