- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我不清楚在 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/
例如, In [33]: def gener(): ...: try: ...: print('hi') ...: yield 1 ...:
我有以下 mcve : import logging class MyGenIt(object): def __init__(self, name, content): sel
我不清楚在 while 循环中捕获 GeneratorExit 的行为,这是我的代码: # python Python 2.6.6 (r266:84292, Sep 4 2013, 07:46:00
我写了一个关于 Python 生成器的测试程序。但是我得到了一个意想不到的错误。我不知道如何解释。让我向您展示代码: def countdown(n): logging.debug("Coun
def receiver(): print("Ready to receive") # try: while True: n = (yield) p
我查看了内置 python 异常的层次结构,我注意到 StopIteration 和 GeneratorExit 有不同的基类: BaseException +-- SystemExit +--
感谢您提出我的问题。我试着把我的问题说清楚,但如果因为我的英语还有不清楚的地方,请告诉我。 我正在研究 Python 协同程序,并且读到在生成器上调用 close() 方法类似于将 Generator
我是一名优秀的程序员,十分优秀!