gpt4 book ai didi

python - while 循环中的 GeneratorExit

转载 作者:太空狗 更新时间:2023-10-29 22:05:37 24 4
gpt4 key购买 nike

我不清楚在 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

它出现在调用 g.close() 时,GeneratorExit 被捕获,因为“需要做一些清理工作”。已打印,但我不明白为什么会出现 RuntimeError。

最佳答案

“调用g.close()时出现,GeneratorExit被捕获”

是的,GeneratorExit 在调用生成器的 close() 方法时引发。

请参阅以下文档:

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

异常会引发RuntimeError

在循环内部引发上述异常后,它实际上被处理了,您会看到打印的错误消息。但是,循环继续,它仍然尝试产生 9。这就是您看到 RuntimeError 的时候。因此,将异常处理移到循环之外可以解决问题。

关于python - while 循环中的 GeneratorExit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27755989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com