Python生成器中的GeneratorExit [英] GeneratorExit in Python generator
问题描述
我写了一个关于Python生成器的测试程序.但是我得到了一个意料之外的错误.而且我不知道该怎么解释.让我向您展示代码:
I wrote a test program about Python generator. But I got an error that is not expected. And I don't know how to explain it. Let me show you the code:
def countdown(n):
logging.debug("Counting down")
while n > 0:
try:
yield n
except GeneratorExit:
logging.error("GeneratorExit")
n -= 1
if __name__ == '__main__':
c = countdown(10)
logging.debug("value: %d", c.next())
我认为它应该可以正常运行.但是输出是:
I thought it should run without any problem. But the output is:
# ./test.py
[2015/06/16 04:10:49] DEBUG - Counting down
[2015/06/16 04:10:49] DEBUG - value: 10
[2015/06/16 04:10:49] ERROR - GeneratorExit
Exception RuntimeError: 'generator ignored GeneratorExit' in <generator object countdown at 0x7f9934407640> ignored
为什么最后一行出现错误.我不知道为什么触发了GeneratorExit异常.我错过了发电机吗?我也将代码输入到交互式python shell中,一切正常.这怎么会发生?
Why is there an error at the last line. I don't know why I triggered the GeneratorExit exception. Is there something aobut generator I missed? I also typed the code into interactive python shell, and everything is OK. How can this happen?
推荐答案
假设您具有以下生成器:
Suppose you have the following generator:
def gen():
with open('important_file') as f:
for line in f:
yield line
然后您next
将其丢弃一次:
g = gen()
next(g)
del g
生成器的控制流从不离开with
块,因此不会关闭文件.为了防止这种情况,当生成器被垃圾回收时,Python调用其close
方法,该方法在生成器最后一次yield
的生成点引发GeneratorExit
异常.此异常旨在触发所有没有机会运行的finally
块或上下文管理器__exit__
.
The generator's control flow never leaves the with
block, so the file doesn't get closed. To prevent this, when a generator is garbage-collected, Python calls its close
method, which raises a GeneratorExit
exception at the point from which the generator last yield
ed. This exception is intended to trigger any finally
blocks or context manager __exit__
s that didn't get a chance to run.
当您抓住GeneratorExit
并继续前进时,Python会看到生成器未正确退出.由于这可能表明资源未正确释放,因此Python将其报告为RuntimeError.
When you catch the GeneratorExit
and keep going, Python sees that the generator didn't exit properly. Since that can indicate that resources weren't properly released, Python reports this as a RuntimeError.
这篇关于Python生成器中的GeneratorExit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!