2016-04-28 2 views
-1

一度にバイナリファイルをチャンクとして読み込もうとしています。ジェネレータは毎回1024バイトのデータを要求します。私が停止したいときは、.send( 'Stop')でジェネレータを呼び出します。私は出力を正しく取得しますが、例外が発生します。私は何か間違っているのですか、これがどのような場合にこれをどう扱うのでしょうか?左これ以上yield値が存在しない場合に私の理解からジェネレータを中断した後のStopIterationエラー

Stopped 
End 

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

答えて

0

を見

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') 

出力はStopIterationは常に発生器によって生成されます。この例外は通常、ループ内で自動的に消費されます(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