[docs] asyncio: example for shield and readexactly
Dietmar Schwertberger
maillist at schwertberger.de
Wed Aug 6 19:28:42 CEST 2014
Hi!
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
while True:
try:
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(
asyncio.shield(readexactly_task), 2.0)
readexactly_task = None # task has finished
if not rx:
break # EOF met
except asyncio.TimeoutError:
# asyncio.wait_for was canceled
# the task readexactly_task is still alive
rx = None
if rx:
# process the received bytes
print(rx)
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
been easier...
Regards,
Dietmar
More information about the docs
mailing list