[docs] asyncio: example for shield and readexactly
maillist at schwertberger.de
Wed Aug 6 19:28:42 CEST 2014
I've recently started using asyncio.
My usage includes code which reads two bytes, but with a timeout.
My naive approach was:
rx = yield from asyncio.wait_for( reader.readexactly(2), 2.0)
But of course this does not work as it could lose a byte if exactly
one byte hasbeen received when the timeout was met.
For asyncio beginners it's not obvious how to fix that and especially
how to use shield().
My code now looks something like that:
readexactly_task = None
if readexactly_task is None:
# create a task to receive two bytes
readexactly_task = asyncio.Task( reader.readexactly(2) )
# give the task two seconds to complete
# shield it not to be canceled on timeout
rx = yield from asyncio.wait_for(
readexactly_task = None # task has finished
if not rx:
break # EOF met
# asyncio.wait_for was canceled
# the task readexactly_task is still alive
rx = None
# process the received bytes
I think that it would be helpful to have such an example in the
documentation for both
StreamReader and shield.
Of course, if readexactly had an argument 'timeout' things would have
More information about the docs