中断发电机后的StopIteration错误

时间:2016-04-28 16:09:09

标签: python-2.7 generator

我试图一次读取一个块的二进制文件。每次生成器都会产生1024字节的数据。当我想停止时,我用.send调用发生器('停止')。我得到了正确的输出,但我得到了一个例外。我做错了什么或者预计在这种情况下如何处理?

def read_epoch_from_file(filename,size=1024):
    with open(filename, "rb") as f:
        while True:
            read_data = f.read(size)
            if read_data:
                y = yield read_data
                if y == 'Stop':
                    print 'Stopped'
                    break
            else:
                break
        print 'End'
        f.close()
        return

gen = read_epoch_from_file("Test")
readdata_ascii = next(gen)
#do somthing
readdata_ascii = next(gen)
#do somthing
readdata_ascii = next(gen)
#do somthing
gen.send('Stop')

看到输出

Stopped
End

Traceback (most recent call last):
  File "C:\CVS sandbox\Mandela2\Extractor\binary_parser.py", line 50, in <module>
    gen.send('Stop')
StopIteration

1 个答案:

答案 0 :(得分:0)

根据我的理解,当没有剩余StopIteration值时,yield始终由生成器生成。此异常通常在for循环内自动使用。在我的情况下,异常会冒出来,直到我有一个try/except语句块来处理它。下面是我用来处理这个异常的代码。如果这不是最好的方法,请告诉我。

try:
    gen = read_epoch_from_file("Test")
    readdata_ascii = next(gen)
    #do somthing
    readdata_ascii = next(gen)
    #do somthing
    readdata_ascii = next(gen)
    #do somthing
    gen.send('Stop')
except StopIteration:
    pass
finally:
    del gen