【发布时间】:2015-01-03 14:41:19
【问题描述】:
我不清楚在 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。
【问题讨论】:
标签: python