W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
This module implements a IterIO that converts an iterator intoa stream object and the other way round. Converting streams intoiterators requires the greenlet module.
To convert an iterator into a stream all you have to do is to pass itdirectly to the IterIO constructor. In this example we pass ita newly created generator:
def foo():
yield "something\n"
yield "otherthings"
stream = IterIO(foo())
print stream.read() # read the whole iterator
The other way round works a bit different because we have to ensure thatthe code execution doesn't take place yet. An IterIO call with acallable as first argument does two things. The function itself is passedan IterIO stream it can feed. The object returned by theIterIO constructor on the other hand is not an stream object butan iterator:
def foo(stream):
stream.write("some")
stream.write("thing")
stream.flush()
stream.write("otherthing")
iterator = IterIO(foo)
print iterator.next() # prints something
print iterator.next() # prints otherthing
iterator.next() # raises StopIteration
class werkzeug.contrib.iterio.IterIO
Instances of this object implement an interface compatible with thestandard Python file object. Streams are either read-only orwrite-only depending on how the object is created.
If the first argument is an iterable a file like object is returned thatreturns the contents of the iterable. In case the iterable is emptyread operations will return the sentinel value.
If the first argument is a callable then the stream object will becreated and passed to that function. The caller itself however willnot receive a stream but an iterable. The function will be be executedstep by step as something iterates over the returned iterable. Eachcall to flush() will create an item for the iterable. Ifflush() is called without any writes in-between the sentinelvalue will be yielded.
Note for Python 3: due to the incompatible interface of bytes andstreams you should set the sentinel value explicitly to an emptybytestring (b'') if you are expecting to deal with bytes asotherwise the end of the stream is marked with the wrong sentinelvalue.
0.9 新版功能: sentinel parameter was added.
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: