GeneratorExit in while循环

Eri*_*ric 6 python

我不清楚在while循环中捕获GeneratorExit的行为,这是我的代码:

# python 
Python 2.6.6 (r266:84292, Sep  4 2013, 07:46:00) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def func():
...     while True:
...         try:
...             yield 9
...         except GeneratorExit:
...             print "Need to do some clean up."
... 
>>> g = func()
>>> g.next()
9
>>> g.close()
Need to do some clean up.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: generator ignored GeneratorExit
Run Code Online (Sandbox Code Playgroud)

它出现时g.close()被调用,GeneratorExit被逮住,因为"需要做一些清理." 打印,但我不明白为什么会有RuntimeError.

Job*_*obs 11

"它出现时g.close()被调用,GeneratorExit被逮住"

是的,当调用生成器的close()方法时会引发GeneratorExit.

请参阅以下文档:

https://docs.python.org/2/library/exceptions.html

异常将导致RuntimeError

在循环内部引发上述异常后,实际处理它,并且您看到打印的错误消息.但是,循环继续,它仍然试图产生9.那就是当你看到RuntimeError时.因此,在循环外部移动异常处理可以解决问题.


nes*_*dis 7

只需return在打印后添加一条语句即可"Need to do some clean up."。然后一切正常:)。这是首选方式,尤其是当您无法将异常移出时

while True:
    try:
        yield 9
     except GeneratorExit:
        print "Need to do some clean up."
        return
Run Code Online (Sandbox Code Playgroud)