这是应该从迭代器中分批读取的解决方案。
class some_magic_adaptor: def __init__( self, it ): self.it = it self.next_chunk = "" def growChunk( self ): self.next_chunk = self.next_chunk + self.it.next() def read( self, n ): if self.next_chunk == None: return None try: while len(self.next_chunk)<n: self.growChunk() rv = self.next_chunk[:n] self.next_chunk = self.next_chunk[n:] return rv except StopIteration: rv = self.next_chunk self.next_chunk = None return rvdef str_fn(): for c in 'a', 'b', 'c': yield c * 3ff = some_magic_adaptor( str_fn() )while True: data = ff.read(4) if not data: break print data



