Python调试器能调试生成器吗?

8 投票
2 回答
2763 浏览
提问于 2025-04-17 11:19

我现在在用 NetBeans IDE 和 Jython 2.5.1。

在逐步调试我的项目时,一旦遇到生成器的循环,调试器就会直接跳到代码的最后。输出结果是正常的,但一旦遇到第一个生成器,就无法再逐步调试了。

这种情况是所有 Python IDE 中调试的标准行为吗?难道不能像在 VBA 中那样逐个调试“for”循环中的每个元素吗(抱歉提到 VBA :)?

谢谢。

编辑

没有生成器的情况

代码:

def example(n):
i = 1
while i <= n:
    yield i
    i += 1

print "hello"

print "goodbye"

输出:

hello
goodbye

调试:

[LOG]PythonDebugger : overall Starting
[LOG]PythonDebugger.taskStarted : I am Starting a new Debugging Session ...
[LOG]This window is an interactive debugging context aware Python Shell 
[LOG]where you can enter python console commands while debugging 

(...)

>>>[stdout:]hello
>>>[stdout:]goodbye
Debug session normal end

有生成器的情况

代码:

def example(n):
    i = 1
    while i <= n:
        yield i
        i += 1

print "hello"

for n in example(3):
    print n

print "goodbye"

输出:

hello
1
2
3
goodbye

调试:

[LOG]PythonDebugger : overall Starting
[LOG]PythonDebugger.taskStarted : I am Starting a new Debugging Session ...
[LOG]This window is an interactive debugging context aware Python Shell 
[LOG]where you can enter python console commands while debugging 

(...)

>>>[stdout:]hello
>>>None['GeneratorExit
deamon ended
']

Debug session normal end

2 个回答

2

我不使用NetBeans,但至少pdb可以逐步调试生成器。举个例子:

$ cat test.py
def the_generator():
    for i in xrange(10):
        yield i

for x in the_generator():
    print x

$ python -mpdb test.py
> test.py(1)<module>()
-> def the_generator():
(Pdb) n
> test.py(5)<module>()
-> for x in the_generator():
(Pdb) s
--Call--
> test.py(1)the_generator()
-> def the_generator():
(Pdb) n
> test.py(2)the_generator()
-> for i in xrange(10):
(Pdb) n
> test.py(3)the_generator()
-> yield i
(Pdb) n
--Return--
> test.py(3)the_generator()->0
-> yield i
(Pdb) n
> test.py(6)<module>()
-> print x
(Pdb) n
0

如果你发一些代码过来,我们可以一起看看你遇到的问题到底是什么。

1

我刚刚测试了一下Eclipse,发现它可以在安装了pydev的情况下进行调试。

撰写回答